/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/tests/__init__.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-04 19:17:13 UTC
  • mfrom: (0.193.10 trunk)
  • mto: This revision was merged to the branch mainline in revision 6778.
  • Revision ID: jelmer@jelmer.uk-20170604191713-hau7dfsqsl035slm
Bundle the cvs plugin.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2013, 2015, 2016 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
16
16
 
17
17
"""Testing framework extensions"""
18
18
 
19
 
# TODO: Perhaps there should be an API to find out if bzr running under the
20
 
# test suite -- some plugins might want to avoid making intrusive changes if
21
 
# this is the case.  However, we want behaviour under to test to diverge as
22
 
# little as possible, so this should be used rarely if it's added at all.
23
 
# (Suggestion from j-a-meinel, 2005-11-24)
 
19
from __future__ import absolute_import
24
20
 
25
21
# NOTE: Some classes in here use camelCaseNaming() rather than
26
22
# underscore_naming().  That's for consistency with unittest; it's not the
27
 
# general style of bzrlib.  Please continue that consistency when adding e.g.
 
23
# general style of breezy.  Please continue that consistency when adding e.g.
28
24
# new assertFoo() methods.
29
25
 
30
26
import atexit
31
27
import codecs
32
 
from copy import copy
33
 
from cStringIO import StringIO
 
28
import copy
34
29
import difflib
35
30
import doctest
36
31
import errno
 
32
import itertools
37
33
import logging
38
34
import math
39
35
import os
40
 
from pprint import pformat
 
36
import platform
 
37
import pprint
41
38
import random
42
39
import re
43
40
import shlex
 
41
import site
44
42
import stat
45
 
from subprocess import Popen, PIPE, STDOUT
 
43
import subprocess
46
44
import sys
47
45
import tempfile
48
46
import threading
54
52
import testtools
55
53
# nb: check this before importing anything else from within it
56
54
_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"
 
55
if _testtools_version < (0, 9, 5):
 
56
    raise ImportError("need at least testtools 0.9.5: %s is %r"
59
57
        % (testtools.__file__, _testtools_version))
60
58
from testtools import content
61
59
 
62
 
from bzrlib import (
 
60
import breezy
 
61
from .. import (
63
62
    branchbuilder,
64
 
    bzrdir,
 
63
    controldir,
65
64
    chk_map,
 
65
    commands as _mod_commands,
66
66
    config,
 
67
    i18n,
67
68
    debug,
68
69
    errors,
69
70
    hooks,
70
71
    lock as _mod_lock,
 
72
    lockdir,
71
73
    memorytree,
72
74
    osutils,
73
 
    progress,
 
75
    plugin as _mod_plugin,
 
76
    pyutils,
74
77
    ui,
75
78
    urlutils,
76
79
    registry,
 
80
    symbol_versioning,
 
81
    trace,
 
82
    transport as _mod_transport,
77
83
    workingtree,
78
84
    )
79
 
import bzrlib.branch
80
 
import bzrlib.commands
81
 
import bzrlib.timestamp
82
 
import bzrlib.export
83
 
import bzrlib.inventory
84
 
import bzrlib.iterablefile
85
 
import bzrlib.lockdir
86
85
try:
87
 
    import bzrlib.lsprof
 
86
    import breezy.lsprof
88
87
except ImportError:
89
88
    # lsprof not available
90
89
    pass
91
 
from bzrlib.merge import merge_inner
92
 
import bzrlib.merge3
93
 
import bzrlib.plugin
94
 
from bzrlib.smart import client, request, server
95
 
import bzrlib.store
96
 
from bzrlib import symbol_versioning
97
 
from bzrlib.symbol_versioning import (
98
 
    DEPRECATED_PARAMETER,
99
 
    deprecated_function,
100
 
    deprecated_in,
101
 
    deprecated_method,
102
 
    deprecated_passed,
 
90
from ..sixish import (
 
91
    BytesIO,
 
92
    string_types,
 
93
    text_type,
103
94
    )
104
 
import bzrlib.trace
105
 
from bzrlib.transport import (
106
 
    get_transport,
 
95
from ..smart import client, request
 
96
from ..transport import (
107
97
    memory,
108
98
    pathfilter,
109
99
    )
110
 
import bzrlib.transport
111
 
from bzrlib.trace import mutter, note
112
 
from bzrlib.tests import (
 
100
from ..tests import (
 
101
    fixtures,
113
102
    test_server,
114
103
    TestUtil,
115
104
    treeshape,
 
105
    ui_testing,
116
106
    )
117
 
from bzrlib.tests.http_server import HttpServer
118
 
from bzrlib.tests.TestUtil import (
119
 
                          TestSuite,
120
 
                          TestLoader,
121
 
                          )
122
 
from bzrlib.ui import NullProgressView
123
 
from bzrlib.ui.text import TextUIFactory
124
 
import bzrlib.version_info_formats.format_custom
125
 
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
 
107
from ..tests.features import _CompatabilityThunkFeature
126
108
 
127
109
# Mark this python module as being part of the implementation
128
110
# of unittest: this gives us better tracebacks where the last
140
122
SUBUNIT_SEEK_SET = 0
141
123
SUBUNIT_SEEK_CUR = 1
142
124
 
143
 
 
144
 
class ExtendedTestResult(unittest._TextTestResult):
 
125
# These are intentionally brought into this namespace. That way plugins, etc
 
126
# can just "from breezy.tests import TestCase, TestLoader, etc"
 
127
TestSuite = TestUtil.TestSuite
 
128
TestLoader = TestUtil.TestLoader
 
129
 
 
130
# Tests should run in a clean and clearly defined environment. The goal is to
 
131
# keep them isolated from the running environment as mush as possible. The test
 
132
# framework ensures the variables defined below are set (or deleted if the
 
133
# value is None) before a test is run and reset to their original value after
 
134
# the test is run. Generally if some code depends on an environment variable,
 
135
# the tests should start without this variable in the environment. There are a
 
136
# few exceptions but you shouldn't violate this rule lightly.
 
137
isolated_environ = {
 
138
    'BRZ_HOME': None,
 
139
    'HOME': None,
 
140
    'XDG_CONFIG_HOME': None,
 
141
    # brz now uses the Win32 API and doesn't rely on APPDATA, but the
 
142
    # tests do check our impls match APPDATA
 
143
    'BRZ_EDITOR': None, # test_msgeditor manipulates this variable
 
144
    'VISUAL': None,
 
145
    'EDITOR': None,
 
146
    'BRZ_EMAIL': None,
 
147
    'BZREMAIL': None, # may still be present in the environment
 
148
    'EMAIL': 'jrandom@example.com', # set EMAIL as brz does not guess
 
149
    'BRZ_PROGRESS_BAR': None,
 
150
    # This should trap leaks to ~/.brz.log. This occurs when tests use TestCase
 
151
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
 
152
    # TestCase should not use disk resources, BRZ_LOG is one.
 
153
    'BRZ_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
154
    'BRZ_PLUGIN_PATH': None,
 
155
    'BRZ_DISABLE_PLUGINS': None,
 
156
    'BRZ_PLUGINS_AT': None,
 
157
    'BRZ_CONCURRENCY': None,
 
158
    # Make sure that any text ui tests are consistent regardless of
 
159
    # the environment the test case is run in; you may want tests that
 
160
    # test other combinations.  'dumb' is a reasonable guess for tests
 
161
    # going to a pipe or a BytesIO.
 
162
    'TERM': 'dumb',
 
163
    'LINES': '25',
 
164
    'COLUMNS': '80',
 
165
    'BRZ_COLUMNS': '80',
 
166
    # Disable SSH Agent
 
167
    'SSH_AUTH_SOCK': None,
 
168
    # Proxies
 
169
    'http_proxy': None,
 
170
    'HTTP_PROXY': None,
 
171
    'https_proxy': None,
 
172
    'HTTPS_PROXY': None,
 
173
    'no_proxy': None,
 
174
    'NO_PROXY': None,
 
175
    'all_proxy': None,
 
176
    'ALL_PROXY': None,
 
177
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
178
    # least. If you do (care), please update this comment
 
179
    # -- vila 20080401
 
180
    'ftp_proxy': None,
 
181
    'FTP_PROXY': None,
 
182
    'BZR_REMOTE_PATH': None,
 
183
    # Generally speaking, we don't want apport reporting on crashes in
 
184
    # the test envirnoment unless we're specifically testing apport,
 
185
    # so that it doesn't leak into the real system environment.  We
 
186
    # use an env var so it propagates to subprocesses.
 
187
    'APPORT_DISABLE': '1',
 
188
    }
 
189
 
 
190
 
 
191
def override_os_environ(test, env=None):
 
192
    """Modify os.environ keeping a copy.
 
193
    
 
194
    :param test: A test instance
 
195
 
 
196
    :param env: A dict containing variable definitions to be installed
 
197
    """
 
198
    if env is None:
 
199
        env = isolated_environ
 
200
    test._original_os_environ = dict(**os.environ)
 
201
    for var in env:
 
202
        osutils.set_or_unset_env(var, env[var])
 
203
        if var not in test._original_os_environ:
 
204
            # The var is new, add it with a value of None, so
 
205
            # restore_os_environ will delete it
 
206
            test._original_os_environ[var] = None
 
207
 
 
208
 
 
209
def restore_os_environ(test):
 
210
    """Restore os.environ to its original state.
 
211
 
 
212
    :param test: A test instance previously passed to override_os_environ.
 
213
    """
 
214
    for var, value in test._original_os_environ.items():
 
215
        # Restore the original value (or delete it if the value has been set to
 
216
        # None in override_os_environ).
 
217
        osutils.set_or_unset_env(var, value)
 
218
 
 
219
 
 
220
def _clear__type_equality_funcs(test):
 
221
    """Cleanup bound methods stored on TestCase instances
 
222
 
 
223
    Clear the dict breaking a few (mostly) harmless cycles in the affected
 
224
    unittests released with Python 2.6 and initial Python 2.7 versions.
 
225
 
 
226
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
 
227
    shipped in Oneiric, an object with no clear method was used, hence the
 
228
    extra complications, see bug 809048 for details.
 
229
    """
 
230
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
231
    if type_equality_funcs is not None:
 
232
        tef_clear = getattr(type_equality_funcs, "clear", None)
 
233
        if tef_clear is None:
 
234
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
 
235
            if tef_instance_dict is not None:
 
236
                tef_clear = tef_instance_dict.clear
 
237
        if tef_clear is not None:
 
238
            tef_clear()
 
239
 
 
240
 
 
241
class ExtendedTestResult(testtools.TextTestResult):
145
242
    """Accepts, reports and accumulates the results of running tests.
146
243
 
147
244
    Compared to the unittest version this class adds support for
150
247
    different types of display.
151
248
 
152
249
    When a test finishes, in whatever way, it calls one of the addSuccess,
153
 
    addFailure or addError classes.  These in turn may redirect to a more
 
250
    addFailure or addError methods.  These in turn may redirect to a more
154
251
    specific case for the special test results supported by our extended
155
252
    tests.
156
253
 
168
265
        :param bench_history: Optionally, a writable file object to accumulate
169
266
            benchmark results.
170
267
        """
171
 
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
268
        testtools.TextTestResult.__init__(self, stream)
172
269
        if bench_history is not None:
173
 
            from bzrlib.version import _get_bzr_source_tree
 
270
            from breezy.version import _get_bzr_source_tree
174
271
            src_tree = _get_bzr_source_tree()
175
272
            if src_tree:
176
273
                try:
195
292
        self.count = 0
196
293
        self._overall_start_time = time.time()
197
294
        self._strict = strict
 
295
        self._first_thread_leaker_id = None
 
296
        self._tests_leaking_threads_count = 0
 
297
        self._traceback_from_test = None
198
298
 
199
299
    def stopTestRun(self):
200
300
        run = self.testsRun
201
301
        actionTaken = "Ran"
202
302
        stopTime = time.time()
203
303
        timeTaken = stopTime - self.startTime
204
 
        self.printErrors()
205
 
        self.stream.writeln(self.separator2)
206
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
304
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
 
305
        #                the parent class method is similar have to duplicate
 
306
        self._show_list('ERROR', self.errors)
 
307
        self._show_list('FAIL', self.failures)
 
308
        self.stream.write(self.sep2)
 
309
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
207
310
                            run, run != 1 and "s" or "", timeTaken))
208
 
        self.stream.writeln()
209
311
        if not self.wasSuccessful():
210
312
            self.stream.write("FAILED (")
211
313
            failed, errored = map(len, (self.failures, self.errors))
218
320
                if failed or errored: self.stream.write(", ")
219
321
                self.stream.write("known_failure_count=%d" %
220
322
                    self.known_failure_count)
221
 
            self.stream.writeln(")")
 
323
            self.stream.write(")\n")
222
324
        else:
223
325
            if self.known_failure_count:
224
 
                self.stream.writeln("OK (known_failures=%d)" %
 
326
                self.stream.write("OK (known_failures=%d)\n" %
225
327
                    self.known_failure_count)
226
328
            else:
227
 
                self.stream.writeln("OK")
 
329
                self.stream.write("OK\n")
228
330
        if self.skip_count > 0:
229
331
            skipped = self.skip_count
230
 
            self.stream.writeln('%d test%s skipped' %
 
332
            self.stream.write('%d test%s skipped\n' %
231
333
                                (skipped, skipped != 1 and "s" or ""))
232
334
        if self.unsupported:
233
335
            for feature, count in sorted(self.unsupported.items()):
234
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
336
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
235
337
                    (feature, count))
236
338
        if self._strict:
237
339
            ok = self.wasStrictlySuccessful()
238
340
        else:
239
341
            ok = self.wasSuccessful()
240
 
        if TestCase._first_thread_leaker_id:
 
342
        if self._first_thread_leaker_id:
241
343
            self.stream.write(
242
344
                '%s is leaking threads among %d leaking tests.\n' % (
243
 
                TestCase._first_thread_leaker_id,
244
 
                TestCase._leaking_threads_tests))
 
345
                self._first_thread_leaker_id,
 
346
                self._tests_leaking_threads_count))
245
347
            # We don't report the main thread as an active one.
246
348
            self.stream.write(
247
349
                '%d non-main threads were left active in the end.\n'
248
 
                % (TestCase._active_threads - 1))
 
350
                % (len(self._active_threads) - 1))
249
351
 
250
352
    def getDescription(self, test):
251
353
        return test.id()
256
358
            return float(''.join(details['benchtime'].iter_bytes()))
257
359
        return getattr(testCase, "_benchtime", None)
258
360
 
 
361
    def _delta_to_float(self, a_timedelta, precision):
 
362
        # This calls ceiling to ensure that the most pessimistic view of time
 
363
        # taken is shown (rather than leaving it to the Python %f operator
 
364
        # to decide whether to round/floor/ceiling. This was added when we
 
365
        # had pyp3 test failures that suggest a floor was happening.
 
366
        shift = 10 ** precision
 
367
        return math.ceil((a_timedelta.days * 86400.0 + a_timedelta.seconds +
 
368
            a_timedelta.microseconds / 1000000.0) * shift) / shift
 
369
 
259
370
    def _elapsedTestTimeString(self):
260
371
        """Return a time string for the overall time the current test has taken."""
261
 
        return self._formatTime(time.time() - self._start_time)
 
372
        return self._formatTime(self._delta_to_float(
 
373
            self._now() - self._start_datetime, 3))
262
374
 
263
375
    def _testTimeString(self, testCase):
264
376
        benchmark_time = self._extractBenchmarkTime(testCase)
275
387
 
276
388
    def _shortened_test_description(self, test):
277
389
        what = test.id()
278
 
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
390
        what = re.sub(r'^breezy\.tests\.', '', what)
279
391
        return what
280
392
 
 
393
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
394
    #                multiple times in a row, because the handler is added for
 
395
    #                each test but the container list is shared between cases.
 
396
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
397
    def _record_traceback_from_test(self, exc_info):
 
398
        """Store the traceback from passed exc_info tuple till"""
 
399
        self._traceback_from_test = exc_info[2]
 
400
 
281
401
    def startTest(self, test):
282
 
        unittest.TestResult.startTest(self, test)
 
402
        super(ExtendedTestResult, self).startTest(test)
283
403
        if self.count == 0:
284
404
            self.startTests()
 
405
        self.count += 1
285
406
        self.report_test_start(test)
286
407
        test.number = self.count
287
408
        self._recordTestStartTime()
 
409
        # Make testtools cases give us the real traceback on failure
 
410
        addOnException = getattr(test, "addOnException", None)
 
411
        if addOnException is not None:
 
412
            addOnException(self._record_traceback_from_test)
 
413
        # Only check for thread leaks on breezy derived test cases
 
414
        if isinstance(test, TestCase):
 
415
            test.addCleanup(self._check_leaked_threads, test)
 
416
 
 
417
    def stopTest(self, test):
 
418
        super(ExtendedTestResult, self).stopTest(test)
 
419
        # Manually break cycles, means touching various private things but hey
 
420
        getDetails = getattr(test, "getDetails", None)
 
421
        if getDetails is not None:
 
422
            getDetails().clear()
 
423
        _clear__type_equality_funcs(test)
 
424
        self._traceback_from_test = None
288
425
 
289
426
    def startTests(self):
290
 
        import platform
291
 
        if getattr(sys, 'frozen', None) is None:
292
 
            bzr_path = osutils.realpath(sys.argv[0])
293
 
        else:
294
 
            bzr_path = sys.executable
295
 
        self.stream.write(
296
 
            'bzr selftest: %s\n' % (bzr_path,))
297
 
        self.stream.write(
298
 
            '   %s\n' % (
299
 
                    bzrlib.__path__[0],))
300
 
        self.stream.write(
301
 
            '   bzr-%s python-%s %s\n' % (
302
 
                    bzrlib.version_string,
303
 
                    bzrlib._format_version_tuple(sys.version_info),
304
 
                    platform.platform(aliased=1),
305
 
                    ))
306
 
        self.stream.write('\n')
 
427
        self.report_tests_starting()
 
428
        self._active_threads = threading.enumerate()
 
429
 
 
430
    def _check_leaked_threads(self, test):
 
431
        """See if any threads have leaked since last call
 
432
 
 
433
        A sample of live threads is stored in the _active_threads attribute,
 
434
        when this method runs it compares the current live threads and any not
 
435
        in the previous sample are treated as having leaked.
 
436
        """
 
437
        now_active_threads = set(threading.enumerate())
 
438
        threads_leaked = now_active_threads.difference(self._active_threads)
 
439
        if threads_leaked:
 
440
            self._report_thread_leak(test, threads_leaked, now_active_threads)
 
441
            self._tests_leaking_threads_count += 1
 
442
            if self._first_thread_leaker_id is None:
 
443
                self._first_thread_leaker_id = test.id()
 
444
            self._active_threads = now_active_threads
307
445
 
308
446
    def _recordTestStartTime(self):
309
447
        """Record that a test has started."""
310
 
        self._start_time = time.time()
311
 
 
312
 
    def _cleanupLogFile(self, test):
313
 
        # We can only do this if we have one of our TestCases, not if
314
 
        # we have a doctest.
315
 
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
316
 
        if setKeepLogfile is not None:
317
 
            setKeepLogfile()
 
448
        self._start_datetime = self._now()
318
449
 
319
450
    def addError(self, test, err):
320
451
        """Tell result that test finished with an error.
322
453
        Called from the TestCase run() method when the test
323
454
        fails with an unexpected error.
324
455
        """
325
 
        self._post_mortem()
326
 
        unittest.TestResult.addError(self, test, err)
 
456
        self._post_mortem(self._traceback_from_test)
 
457
        super(ExtendedTestResult, self).addError(test, err)
327
458
        self.error_count += 1
328
459
        self.report_error(test, err)
329
460
        if self.stop_early:
330
461
            self.stop()
331
 
        self._cleanupLogFile(test)
332
462
 
333
463
    def addFailure(self, test, err):
334
464
        """Tell result that test failed.
336
466
        Called from the TestCase run() method when the test
337
467
        fails because e.g. an assert() method failed.
338
468
        """
339
 
        self._post_mortem()
340
 
        unittest.TestResult.addFailure(self, test, err)
 
469
        self._post_mortem(self._traceback_from_test)
 
470
        super(ExtendedTestResult, self).addFailure(test, err)
341
471
        self.failure_count += 1
342
472
        self.report_failure(test, err)
343
473
        if self.stop_early:
344
474
            self.stop()
345
 
        self._cleanupLogFile(test)
346
475
 
347
476
    def addSuccess(self, test, details=None):
348
477
        """Tell result that test completed successfully.
356
485
                    self._formatTime(benchmark_time),
357
486
                    test.id()))
358
487
        self.report_success(test)
359
 
        self._cleanupLogFile(test)
360
 
        unittest.TestResult.addSuccess(self, test)
 
488
        super(ExtendedTestResult, self).addSuccess(test)
361
489
        test._log_contents = ''
362
490
 
363
491
    def addExpectedFailure(self, test, err):
364
492
        self.known_failure_count += 1
365
493
        self.report_known_failure(test, err)
366
494
 
 
495
    def addUnexpectedSuccess(self, test, details=None):
 
496
        """Tell result the test unexpectedly passed, counting as a failure
 
497
 
 
498
        When the minimum version of testtools required becomes 0.9.8 this
 
499
        can be updated to use the new handling there.
 
500
        """
 
501
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
502
        self.failure_count += 1
 
503
        self.report_unexpected_success(test,
 
504
            "".join(details["reason"].iter_text()))
 
505
        if self.stop_early:
 
506
            self.stop()
 
507
 
367
508
    def addNotSupported(self, test, feature):
368
509
        """The test will not be run because of a missing feature.
369
510
        """
386
527
        self.not_applicable_count += 1
387
528
        self.report_not_applicable(test, reason)
388
529
 
389
 
    def _post_mortem(self):
 
530
    def _count_stored_tests(self):
 
531
        """Count of tests instances kept alive due to not succeeding"""
 
532
        return self.error_count + self.failure_count + self.known_failure_count
 
533
 
 
534
    def _post_mortem(self, tb=None):
390
535
        """Start a PDB post mortem session."""
391
 
        if os.environ.get('BZR_TEST_PDB', None):
392
 
            import pdb;pdb.post_mortem()
 
536
        if os.environ.get('BRZ_TEST_PDB', None):
 
537
            import pdb
 
538
            pdb.post_mortem(tb)
393
539
 
394
540
    def progress(self, offset, whence):
395
541
        """The test is adjusting the count of tests to run."""
400
546
        else:
401
547
            raise errors.BzrError("Unknown whence %r" % whence)
402
548
 
403
 
    def report_cleaning_up(self):
404
 
        pass
 
549
    def report_tests_starting(self):
 
550
        """Display information before the test run begins"""
 
551
        if getattr(sys, 'frozen', None) is None:
 
552
            bzr_path = osutils.realpath(sys.argv[0])
 
553
        else:
 
554
            bzr_path = sys.executable
 
555
        self.stream.write(
 
556
            'brz selftest: %s\n' % (bzr_path,))
 
557
        self.stream.write(
 
558
            '   %s\n' % (
 
559
                    breezy.__path__[0],))
 
560
        self.stream.write(
 
561
            '   bzr-%s python-%s %s\n' % (
 
562
                    breezy.version_string,
 
563
                    breezy._format_version_tuple(sys.version_info),
 
564
                    platform.platform(aliased=1),
 
565
                    ))
 
566
        self.stream.write('\n')
 
567
 
 
568
    def report_test_start(self, test):
 
569
        """Display information on the test just about to be run"""
 
570
 
 
571
    def _report_thread_leak(self, test, leaked_threads, active_threads):
 
572
        """Display information on a test that leaked one or more threads"""
 
573
        # GZ 2010-09-09: A leak summary reported separately from the general
 
574
        #                thread debugging would be nice. Tests under subunit
 
575
        #                need something not using stream, perhaps adding a
 
576
        #                testtools details object would be fitting.
 
577
        if 'threads' in selftest_debug_flags:
 
578
            self.stream.write('%s is leaking, active is now %d\n' %
 
579
                (test.id(), len(active_threads)))
405
580
 
406
581
    def startTestRun(self):
407
582
        self.startTime = time.time()
444
619
        self.pb.finished()
445
620
        super(TextTestResult, self).stopTestRun()
446
621
 
447
 
    def startTestRun(self):
448
 
        super(TextTestResult, self).startTestRun()
 
622
    def report_tests_starting(self):
 
623
        super(TextTestResult, self).report_tests_starting()
449
624
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
450
625
 
451
 
    def printErrors(self):
452
 
        # clear the pb to make room for the error listing
453
 
        self.pb.clear()
454
 
        super(TextTestResult, self).printErrors()
455
 
 
456
626
    def _progress_prefix_text(self):
457
627
        # the longer this text, the less space we have to show the test
458
628
        # name...
480
650
        return a
481
651
 
482
652
    def report_test_start(self, test):
483
 
        self.count += 1
484
653
        self.pb.update(
485
654
                self._progress_prefix_text()
486
655
                + ' '
504
673
    def report_known_failure(self, test, err):
505
674
        pass
506
675
 
 
676
    def report_unexpected_success(self, test, reason):
 
677
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
 
678
            self._test_description(test),
 
679
            "Unexpected success. Should have failed",
 
680
            reason,
 
681
            ))
 
682
 
507
683
    def report_skip(self, test, reason):
508
684
        pass
509
685
 
513
689
    def report_unsupported(self, test, feature):
514
690
        """test cannot be run because feature is missing."""
515
691
 
516
 
    def report_cleaning_up(self):
517
 
        self.pb.update('Cleaning up')
518
 
 
519
692
 
520
693
class VerboseTestResult(ExtendedTestResult):
521
694
    """Produce long output, with one line per test run plus times"""
528
701
            result = a_string
529
702
        return result.ljust(final_width)
530
703
 
531
 
    def startTestRun(self):
532
 
        super(VerboseTestResult, self).startTestRun()
 
704
    def report_tests_starting(self):
533
705
        self.stream.write('running %d tests...\n' % self.num_tests)
 
706
        super(VerboseTestResult, self).report_tests_starting()
534
707
 
535
708
    def report_test_start(self, test):
536
 
        self.count += 1
537
709
        name = self._shortened_test_description(test)
538
710
        width = osutils.terminal_width()
539
711
        if width is not None:
551
723
        return '%s%s' % (indent, err[1])
552
724
 
553
725
    def report_error(self, test, err):
554
 
        self.stream.writeln('ERROR %s\n%s'
 
726
        self.stream.write('ERROR %s\n%s\n'
555
727
                % (self._testTimeString(test),
556
728
                   self._error_summary(err)))
557
729
 
558
730
    def report_failure(self, test, err):
559
 
        self.stream.writeln(' FAIL %s\n%s'
 
731
        self.stream.write(' FAIL %s\n%s\n'
560
732
                % (self._testTimeString(test),
561
733
                   self._error_summary(err)))
562
734
 
563
735
    def report_known_failure(self, test, err):
564
 
        self.stream.writeln('XFAIL %s\n%s'
 
736
        self.stream.write('XFAIL %s\n%s\n'
565
737
                % (self._testTimeString(test),
566
738
                   self._error_summary(err)))
567
739
 
 
740
    def report_unexpected_success(self, test, reason):
 
741
        self.stream.write(' FAIL %s\n%s: %s\n'
 
742
                % (self._testTimeString(test),
 
743
                   "Unexpected success. Should have failed",
 
744
                   reason))
 
745
 
568
746
    def report_success(self, test):
569
 
        self.stream.writeln('   OK %s' % self._testTimeString(test))
 
747
        self.stream.write('   OK %s\n' % self._testTimeString(test))
570
748
        for bench_called, stats in getattr(test, '_benchcalls', []):
571
 
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
749
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
572
750
            stats.pprint(file=self.stream)
573
751
        # flush the stream so that we get smooth output. This verbose mode is
574
752
        # used to show the output in PQM.
575
753
        self.stream.flush()
576
754
 
577
755
    def report_skip(self, test, reason):
578
 
        self.stream.writeln(' SKIP %s\n%s'
 
756
        self.stream.write(' SKIP %s\n%s\n'
579
757
                % (self._testTimeString(test), reason))
580
758
 
581
759
    def report_not_applicable(self, test, reason):
582
 
        self.stream.writeln('  N/A %s\n    %s'
 
760
        self.stream.write('  N/A %s\n    %s\n'
583
761
                % (self._testTimeString(test), reason))
584
762
 
585
763
    def report_unsupported(self, test, feature):
586
764
        """test cannot be run because feature is missing."""
587
 
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
 
765
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
588
766
                %(self._testTimeString(test), feature))
589
767
 
590
768
 
612
790
        # to encode using ascii.
613
791
        new_encoding = osutils.get_terminal_encoding()
614
792
        codec = codecs.lookup(new_encoding)
615
 
        if type(codec) is tuple:
 
793
        if isinstance(codec, tuple):
616
794
            # Python 2.4
617
795
            encode = codec[0]
618
796
        else:
619
797
            encode = codec.encode
620
 
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream)
 
798
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
799
        #                so should swap to the plain codecs.StreamWriter
 
800
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
801
            "backslashreplace")
621
802
        stream.encoding = new_encoding
622
 
        self.stream = unittest._WritelnDecorator(stream)
 
803
        self.stream = stream
623
804
        self.descriptions = descriptions
624
805
        self.verbosity = verbosity
625
806
        self._bench_history = bench_history
707
888
    """
708
889
 
709
890
 
710
 
class StringIOWrapper(object):
711
 
    """A wrapper around cStringIO which just adds an encoding attribute.
712
 
 
713
 
    Internally we can check sys.stdout to see what the output encoding
714
 
    should be. However, cStringIO has no encoding attribute that we can
715
 
    set. So we wrap it instead.
716
 
    """
717
 
    encoding='ascii'
718
 
    _cstring = None
719
 
 
 
891
class StringIOWrapper(ui_testing.BytesIOWithEncoding):
 
892
 
 
893
    @symbol_versioning.deprecated_method(
 
894
        symbol_versioning.deprecated_in((3, 0)))
720
895
    def __init__(self, s=None):
721
 
        if s is not None:
722
 
            self.__dict__['_cstring'] = StringIO(s)
723
 
        else:
724
 
            self.__dict__['_cstring'] = StringIO()
725
 
 
726
 
    def __getattr__(self, name, getattr=getattr):
727
 
        return getattr(self.__dict__['_cstring'], name)
728
 
 
729
 
    def __setattr__(self, name, val):
730
 
        if name == 'encoding':
731
 
            self.__dict__['encoding'] = val
732
 
        else:
733
 
            return setattr(self._cstring, name, val)
734
 
 
735
 
 
736
 
class TestUIFactory(TextUIFactory):
737
 
    """A UI Factory for testing.
738
 
 
739
 
    Hide the progress bar but emit note()s.
740
 
    Redirect stdin.
741
 
    Allows get_password to be tested without real tty attached.
742
 
 
743
 
    See also CannedInputUIFactory which lets you provide programmatic input in
744
 
    a structured way.
 
896
        super(StringIOWrapper, self).__init__(s)
 
897
 
 
898
 
 
899
TestUIFactory = ui_testing.TestUIFactory
 
900
 
 
901
 
 
902
def isolated_doctest_setUp(test):
 
903
    override_os_environ(test)
 
904
    test._orig_ui_factory = ui.ui_factory
 
905
    ui.ui_factory = ui.SilentUIFactory()
 
906
 
 
907
 
 
908
def isolated_doctest_tearDown(test):
 
909
    restore_os_environ(test)
 
910
    ui.ui_factory = test._orig_ui_factory
 
911
 
 
912
 
 
913
def IsolatedDocTestSuite(*args, **kwargs):
 
914
    """Overrides doctest.DocTestSuite to handle isolation.
 
915
 
 
916
    The method is really a factory and users are expected to use it as such.
745
917
    """
746
 
    # TODO: Capture progress events at the model level and allow them to be
747
 
    # observed by tests that care.
748
 
    #
749
 
    # XXX: Should probably unify more with CannedInputUIFactory or a
750
 
    # particular configuration of TextUIFactory, or otherwise have a clearer
751
 
    # idea of how they're supposed to be different.
752
 
    # See https://bugs.edge.launchpad.net/bzr/+bug/408213
753
 
 
754
 
    def __init__(self, stdout=None, stderr=None, stdin=None):
755
 
        if stdin is not None:
756
 
            # We use a StringIOWrapper to be able to test various
757
 
            # encodings, but the user is still responsible to
758
 
            # encode the string and to set the encoding attribute
759
 
            # of StringIOWrapper.
760
 
            stdin = StringIOWrapper(stdin)
761
 
        super(TestUIFactory, self).__init__(stdin, stdout, stderr)
762
 
 
763
 
    def get_non_echoed_password(self):
764
 
        """Get password from stdin without trying to handle the echo mode"""
765
 
        password = self.stdin.readline()
766
 
        if not password:
767
 
            raise EOFError
768
 
        if password[-1] == '\n':
769
 
            password = password[:-1]
770
 
        return password
771
 
 
772
 
    def make_progress_view(self):
773
 
        return NullProgressView()
 
918
 
 
919
    kwargs['setUp'] = isolated_doctest_setUp
 
920
    kwargs['tearDown'] = isolated_doctest_tearDown
 
921
    return doctest.DocTestSuite(*args, **kwargs)
774
922
 
775
923
 
776
924
class TestCase(testtools.TestCase):
777
 
    """Base class for bzr unit tests.
 
925
    """Base class for brz unit tests.
778
926
 
779
927
    Tests that need access to disk resources should subclass
780
928
    TestCaseInTempDir not TestCase.
786
934
    is read into memory and removed from disk.
787
935
 
788
936
    There are also convenience functions to invoke bzr's command-line
789
 
    routine, and to build and check bzr trees.
 
937
    routine, and to build and check brz trees.
790
938
 
791
939
    In addition to the usual method of overriding tearDown(), this class also
792
 
    allows subclasses to register functions into the _cleanups list, which is
 
940
    allows subclasses to register cleanup functions via addCleanup, which are
793
941
    run in order as the object is torn down.  It's less likely this will be
794
942
    accidentally overlooked.
795
943
    """
796
944
 
797
 
    _active_threads = None
798
 
    _leaking_threads_tests = 0
799
 
    _first_thread_leaker_id = None
800
 
    _log_file_name = None
 
945
    _log_file = None
801
946
    # record lsprof data when performing benchmark calls.
802
947
    _gather_lsprof_in_benchmarks = False
803
948
 
804
949
    def __init__(self, methodName='testMethod'):
805
950
        super(TestCase, self).__init__(methodName)
806
 
        self._cleanups = []
807
951
        self._directory_isolation = True
808
952
        self.exception_handlers.insert(0,
809
953
            (UnavailableFeature, self._do_unsupported_or_skip))
812
956
 
813
957
    def setUp(self):
814
958
        super(TestCase, self).setUp()
 
959
 
 
960
        # At this point we're still accessing the config files in $BRZ_HOME (as
 
961
        # set by the user running selftest).
 
962
        timeout = config.GlobalStack().get('selftest.timeout')
 
963
        if timeout:
 
964
            timeout_fixture = fixtures.TimeoutFixture(timeout)
 
965
            timeout_fixture.setUp()
 
966
            self.addCleanup(timeout_fixture.cleanUp)
 
967
 
815
968
        for feature in getattr(self, '_test_needs_features', []):
816
969
            self.requireFeature(feature)
817
 
        self._log_contents = None
818
 
        self.addDetail("log", content.Content(content.ContentType("text",
819
 
            "plain", {"charset": "utf8"}),
820
 
            lambda:[self._get_log(keep_log_file=True)]))
821
970
        self._cleanEnvironment()
 
971
 
 
972
        if breezy.global_state is not None:
 
973
            self.overrideAttr(breezy.global_state, 'cmdline_overrides',
 
974
                              config.CommandLineStore())
 
975
 
822
976
        self._silenceUI()
823
977
        self._startLogFile()
824
978
        self._benchcalls = []
827
981
        self._track_transports()
828
982
        self._track_locks()
829
983
        self._clear_debug_flags()
830
 
        TestCase._active_threads = threading.activeCount()
831
 
        self.addCleanup(self._check_leaked_threads)
 
984
        # Isolate global verbosity level, to make sure it's reproducible
 
985
        # between tests.  We should get rid of this altogether: bug 656694. --
 
986
        # mbp 20101008
 
987
        self.overrideAttr(breezy.trace, '_verbosity_level', 0)
 
988
        self._log_files = set()
 
989
        # Each key in the ``_counters`` dict holds a value for a different
 
990
        # counter. When the test ends, addDetail() should be used to output the
 
991
        # counter values. This happens in install_counter_hook().
 
992
        self._counters = {}
 
993
        if 'config_stats' in selftest_debug_flags:
 
994
            self._install_config_stats_hooks()
 
995
        # Do not use i18n for tests (unless the test reverses this)
 
996
        i18n.disable_i18n()
832
997
 
833
998
    def debug(self):
834
999
        # debug a frame up.
835
1000
        import pdb
836
 
        pdb.Pdb().set_trace(sys._getframe().f_back)
837
 
 
838
 
    def _check_leaked_threads(self):
839
 
        active = threading.activeCount()
840
 
        leaked_threads = active - TestCase._active_threads
841
 
        TestCase._active_threads = active
842
 
        # If some tests make the number of threads *decrease*, we'll consider
843
 
        # that they are just observing old threads dieing, not agressively kill
844
 
        # random threads. So we don't report these tests as leaking. The risk
845
 
        # is that we have false positives that way (the test see 2 threads
846
 
        # going away but leak one) but it seems less likely than the actual
847
 
        # false positives (the test see threads going away and does not leak).
848
 
        if leaked_threads > 0:
849
 
            TestCase._leaking_threads_tests += 1
850
 
            if TestCase._first_thread_leaker_id is None:
851
 
                TestCase._first_thread_leaker_id = self.id()
 
1001
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
1002
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
1003
                ).set_trace(sys._getframe().f_back)
 
1004
 
 
1005
    def discardDetail(self, name):
 
1006
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1007
 
 
1008
        eg. brz always adds the 'log' detail at startup, but we don't want to
 
1009
        include it for skipped, xfail, etc tests.
 
1010
 
 
1011
        It is safe to call this for a detail that doesn't exist, in case this
 
1012
        gets called multiple times.
 
1013
        """
 
1014
        # We cheat. details is stored in __details which means we shouldn't
 
1015
        # touch it. but getDetails() returns the dict directly, so we can
 
1016
        # mutate it.
 
1017
        details = self.getDetails()
 
1018
        if name in details:
 
1019
            del details[name]
 
1020
 
 
1021
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1022
        """Install a counting hook.
 
1023
 
 
1024
        Any hook can be counted as long as it doesn't need to return a value.
 
1025
 
 
1026
        :param hooks: Where the hook should be installed.
 
1027
 
 
1028
        :param name: The hook name that will be counted.
 
1029
 
 
1030
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1031
            to ``name``.
 
1032
        """
 
1033
        _counters = self._counters # Avoid closing over self
 
1034
        if counter_name is None:
 
1035
            counter_name = name
 
1036
        if counter_name in _counters:
 
1037
            raise AssertionError('%s is already used as a counter name'
 
1038
                                  % (counter_name,))
 
1039
        _counters[counter_name] = 0
 
1040
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1041
            lambda: ['%d' % (_counters[counter_name],)]))
 
1042
        def increment_counter(*args, **kwargs):
 
1043
            _counters[counter_name] += 1
 
1044
        label = 'count %s calls' % (counter_name,)
 
1045
        hooks.install_named_hook(name, increment_counter, label)
 
1046
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1047
 
 
1048
    def _install_config_stats_hooks(self):
 
1049
        """Install config hooks to count hook calls.
 
1050
 
 
1051
        """
 
1052
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1053
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1054
                                       'config.%s' % (hook_name,))
 
1055
 
 
1056
        # The OldConfigHooks are private and need special handling to protect
 
1057
        # against recursive tests (tests that run other tests), so we just do
 
1058
        # manually what registering them into _builtin_known_hooks will provide
 
1059
        # us.
 
1060
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1061
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1062
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1063
                                      'old_config.%s' % (hook_name,))
852
1064
 
853
1065
    def _clear_debug_flags(self):
854
1066
        """Prevent externally set debug flags affecting tests.
865
1077
 
866
1078
    def _clear_hooks(self):
867
1079
        # prevent hooks affecting tests
 
1080
        known_hooks = hooks.known_hooks
868
1081
        self._preserved_hooks = {}
869
 
        for key, factory in hooks.known_hooks.items():
870
 
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
871
 
            current_hooks = hooks.known_hooks_key_to_object(key)
 
1082
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1083
            current_hooks = getattr(parent, name)
872
1084
            self._preserved_hooks[parent] = (name, current_hooks)
 
1085
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1086
        hooks._lazy_hooks = {}
873
1087
        self.addCleanup(self._restoreHooks)
874
 
        for key, factory in hooks.known_hooks.items():
875
 
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
 
1088
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1089
            factory = known_hooks.get(key)
876
1090
            setattr(parent, name, factory())
877
1091
        # this hook should always be installed
878
1092
        request._install_hook()
907
1121
        # break some locks on purpose and should be taken into account by
908
1122
        # considering that breaking a lock is just a dirty way of releasing it.
909
1123
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
910
 
            message = ('Different number of acquired and '
911
 
                       'released or broken locks. (%s, %s + %s)' %
912
 
                       (acquired_locks, released_locks, broken_locks))
 
1124
            message = (
 
1125
                'Different number of acquired and '
 
1126
                'released or broken locks.\n'
 
1127
                'acquired=%s\n'
 
1128
                'released=%s\n'
 
1129
                'broken=%s\n' %
 
1130
                (acquired_locks, released_locks, broken_locks))
913
1131
            if not self._lock_check_thorough:
914
1132
                # Rather than fail, just warn
915
 
                print "Broken test %s: %s" % (self, message)
 
1133
                print("Broken test %s: %s" % (self, message))
916
1134
                return
917
1135
            self.fail(message)
918
1136
 
943
1161
 
944
1162
    def permit_dir(self, name):
945
1163
        """Permit a directory to be used by this test. See permit_url."""
946
 
        name_transport = get_transport(name)
 
1164
        name_transport = _mod_transport.get_transport_from_path(name)
947
1165
        self.permit_url(name)
948
1166
        self.permit_url(name_transport.base)
949
1167
 
950
1168
    def permit_url(self, url):
951
1169
        """Declare that url is an ok url to use in this test.
952
 
        
 
1170
 
953
1171
        Do this for memory transports, temporary test directory etc.
954
 
        
 
1172
 
955
1173
        Do not do this for the current working directory, /tmp, or any other
956
1174
        preexisting non isolated url.
957
1175
        """
960
1178
        self._bzr_selftest_roots.append(url)
961
1179
 
962
1180
    def permit_source_tree_branch_repo(self):
963
 
        """Permit the source tree bzr is running from to be opened.
 
1181
        """Permit the source tree brz is running from to be opened.
964
1182
 
965
 
        Some code such as bzrlib.version attempts to read from the bzr branch
966
 
        that bzr is executing from (if any). This method permits that directory
 
1183
        Some code such as breezy.version attempts to read from the brz branch
 
1184
        that brz is executing from (if any). This method permits that directory
967
1185
        to be used in the test suite.
968
1186
        """
969
1187
        path = self.get_source_path()
972
1190
            try:
973
1191
                workingtree.WorkingTree.open(path)
974
1192
            except (errors.NotBranchError, errors.NoWorkingTree):
975
 
                return
 
1193
                raise TestSkipped('Needs a working tree of brz sources')
976
1194
        finally:
977
1195
            self.enable_directory_isolation()
978
1196
 
1010
1228
 
1011
1229
    def record_directory_isolation(self):
1012
1230
        """Gather accessed directories to permit later access.
1013
 
        
1014
 
        This is used for tests that access the branch bzr is running from.
 
1231
 
 
1232
        This is used for tests that access the branch brz is running from.
1015
1233
        """
1016
1234
        self._directory_isolation = "record"
1017
1235
 
1028
1246
        self.addCleanup(transport_server.stop_server)
1029
1247
        # Obtain a real transport because if the server supplies a password, it
1030
1248
        # will be hidden from the base on the client side.
1031
 
        t = get_transport(transport_server.get_url())
 
1249
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1032
1250
        # Some transport servers effectively chroot the backing transport;
1033
1251
        # others like SFTPServer don't - users of the transport can walk up the
1034
1252
        # transport to read the entire backing transport. This wouldn't matter
1062
1280
        # TestCase has no safe place it can write to.
1063
1281
        self._bzr_selftest_roots = []
1064
1282
        # Currently the easiest way to be sure that nothing is going on is to
1065
 
        # hook into bzr dir opening. This leaves a small window of error for
 
1283
        # hook into brz dir opening. This leaves a small window of error for
1066
1284
        # transport tests, but they are well known, and we can improve on this
1067
1285
        # step.
1068
 
        bzrdir.BzrDir.hooks.install_named_hook("pre_open",
1069
 
            self._preopen_isolate_transport, "Check bzr directories are safe.")
 
1286
        controldir.ControlDir.hooks.install_named_hook("pre_open",
 
1287
            self._preopen_isolate_transport, "Check brz directories are safe.")
1070
1288
 
1071
1289
    def _ndiff_strings(self, a, b):
1072
1290
        """Return ndiff between two strings containing lines.
1087
1305
        try:
1088
1306
            if a == b:
1089
1307
                return
1090
 
        except UnicodeError, e:
 
1308
        except UnicodeError as e:
1091
1309
            # If we can't compare without getting a UnicodeError, then
1092
1310
            # obviously they are different
1093
 
            mutter('UnicodeError: %s', e)
 
1311
            trace.mutter('UnicodeError: %s', e)
1094
1312
        if message:
1095
1313
            message += '\n'
1096
1314
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1097
1315
            % (message,
1098
 
               pformat(a), pformat(b)))
 
1316
               pprint.pformat(a), pprint.pformat(b)))
1099
1317
 
 
1318
    # FIXME: This is deprecated in unittest2 but plugins may still use it so we
 
1319
    # need a deprecation period for them -- vila 2016-02-01
1100
1320
    assertEquals = assertEqual
1101
1321
 
1102
1322
    def assertEqualDiff(self, a, b, message=None):
1105
1325
        This is intended for use with multi-line strings where it can
1106
1326
        be hard to find the differences by eye.
1107
1327
        """
1108
 
        # TODO: perhaps override assertEquals to call this for strings?
 
1328
        # TODO: perhaps override assertEqual to call this for strings?
1109
1329
        if a == b:
1110
1330
            return
1111
1331
        if message is None:
1135
1355
                         'st_mtime did not match')
1136
1356
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1137
1357
                         'st_ctime did not match')
1138
 
        if sys.platform != 'win32':
 
1358
        if sys.platform == 'win32':
1139
1359
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1140
1360
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
1141
 
            # odd. Regardless we shouldn't actually try to assert anything
1142
 
            # about their values
 
1361
            # odd. We just force it to always be 0 to avoid any problems.
 
1362
            self.assertEqual(0, expected.st_dev)
 
1363
            self.assertEqual(0, actual.st_dev)
 
1364
            self.assertEqual(0, expected.st_ino)
 
1365
            self.assertEqual(0, actual.st_ino)
 
1366
        else:
1143
1367
            self.assertEqual(expected.st_dev, actual.st_dev,
1144
1368
                             'st_dev did not match')
1145
1369
            self.assertEqual(expected.st_ino, actual.st_ino,
1154
1378
                length, len(obj_with_len), obj_with_len))
1155
1379
 
1156
1380
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1157
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1381
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1158
1382
        """
1159
 
        from bzrlib import trace
1160
1383
        captured = []
1161
1384
        orig_log_exception_quietly = trace.log_exception_quietly
1162
1385
        try:
1163
1386
            def capture():
1164
1387
                orig_log_exception_quietly()
1165
 
                captured.append(sys.exc_info())
 
1388
                captured.append(sys.exc_info()[1])
1166
1389
            trace.log_exception_quietly = capture
1167
1390
            func(*args, **kwargs)
1168
1391
        finally:
1169
1392
            trace.log_exception_quietly = orig_log_exception_quietly
1170
1393
        self.assertLength(1, captured)
1171
 
        err = captured[0][1]
 
1394
        err = captured[0]
1172
1395
        self.assertIsInstance(err, exception_class)
1173
1396
        return err
1174
1397
 
1211
1434
        if haystack.find(needle) == -1:
1212
1435
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1213
1436
 
 
1437
    def assertNotContainsString(self, haystack, needle):
 
1438
        if haystack.find(needle) != -1:
 
1439
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1440
 
1214
1441
    def assertSubset(self, sublist, superlist):
1215
1442
        """Assert that every entry in sublist is present in superlist."""
1216
1443
        missing = set(sublist) - set(superlist)
1227
1454
        """
1228
1455
        try:
1229
1456
            list(func(*args, **kwargs))
1230
 
        except excClass, e:
 
1457
        except excClass as e:
1231
1458
            return e
1232
1459
        else:
1233
1460
            if getattr(excClass,'__name__', None) is not None:
1234
1461
                excName = excClass.__name__
1235
1462
            else:
1236
1463
                excName = str(excClass)
1237
 
            raise self.failureException, "%s not raised" % excName
 
1464
            raise self.failureException("%s not raised" % excName)
1238
1465
 
1239
1466
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
1240
1467
        """Assert that a callable raises a particular exception.
1248
1475
        """
1249
1476
        try:
1250
1477
            callableObj(*args, **kwargs)
1251
 
        except excClass, e:
 
1478
        except excClass as e:
1252
1479
            return e
1253
1480
        else:
1254
1481
            if getattr(excClass,'__name__', None) is not None:
1256
1483
            else:
1257
1484
                # probably a tuple
1258
1485
                excName = str(excClass)
1259
 
            raise self.failureException, "%s not raised" % excName
 
1486
            raise self.failureException("%s not raised" % excName)
1260
1487
 
1261
1488
    def assertIs(self, left, right, message=None):
1262
1489
        if not (left is right):
1305
1532
 
1306
1533
    def assertFileEqual(self, content, path):
1307
1534
        """Fail if path does not contain 'content'."""
1308
 
        self.failUnlessExists(path)
 
1535
        self.assertPathExists(path)
1309
1536
        f = file(path, 'rb')
1310
1537
        try:
1311
1538
            s = f.read()
1321
1548
        else:
1322
1549
            self.assertEqual(expected_docstring, obj.__doc__)
1323
1550
 
1324
 
    def failUnlessExists(self, path):
 
1551
    def assertPathExists(self, path):
1325
1552
        """Fail unless path or paths, which may be abs or relative, exist."""
1326
1553
        if not isinstance(path, basestring):
1327
1554
            for p in path:
1328
 
                self.failUnlessExists(p)
 
1555
                self.assertPathExists(p)
1329
1556
        else:
1330
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1557
            self.assertTrue(osutils.lexists(path),
 
1558
                path + " does not exist")
1331
1559
 
1332
 
    def failIfExists(self, path):
 
1560
    def assertPathDoesNotExist(self, path):
1333
1561
        """Fail if path or paths, which may be abs or relative, exist."""
1334
1562
        if not isinstance(path, basestring):
1335
1563
            for p in path:
1336
 
                self.failIfExists(p)
 
1564
                self.assertPathDoesNotExist(p)
1337
1565
        else:
1338
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1566
            self.assertFalse(osutils.lexists(path),
 
1567
                path + " exists")
1339
1568
 
1340
1569
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1341
1570
        """A helper for callDeprecated and applyDeprecated.
1367
1596
        not other callers that go direct to the warning module.
1368
1597
 
1369
1598
        To test that a deprecated method raises an error, do something like
1370
 
        this::
 
1599
        this (remember that both assertRaises and applyDeprecated delays *args
 
1600
        and **kwargs passing)::
1371
1601
 
1372
1602
            self.assertRaises(errors.ReservedId,
1373
1603
                self.applyDeprecated,
1451
1681
        return result
1452
1682
 
1453
1683
    def _startLogFile(self):
1454
 
        """Send bzr and test log messages to a temporary file.
1455
 
 
1456
 
        The file is removed as the test is torn down.
1457
 
        """
1458
 
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
1459
 
        self._log_file = os.fdopen(fileno, 'w+')
1460
 
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
1461
 
        self._log_file_name = name
 
1684
        """Setup a in-memory target for bzr and testcase log messages"""
 
1685
        pseudo_log_file = BytesIO()
 
1686
        def _get_log_contents_for_weird_testtools_api():
 
1687
            return [pseudo_log_file.getvalue().decode(
 
1688
                "utf-8", "replace").encode("utf-8")]
 
1689
        self.addDetail("log", content.Content(content.ContentType("text",
 
1690
            "plain", {"charset": "utf8"}),
 
1691
            _get_log_contents_for_weird_testtools_api))
 
1692
        self._log_file = pseudo_log_file
 
1693
        self._log_memento = trace.push_log_file(self._log_file)
1462
1694
        self.addCleanup(self._finishLogFile)
1463
1695
 
1464
1696
    def _finishLogFile(self):
1465
 
        """Finished with the log file.
1466
 
 
1467
 
        Close the file and delete it, unless setKeepLogfile was called.
1468
 
        """
1469
 
        if bzrlib.trace._trace_file:
 
1697
        """Flush and dereference the in-memory log for this testcase"""
 
1698
        if trace._trace_file:
1470
1699
            # flush the log file, to get all content
1471
 
            bzrlib.trace._trace_file.flush()
1472
 
        bzrlib.trace.pop_log_file(self._log_memento)
1473
 
        # Cache the log result and delete the file on disk
1474
 
        self._get_log(False)
 
1700
            trace._trace_file.flush()
 
1701
        trace.pop_log_file(self._log_memento)
 
1702
        # The logging module now tracks references for cleanup so discard ours
 
1703
        del self._log_memento
1475
1704
 
1476
1705
    def thisFailsStrictLockCheck(self):
1477
1706
        """It is known that this test would fail with -Dstrict_locks.
1486
1715
        """
1487
1716
        debug.debug_flags.discard('strict_locks')
1488
1717
 
1489
 
    def addCleanup(self, callable, *args, **kwargs):
1490
 
        """Arrange to run a callable when this case is torn down.
1491
 
 
1492
 
        Callables are run in the reverse of the order they are registered,
1493
 
        ie last-in first-out.
1494
 
        """
1495
 
        self._cleanups.append((callable, args, kwargs))
1496
 
 
1497
1718
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1498
1719
        """Overrides an object attribute restoring it after the test.
1499
1720
 
 
1721
        :note: This should be used with discretion; you should think about
 
1722
        whether it's better to make the code testable without monkey-patching.
 
1723
 
1500
1724
        :param obj: The object that will be mutated.
1501
1725
 
1502
1726
        :param attr_name: The attribute name we want to preserve/override in
1506
1730
 
1507
1731
        :returns: The actual attr value.
1508
1732
        """
1509
 
        value = getattr(obj, attr_name)
1510
1733
        # The actual value is captured by the call below
1511
 
        self.addCleanup(setattr, obj, attr_name, value)
 
1734
        value = getattr(obj, attr_name, _unitialized_attr)
 
1735
        if value is _unitialized_attr:
 
1736
            # When the test completes, the attribute should not exist, but if
 
1737
            # we aren't setting a value, we don't need to do anything.
 
1738
            if new is not _unitialized_attr:
 
1739
                self.addCleanup(delattr, obj, attr_name)
 
1740
        else:
 
1741
            self.addCleanup(setattr, obj, attr_name, value)
1512
1742
        if new is not _unitialized_attr:
1513
1743
            setattr(obj, attr_name, new)
1514
1744
        return value
1515
1745
 
 
1746
    def overrideEnv(self, name, new):
 
1747
        """Set an environment variable, and reset it after the test.
 
1748
 
 
1749
        :param name: The environment variable name.
 
1750
 
 
1751
        :param new: The value to set the variable to. If None, the 
 
1752
            variable is deleted from the environment.
 
1753
 
 
1754
        :returns: The actual variable value.
 
1755
        """
 
1756
        value = osutils.set_or_unset_env(name, new)
 
1757
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1758
        return value
 
1759
 
 
1760
    def recordCalls(self, obj, attr_name):
 
1761
        """Monkeypatch in a wrapper that will record calls.
 
1762
 
 
1763
        The monkeypatch is automatically removed when the test concludes.
 
1764
 
 
1765
        :param obj: The namespace holding the reference to be replaced;
 
1766
            typically a module, class, or object.
 
1767
        :param attr_name: A string for the name of the attribute to 
 
1768
            patch.
 
1769
        :returns: A list that will be extended with one item every time the
 
1770
            function is called, with a tuple of (args, kwargs).
 
1771
        """
 
1772
        calls = []
 
1773
 
 
1774
        def decorator(*args, **kwargs):
 
1775
            calls.append((args, kwargs))
 
1776
            return orig(*args, **kwargs)
 
1777
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1778
        return calls
 
1779
 
1516
1780
    def _cleanEnvironment(self):
1517
 
        new_env = {
1518
 
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1519
 
            'HOME': os.getcwd(),
1520
 
            # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1521
 
            # tests do check our impls match APPDATA
1522
 
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
1523
 
            'VISUAL': None,
1524
 
            'EDITOR': None,
1525
 
            'BZR_EMAIL': None,
1526
 
            'BZREMAIL': None, # may still be present in the environment
1527
 
            'EMAIL': None,
1528
 
            'BZR_PROGRESS_BAR': None,
1529
 
            'BZR_LOG': None,
1530
 
            'BZR_PLUGIN_PATH': None,
1531
 
            'BZR_DISABLE_PLUGINS': None,
1532
 
            'BZR_PLUGINS_AT': None,
1533
 
            'BZR_CONCURRENCY': None,
1534
 
            # Make sure that any text ui tests are consistent regardless of
1535
 
            # the environment the test case is run in; you may want tests that
1536
 
            # test other combinations.  'dumb' is a reasonable guess for tests
1537
 
            # going to a pipe or a StringIO.
1538
 
            'TERM': 'dumb',
1539
 
            'LINES': '25',
1540
 
            'COLUMNS': '80',
1541
 
            'BZR_COLUMNS': '80',
1542
 
            # SSH Agent
1543
 
            'SSH_AUTH_SOCK': None,
1544
 
            # Proxies
1545
 
            'http_proxy': None,
1546
 
            'HTTP_PROXY': None,
1547
 
            'https_proxy': None,
1548
 
            'HTTPS_PROXY': None,
1549
 
            'no_proxy': None,
1550
 
            'NO_PROXY': None,
1551
 
            'all_proxy': None,
1552
 
            'ALL_PROXY': None,
1553
 
            # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1554
 
            # least. If you do (care), please update this comment
1555
 
            # -- vila 20080401
1556
 
            'ftp_proxy': None,
1557
 
            'FTP_PROXY': None,
1558
 
            'BZR_REMOTE_PATH': None,
1559
 
            # Generally speaking, we don't want apport reporting on crashes in
1560
 
            # the test envirnoment unless we're specifically testing apport,
1561
 
            # so that it doesn't leak into the real system environment.  We
1562
 
            # use an env var so it propagates to subprocesses.
1563
 
            'APPORT_DISABLE': '1',
1564
 
        }
1565
 
        self._old_env = {}
1566
 
        self.addCleanup(self._restoreEnvironment)
1567
 
        for name, value in new_env.iteritems():
1568
 
            self._captureVar(name, value)
1569
 
 
1570
 
    def _captureVar(self, name, newvalue):
1571
 
        """Set an environment variable, and reset it when finished."""
1572
 
        self._old_env[name] = osutils.set_or_unset_env(name, newvalue)
1573
 
 
1574
 
    def _restoreEnvironment(self):
1575
 
        for name, value in self._old_env.iteritems():
1576
 
            osutils.set_or_unset_env(name, value)
 
1781
        for name, value in isolated_environ.items():
 
1782
            self.overrideEnv(name, value)
1577
1783
 
1578
1784
    def _restoreHooks(self):
1579
1785
        for klass, (name, hooks) in self._preserved_hooks.items():
1580
1786
            setattr(klass, name, hooks)
 
1787
        self._preserved_hooks.clear()
 
1788
        breezy.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1789
        self._preserved_lazy_hooks.clear()
1581
1790
 
1582
1791
    def knownFailure(self, reason):
1583
 
        """This test has failed for some known reason."""
1584
 
        raise KnownFailure(reason)
 
1792
        """Declare that this test fails for a known reason
 
1793
 
 
1794
        Tests that are known to fail should generally be using expectedFailure
 
1795
        with an appropriate reverse assertion if a change could cause the test
 
1796
        to start passing. Conversely if the test has no immediate prospect of
 
1797
        succeeding then using skip is more suitable.
 
1798
 
 
1799
        When this method is called while an exception is being handled, that
 
1800
        traceback will be used, otherwise a new exception will be thrown to
 
1801
        provide one but won't be reported.
 
1802
        """
 
1803
        self._add_reason(reason)
 
1804
        try:
 
1805
            exc_info = sys.exc_info()
 
1806
            if exc_info != (None, None, None):
 
1807
                self._report_traceback(exc_info)
 
1808
            else:
 
1809
                try:
 
1810
                    raise self.failureException(reason)
 
1811
                except self.failureException:
 
1812
                    exc_info = sys.exc_info()
 
1813
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1814
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1815
        finally:
 
1816
            del exc_info
 
1817
 
 
1818
    def _suppress_log(self):
 
1819
        """Remove the log info from details."""
 
1820
        self.discardDetail('log')
1585
1821
 
1586
1822
    def _do_skip(self, result, reason):
 
1823
        self._suppress_log()
1587
1824
        addSkip = getattr(result, 'addSkip', None)
1588
1825
        if not callable(addSkip):
1589
1826
            result.addSuccess(result)
1592
1829
 
1593
1830
    @staticmethod
1594
1831
    def _do_known_failure(self, result, e):
 
1832
        self._suppress_log()
1595
1833
        err = sys.exc_info()
1596
1834
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1597
1835
        if addExpectedFailure is not None:
1605
1843
            reason = 'No reason given'
1606
1844
        else:
1607
1845
            reason = e.args[0]
 
1846
        self._suppress_log ()
1608
1847
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1609
1848
        if addNotApplicable is not None:
1610
1849
            result.addNotApplicable(self, reason)
1612
1851
            self._do_skip(result, reason)
1613
1852
 
1614
1853
    @staticmethod
 
1854
    def _report_skip(self, result, err):
 
1855
        """Override the default _report_skip.
 
1856
 
 
1857
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1858
        already been formatted into the 'reason' string, and we can't pull it
 
1859
        out again.
 
1860
        """
 
1861
        self._suppress_log()
 
1862
        super(TestCase, self)._report_skip(self, result, err)
 
1863
 
 
1864
    @staticmethod
 
1865
    def _report_expected_failure(self, result, err):
 
1866
        """Strip the log.
 
1867
 
 
1868
        See _report_skip for motivation.
 
1869
        """
 
1870
        self._suppress_log()
 
1871
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1872
 
 
1873
    @staticmethod
1615
1874
    def _do_unsupported_or_skip(self, result, e):
1616
1875
        reason = e.args[0]
 
1876
        self._suppress_log()
1617
1877
        addNotSupported = getattr(result, 'addNotSupported', None)
1618
1878
        if addNotSupported is not None:
1619
1879
            result.addNotSupported(self, reason)
1623
1883
    def time(self, callable, *args, **kwargs):
1624
1884
        """Run callable and accrue the time it takes to the benchmark time.
1625
1885
 
1626
 
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
 
1886
        If lsprofiling is enabled (i.e. by --lsprof-time to brz selftest) then
1627
1887
        this will cause lsprofile statistics to be gathered and stored in
1628
1888
        self._benchcalls.
1629
1889
        """
1637
1897
                return callable(*args, **kwargs)
1638
1898
            else:
1639
1899
                # record this benchmark
1640
 
                ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
 
1900
                ret, stats = breezy.lsprof.profile(callable, *args, **kwargs)
1641
1901
                stats.sort()
1642
1902
                self._benchcalls.append(((callable, args, kwargs), stats))
1643
1903
                return ret
1645
1905
            self._benchtime += time.time() - start
1646
1906
 
1647
1907
    def log(self, *args):
1648
 
        mutter(*args)
1649
 
 
1650
 
    def _get_log(self, keep_log_file=False):
1651
 
        """Internal helper to get the log from bzrlib.trace for this test.
1652
 
 
1653
 
        Please use self.getDetails, or self.get_log to access this in test case
1654
 
        code.
1655
 
 
1656
 
        :param keep_log_file: When True, if the log is still a file on disk
1657
 
            leave it as a file on disk. When False, if the log is still a file
1658
 
            on disk, the log file is deleted and the log preserved as
1659
 
            self._log_contents.
1660
 
        :return: A string containing the log.
1661
 
        """
1662
 
        if self._log_contents is not None:
1663
 
            try:
1664
 
                self._log_contents.decode('utf8')
1665
 
            except UnicodeDecodeError:
1666
 
                unicodestr = self._log_contents.decode('utf8', 'replace')
1667
 
                self._log_contents = unicodestr.encode('utf8')
1668
 
            return self._log_contents
1669
 
        import bzrlib.trace
1670
 
        if bzrlib.trace._trace_file:
1671
 
            # flush the log file, to get all content
1672
 
            bzrlib.trace._trace_file.flush()
1673
 
        if self._log_file_name is not None:
1674
 
            logfile = open(self._log_file_name)
1675
 
            try:
1676
 
                log_contents = logfile.read()
1677
 
            finally:
1678
 
                logfile.close()
1679
 
            try:
1680
 
                log_contents.decode('utf8')
1681
 
            except UnicodeDecodeError:
1682
 
                unicodestr = log_contents.decode('utf8', 'replace')
1683
 
                log_contents = unicodestr.encode('utf8')
1684
 
            if not keep_log_file:
1685
 
                close_attempts = 0
1686
 
                max_close_attempts = 100
1687
 
                first_close_error = None
1688
 
                while close_attempts < max_close_attempts:
1689
 
                    close_attempts += 1
1690
 
                    try:
1691
 
                        self._log_file.close()
1692
 
                    except IOError, ioe:
1693
 
                        if ioe.errno is None:
1694
 
                            # No errno implies 'close() called during
1695
 
                            # concurrent operation on the same file object', so
1696
 
                            # retry.  Probably a thread is trying to write to
1697
 
                            # the log file.
1698
 
                            if first_close_error is None:
1699
 
                                first_close_error = ioe
1700
 
                            continue
1701
 
                        raise
1702
 
                    else:
1703
 
                        break
1704
 
                if close_attempts > 1:
1705
 
                    sys.stderr.write(
1706
 
                        'Unable to close log file on first attempt, '
1707
 
                        'will retry: %s\n' % (first_close_error,))
1708
 
                    if close_attempts == max_close_attempts:
1709
 
                        sys.stderr.write(
1710
 
                            'Unable to close log file after %d attempts.\n'
1711
 
                            % (max_close_attempts,))
1712
 
                self._log_file = None
1713
 
                # Permit multiple calls to get_log until we clean it up in
1714
 
                # finishLogFile
1715
 
                self._log_contents = log_contents
1716
 
                try:
1717
 
                    os.remove(self._log_file_name)
1718
 
                except OSError, e:
1719
 
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
1720
 
                        sys.stderr.write(('Unable to delete log file '
1721
 
                                             ' %r\n' % self._log_file_name))
1722
 
                    else:
1723
 
                        raise
1724
 
                self._log_file_name = None
1725
 
            return log_contents
1726
 
        else:
1727
 
            return "No log file content and no log file name."
 
1908
        trace.mutter(*args)
1728
1909
 
1729
1910
    def get_log(self):
1730
 
        """Get a unicode string containing the log from bzrlib.trace.
 
1911
        """Get a unicode string containing the log from breezy.trace.
1731
1912
 
1732
1913
        Undecodable characters are replaced.
1733
1914
        """
1744
1925
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1745
1926
            working_dir):
1746
1927
        """Run bazaar command line, splitting up a string command line."""
1747
 
        if isinstance(args, basestring):
1748
 
            # shlex don't understand unicode strings,
1749
 
            # so args should be plain string (bialix 20070906)
1750
 
            args = list(shlex.split(str(args)))
 
1928
        if isinstance(args, string_types):
 
1929
            args = shlex.split(args)
1751
1930
        return self._run_bzr_core(args, retcode=retcode,
1752
1931
                encoding=encoding, stdin=stdin, working_dir=working_dir,
1753
1932
                )
1759
1938
        chk_map.clear_cache()
1760
1939
        if encoding is None:
1761
1940
            encoding = osutils.get_user_encoding()
1762
 
        stdout = StringIOWrapper()
1763
 
        stderr = StringIOWrapper()
1764
 
        stdout.encoding = encoding
1765
 
        stderr.encoding = encoding
1766
 
 
1767
 
        self.log('run bzr: %r', args)
 
1941
 
 
1942
        self.log('run brz: %r', args)
 
1943
 
 
1944
        stdout = ui_testing.BytesIOWithEncoding()
 
1945
        stderr = ui_testing.BytesIOWithEncoding()
 
1946
        stdout.encoding = stderr.encoding = encoding
 
1947
 
1768
1948
        # FIXME: don't call into logging here
1769
 
        handler = logging.StreamHandler(stderr)
1770
 
        handler.setLevel(logging.INFO)
 
1949
        handler = trace.EncodedStreamHandler(
 
1950
            stderr, errors="replace", level=logging.INFO)
1771
1951
        logger = logging.getLogger('')
1772
1952
        logger.addHandler(handler)
 
1953
 
 
1954
        self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
 
1955
        self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
 
1956
 
1773
1957
        old_ui_factory = ui.ui_factory
1774
 
        ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
 
1958
        ui.ui_factory = ui_testing.TestUIFactory(
 
1959
            stdin=stdin,
 
1960
            stdout=self._last_cmd_stdout,
 
1961
            stderr=self._last_cmd_stderr)
1775
1962
 
1776
1963
        cwd = None
1777
1964
        if working_dir is not None:
1779
1966
            os.chdir(working_dir)
1780
1967
 
1781
1968
        try:
1782
 
            try:
1783
 
                result = self.apply_redirected(ui.ui_factory.stdin,
1784
 
                    stdout, stderr,
1785
 
                    bzrlib.commands.run_bzr_catch_user_errors,
1786
 
                    args)
1787
 
            except KeyboardInterrupt:
1788
 
                # Reraise KeyboardInterrupt with contents of redirected stdout
1789
 
                # and stderr as arguments, for tests which are interested in
1790
 
                # stdout and stderr and are expecting the exception.
1791
 
                out = stdout.getvalue()
1792
 
                err = stderr.getvalue()
1793
 
                if out:
1794
 
                    self.log('output:\n%r', out)
1795
 
                if err:
1796
 
                    self.log('errors:\n%r', err)
1797
 
                raise KeyboardInterrupt(out, err)
 
1969
            result = self.apply_redirected(
 
1970
                ui.ui_factory.stdin,
 
1971
                stdout, stderr,
 
1972
                _mod_commands.run_bzr_catch_user_errors,
 
1973
                args)
1798
1974
        finally:
1799
1975
            logger.removeHandler(handler)
1800
1976
            ui.ui_factory = old_ui_factory
1808
1984
        if err:
1809
1985
            self.log('errors:\n%r', err)
1810
1986
        if retcode is not None:
1811
 
            self.assertEquals(retcode, result,
 
1987
            self.assertEqual(retcode, result,
1812
1988
                              message='Unexpected return code')
1813
1989
        return result, out, err
1814
1990
 
1815
 
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
1816
 
                working_dir=None, error_regexes=[], output_encoding=None):
1817
 
        """Invoke bzr, as if it were run from the command line.
 
1991
    def run_bzr(self, args, retcode=0, stdin=None, encoding=None,
 
1992
                working_dir=None, error_regexes=[]):
 
1993
        """Invoke brz, as if it were run from the command line.
1818
1994
 
1819
 
        The argument list should not include the bzr program name - the
1820
 
        first argument is normally the bzr command.  Arguments may be
 
1995
        The argument list should not include the brz program name - the
 
1996
        first argument is normally the brz command.  Arguments may be
1821
1997
        passed in three ways:
1822
1998
 
1823
1999
        1- A list of strings, eg ["commit", "a"].  This is recommended
1827
2003
        2- A single string, eg "add a".  This is the most convenient
1828
2004
        for hardcoded commands.
1829
2005
 
1830
 
        This runs bzr through the interface that catches and reports
 
2006
        This runs brz through the interface that catches and reports
1831
2007
        errors, and with logging set to something approximating the
1832
2008
        default, so that error reporting can be checked.
1833
2009
 
1834
2010
        This should be the main method for tests that want to exercise the
1835
 
        overall behavior of the bzr application (rather than a unit test
 
2011
        overall behavior of the brz application (rather than a unit test
1836
2012
        or a functional test of the library.)
1837
2013
 
1838
2014
        This sends the stdout/stderr results into the test's log,
1858
2034
        return out, err
1859
2035
 
1860
2036
    def run_bzr_error(self, error_regexes, *args, **kwargs):
1861
 
        """Run bzr, and check that stderr contains the supplied regexes
 
2037
        """Run brz, and check that stderr contains the supplied regexes
1862
2038
 
1863
2039
        :param error_regexes: Sequence of regular expressions which
1864
2040
            must each be found in the error output. The relative ordering
1865
2041
            is not enforced.
1866
 
        :param args: command-line arguments for bzr
1867
 
        :param kwargs: Keyword arguments which are interpreted by run_bzr
 
2042
        :param args: command-line arguments for brz
 
2043
        :param kwargs: Keyword arguments which are interpreted by run_brz
1868
2044
            This function changes the default value of retcode to be 3,
1869
 
            since in most cases this is run when you expect bzr to fail.
 
2045
            since in most cases this is run when you expect brz to fail.
1870
2046
 
1871
2047
        :return: (out, err) The actual output of running the command (in case
1872
2048
            you want to do more inspection)
1888
2064
        return out, err
1889
2065
 
1890
2066
    def run_bzr_subprocess(self, *args, **kwargs):
1891
 
        """Run bzr in a subprocess for testing.
 
2067
        """Run brz in a subprocess for testing.
1892
2068
 
1893
 
        This starts a new Python interpreter and runs bzr in there.
 
2069
        This starts a new Python interpreter and runs brz in there.
1894
2070
        This should only be used for tests that have a justifiable need for
1895
2071
        this isolation: e.g. they are testing startup time, or signal
1896
2072
        handling, or early startup code, etc.  Subprocess code can't be
1930
2106
    def start_bzr_subprocess(self, process_args, env_changes=None,
1931
2107
                             skip_if_plan_to_signal=False,
1932
2108
                             working_dir=None,
1933
 
                             allow_plugins=False):
1934
 
        """Start bzr in a subprocess for testing.
 
2109
                             allow_plugins=False, stderr=subprocess.PIPE):
 
2110
        """Start brz in a subprocess for testing.
1935
2111
 
1936
 
        This starts a new Python interpreter and runs bzr in there.
 
2112
        This starts a new Python interpreter and runs brz in there.
1937
2113
        This should only be used for tests that have a justifiable need for
1938
2114
        this isolation: e.g. they are testing startup time, or signal
1939
2115
        handling, or early startup code, etc.  Subprocess code can't be
1940
2116
        profiled or debugged so easily.
1941
2117
 
1942
 
        :param process_args: a list of arguments to pass to the bzr executable,
 
2118
        :param process_args: a list of arguments to pass to the brz executable,
1943
2119
            for example ``['--version']``.
1944
2120
        :param env_changes: A dictionary which lists changes to environment
1945
2121
            variables. A value of None will unset the env variable.
1946
2122
            The values must be strings. The change will only occur in the
1947
2123
            child, so you don't need to fix the environment after running.
1948
 
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
1949
 
            is not available.
1950
 
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
2124
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2125
            doesn't support signalling subprocesses.
 
2126
        :param allow_plugins: If False (default) pass --no-plugins to brz.
 
2127
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2128
            are those valid for the stderr argument of `subprocess.Popen`.
 
2129
            Default value is ``subprocess.PIPE``.
1951
2130
 
1952
2131
        :returns: Popen object for the started process.
1953
2132
        """
1954
2133
        if skip_if_plan_to_signal:
1955
 
            if not getattr(os, 'kill', None):
1956
 
                raise TestSkipped("os.kill not available.")
 
2134
            if os.name != "posix":
 
2135
                raise TestSkipped("Sending signals not supported")
1957
2136
 
1958
2137
        if env_changes is None:
1959
2138
            env_changes = {}
 
2139
        # Because $HOME is set to a tempdir for the context of a test, modules
 
2140
        # installed in the user dir will not be found unless $PYTHONUSERBASE
 
2141
        # gets set to the computed directory of this parent process.
 
2142
        if site.USER_BASE is not None:
 
2143
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
1960
2144
        old_env = {}
1961
2145
 
1962
2146
        def cleanup_environment():
1963
 
            for env_var, value in env_changes.iteritems():
 
2147
            for env_var, value in env_changes.items():
1964
2148
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
1965
2149
 
1966
2150
        def restore_environment():
1967
 
            for env_var, value in old_env.iteritems():
 
2151
            for env_var, value in old_env.items():
1968
2152
                osutils.set_or_unset_env(env_var, value)
1969
2153
 
1970
 
        bzr_path = self.get_bzr_path()
 
2154
        bzr_path = self.get_brz_path()
1971
2155
 
1972
2156
        cwd = None
1973
2157
        if working_dir is not None:
1979
2163
            # so we will avoid using it on all platforms, just to
1980
2164
            # make sure the code path is used, and we don't break on win32
1981
2165
            cleanup_environment()
 
2166
            # Include the subprocess's log file in the test details, in case
 
2167
            # the test fails due to an error in the subprocess.
 
2168
            self._add_subprocess_log(trace._get_brz_log_filename())
1982
2169
            command = [sys.executable]
1983
2170
            # frozen executables don't need the path to bzr
1984
2171
            if getattr(sys, "frozen", None) is None:
1986
2173
            if not allow_plugins:
1987
2174
                command.append('--no-plugins')
1988
2175
            command.extend(process_args)
1989
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
2176
            process = self._popen(command, stdin=subprocess.PIPE,
 
2177
                                  stdout=subprocess.PIPE,
 
2178
                                  stderr=stderr)
1990
2179
        finally:
1991
2180
            restore_environment()
1992
2181
            if cwd is not None:
1994
2183
 
1995
2184
        return process
1996
2185
 
 
2186
    def _add_subprocess_log(self, log_file_path):
 
2187
        if len(self._log_files) == 0:
 
2188
            # Register an addCleanup func.  We do this on the first call to
 
2189
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2190
            # addCleanup is registered after any cleanups for tempdirs that
 
2191
            # subclasses might create, which will probably remove the log file
 
2192
            # we want to read.
 
2193
            self.addCleanup(self._subprocess_log_cleanup)
 
2194
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2195
        # twice.
 
2196
        self._log_files.add(log_file_path)
 
2197
 
 
2198
    def _subprocess_log_cleanup(self):
 
2199
        for count, log_file_path in enumerate(self._log_files):
 
2200
            # We use buffer_now=True to avoid holding the file open beyond
 
2201
            # the life of this function, which might interfere with e.g.
 
2202
            # cleaning tempdirs on Windows.
 
2203
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2204
            #detail_content = content.content_from_file(
 
2205
            #    log_file_path, buffer_now=True)
 
2206
            with open(log_file_path, 'rb') as log_file:
 
2207
                log_file_bytes = log_file.read()
 
2208
            detail_content = content.Content(content.ContentType("text",
 
2209
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2210
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2211
                detail_content)
 
2212
 
1997
2213
    def _popen(self, *args, **kwargs):
1998
2214
        """Place a call to Popen.
1999
2215
 
2000
2216
        Allows tests to override this method to intercept the calls made to
2001
2217
        Popen for introspection.
2002
2218
        """
2003
 
        return Popen(*args, **kwargs)
 
2219
        return subprocess.Popen(*args, **kwargs)
2004
2220
 
2005
2221
    def get_source_path(self):
2006
 
        """Return the path of the directory containing bzrlib."""
2007
 
        return os.path.dirname(os.path.dirname(bzrlib.__file__))
 
2222
        """Return the path of the directory containing breezy."""
 
2223
        return os.path.dirname(os.path.dirname(breezy.__file__))
2008
2224
 
2009
 
    def get_bzr_path(self):
2010
 
        """Return the path of the 'bzr' executable for this test suite."""
2011
 
        bzr_path = self.get_source_path()+'/bzr'
2012
 
        if not os.path.isfile(bzr_path):
 
2225
    def get_brz_path(self):
 
2226
        """Return the path of the 'brz' executable for this test suite."""
 
2227
        brz_path = os.path.join(self.get_source_path(), "brz")
 
2228
        if not os.path.isfile(brz_path):
2013
2229
            # We are probably installed. Assume sys.argv is the right file
2014
 
            bzr_path = sys.argv[0]
2015
 
        return bzr_path
 
2230
            brz_path = sys.argv[0]
 
2231
        return brz_path
2016
2232
 
2017
2233
    def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
2018
2234
                              universal_newlines=False, process_args=None):
2036
2252
        if retcode is not None and retcode != process.returncode:
2037
2253
            if process_args is None:
2038
2254
                process_args = "(unknown args)"
2039
 
            mutter('Output of bzr %s:\n%s', process_args, out)
2040
 
            mutter('Error for bzr %s:\n%s', process_args, err)
2041
 
            self.fail('Command bzr %s failed with retcode %s != %s'
 
2255
            trace.mutter('Output of brz %s:\n%s', process_args, out)
 
2256
            trace.mutter('Error for brz %s:\n%s', process_args, err)
 
2257
            self.fail('Command brz %s failed with retcode %s != %s'
2042
2258
                      % (process_args, retcode, process.returncode))
2043
2259
        return [out, err]
2044
2260
 
2045
 
    def check_inventory_shape(self, inv, shape):
2046
 
        """Compare an inventory to a list of expected names.
 
2261
    def check_tree_shape(self, tree, shape):
 
2262
        """Compare a tree to a list of expected names.
2047
2263
 
2048
2264
        Fail if they are not precisely equal.
2049
2265
        """
2050
2266
        extras = []
2051
2267
        shape = list(shape)             # copy
2052
 
        for path, ie in inv.entries():
 
2268
        for path, ie in tree.iter_entries_by_dir():
2053
2269
            name = path.replace('\\', '/')
2054
2270
            if ie.kind == 'directory':
2055
2271
                name = name + '/'
2056
 
            if name in shape:
 
2272
            if name == "/":
 
2273
                pass # ignore root entry
 
2274
            elif name in shape:
2057
2275
                shape.remove(name)
2058
2276
            else:
2059
2277
                extras.append(name)
2070
2288
        if not callable(a_callable):
2071
2289
            raise ValueError("a_callable must be callable.")
2072
2290
        if stdin is None:
2073
 
            stdin = StringIO("")
 
2291
            stdin = BytesIO("")
2074
2292
        if stdout is None:
2075
2293
            if getattr(self, "_log_file", None) is not None:
2076
2294
                stdout = self._log_file
2077
2295
            else:
2078
 
                stdout = StringIO()
 
2296
                stdout = BytesIO()
2079
2297
        if stderr is None:
2080
2298
            if getattr(self, "_log_file", None is not None):
2081
2299
                stderr = self._log_file
2082
2300
            else:
2083
 
                stderr = StringIO()
 
2301
                stderr = BytesIO()
2084
2302
        real_stdin = sys.stdin
2085
2303
        real_stdout = sys.stdout
2086
2304
        real_stderr = sys.stderr
2100
2318
 
2101
2319
        Tests that expect to provoke LockContention errors should call this.
2102
2320
        """
2103
 
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2321
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2104
2322
 
2105
2323
    def make_utf8_encoded_stringio(self, encoding_type=None):
2106
 
        """Return a StringIOWrapper instance, that will encode Unicode
2107
 
        input to UTF-8.
2108
 
        """
 
2324
        """Return a wrapped BytesIO, that will encode text input to UTF-8."""
2109
2325
        if encoding_type is None:
2110
2326
            encoding_type = 'strict'
2111
 
        sio = StringIO()
 
2327
        bio = BytesIO()
2112
2328
        output_encoding = 'utf-8'
2113
 
        sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
 
2329
        sio = codecs.getwriter(output_encoding)(bio, errors=encoding_type)
2114
2330
        sio.encoding = output_encoding
2115
2331
        return sio
2116
2332
 
2117
2333
    def disable_verb(self, verb):
2118
2334
        """Disable a smart server verb for one test."""
2119
 
        from bzrlib.smart import request
 
2335
        from breezy.smart import request
2120
2336
        request_handlers = request.request_handlers
2121
2337
        orig_method = request_handlers.get(verb)
 
2338
        orig_info = request_handlers.get_info(verb)
2122
2339
        request_handlers.remove(verb)
2123
 
        self.addCleanup(request_handlers.register, verb, orig_method)
 
2340
        self.addCleanup(request_handlers.register, verb, orig_method,
 
2341
            info=orig_info)
 
2342
 
 
2343
    def __hash__(self):
 
2344
        return id(self)
2124
2345
 
2125
2346
 
2126
2347
class CapturedCall(object):
2149
2370
class TestCaseWithMemoryTransport(TestCase):
2150
2371
    """Common test class for tests that do not need disk resources.
2151
2372
 
2152
 
    Tests that need disk resources should derive from TestCaseWithTransport.
2153
 
 
2154
 
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2155
 
 
2156
 
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
2373
    Tests that need disk resources should derive from TestCaseInTempDir
 
2374
    orTestCaseWithTransport.
 
2375
 
 
2376
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all brz tests.
 
2377
 
 
2378
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2157
2379
    a directory which does not exist. This serves to help ensure test isolation
2158
 
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
2159
 
    must exist. However, TestCaseWithMemoryTransport does not offer local
2160
 
    file defaults for the transport in tests, nor does it obey the command line
 
2380
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2381
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2382
    defaults for the transport in tests, nor does it obey the command line
2161
2383
    override, so tests that accidentally write to the common directory should
2162
2384
    be rare.
2163
2385
 
2164
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
2165
 
    a .bzr directory that stops us ascending higher into the filesystem.
 
2386
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2387
        ``.bzr`` directory that stops us ascending higher into the filesystem.
2166
2388
    """
2167
2389
 
2168
2390
    TEST_ROOT = None
2178
2400
        self.transport_readonly_server = None
2179
2401
        self.__vfs_server = None
2180
2402
 
 
2403
    def setUp(self):
 
2404
        super(TestCaseWithMemoryTransport, self).setUp()
 
2405
 
 
2406
        def _add_disconnect_cleanup(transport):
 
2407
            """Schedule disconnection of given transport at test cleanup
 
2408
 
 
2409
            This needs to happen for all connected transports or leaks occur.
 
2410
 
 
2411
            Note reconnections may mean we call disconnect multiple times per
 
2412
            transport which is suboptimal but seems harmless.
 
2413
            """
 
2414
            self.addCleanup(transport.disconnect)
 
2415
 
 
2416
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
 
2417
            _add_disconnect_cleanup, None)
 
2418
 
 
2419
        self._make_test_root()
 
2420
        self.addCleanup(os.chdir, osutils.getcwd())
 
2421
        self.makeAndChdirToTestDir()
 
2422
        self.overrideEnvironmentForTesting()
 
2423
        self.__readonly_server = None
 
2424
        self.__server = None
 
2425
        self.reduceLockdirTimeout()
 
2426
        # Each test may use its own config files even if the local config files
 
2427
        # don't actually exist. They'll rightly fail if they try to create them
 
2428
        # though.
 
2429
        self.overrideAttr(config, '_shared_stores', {})
 
2430
 
2181
2431
    def get_transport(self, relpath=None):
2182
2432
        """Return a writeable transport.
2183
2433
 
2186
2436
 
2187
2437
        :param relpath: a path relative to the base url.
2188
2438
        """
2189
 
        t = get_transport(self.get_url(relpath))
 
2439
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2190
2440
        self.assertFalse(t.is_readonly())
2191
2441
        return t
2192
2442
 
2198
2448
 
2199
2449
        :param relpath: a path relative to the base url.
2200
2450
        """
2201
 
        t = get_transport(self.get_readonly_url(relpath))
 
2451
        t = _mod_transport.get_transport_from_url(
 
2452
            self.get_readonly_url(relpath))
2202
2453
        self.assertTrue(t.is_readonly())
2203
2454
        return t
2204
2455
 
2325
2576
        real branch.
2326
2577
        """
2327
2578
        root = TestCaseWithMemoryTransport.TEST_ROOT
2328
 
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2579
        try:
 
2580
            # Make sure we get a readable and accessible home for .brz.log
 
2581
            # and/or config files, and not fallback to weird defaults (see
 
2582
            # http://pad.lv/825027).
 
2583
            self.assertIs(None, os.environ.get('BRZ_HOME', None))
 
2584
            os.environ['BRZ_HOME'] = root
 
2585
            wt = controldir.ControlDir.create_standalone_workingtree(root)
 
2586
            del os.environ['BRZ_HOME']
 
2587
        except Exception as e:
 
2588
            self.fail("Fail to initialize the safety net: %r\n" % (e,))
 
2589
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2590
        # we don't need to re-open the wt to check it hasn't changed.
 
2591
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2592
            wt.control_transport.get_bytes('dirstate'))
2329
2593
 
2330
2594
    def _check_safety_net(self):
2331
2595
        """Check that the safety .bzr directory have not been touched.
2334
2598
        propagating. This method ensures than a test did not leaked.
2335
2599
        """
2336
2600
        root = TestCaseWithMemoryTransport.TEST_ROOT
2337
 
        self.permit_url(get_transport(root).base)
2338
 
        wt = workingtree.WorkingTree.open(root)
2339
 
        last_rev = wt.last_revision()
2340
 
        if last_rev != 'null:':
 
2601
        t = _mod_transport.get_transport_from_path(root)
 
2602
        self.permit_url(t.base)
 
2603
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2604
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2341
2605
            # The current test have modified the /bzr directory, we need to
2342
2606
            # recreate a new one or all the followng tests will fail.
2343
2607
            # If you need to inspect its content uncomment the following line
2375
2639
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2376
2640
        self.permit_dir(self.test_dir)
2377
2641
 
2378
 
    def make_branch(self, relpath, format=None):
 
2642
    def make_branch(self, relpath, format=None, name=None):
2379
2643
        """Create a branch on the transport at relpath."""
2380
2644
        repo = self.make_repository(relpath, format=format)
2381
 
        return repo.bzrdir.create_branch()
 
2645
        return repo.bzrdir.create_branch(append_revisions_only=False,
 
2646
                                         name=name)
 
2647
 
 
2648
    def get_default_format(self):
 
2649
        return 'default'
 
2650
 
 
2651
    def resolve_format(self, format):
 
2652
        """Resolve an object to a ControlDir format object.
 
2653
 
 
2654
        The initial format object can either already be
 
2655
        a ControlDirFormat, None (for the default format),
 
2656
        or a string with the name of the control dir format.
 
2657
 
 
2658
        :param format: Object to resolve
 
2659
        :return A ControlDirFormat instance
 
2660
        """
 
2661
        if format is None:
 
2662
            format = self.get_default_format()
 
2663
        if isinstance(format, basestring):
 
2664
            format = controldir.format_registry.make_bzrdir(format)
 
2665
        return format
2382
2666
 
2383
2667
    def make_bzrdir(self, relpath, format=None):
2384
2668
        try:
2385
2669
            # might be a relative or absolute path
2386
2670
            maybe_a_url = self.get_url(relpath)
2387
2671
            segments = maybe_a_url.rsplit('/', 1)
2388
 
            t = get_transport(maybe_a_url)
 
2672
            t = _mod_transport.get_transport(maybe_a_url)
2389
2673
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2390
2674
                t.ensure_base()
2391
 
            if format is None:
2392
 
                format = 'default'
2393
 
            if isinstance(format, basestring):
2394
 
                format = bzrdir.format_registry.make_bzrdir(format)
 
2675
            format = self.resolve_format(format)
2395
2676
            return format.initialize_on_transport(t)
2396
2677
        except errors.UninitializableFormat:
2397
2678
            raise TestSkipped("Format %s is not initializable." % format)
2398
2679
 
2399
 
    def make_repository(self, relpath, shared=False, format=None):
 
2680
    def make_repository(self, relpath, shared=None, format=None):
2400
2681
        """Create a repository on our default transport at relpath.
2401
2682
 
2402
2683
        Note that relpath must be a relative path, not a full url.
2408
2689
        made_control = self.make_bzrdir(relpath, format=format)
2409
2690
        return made_control.create_repository(shared=shared)
2410
2691
 
2411
 
    def make_smart_server(self, path):
 
2692
    def make_smart_server(self, path, backing_server=None):
 
2693
        if backing_server is None:
 
2694
            backing_server = self.get_server()
2412
2695
        smart_server = test_server.SmartTCPServer_for_testing()
2413
 
        self.start_server(smart_server, self.get_server())
2414
 
        remote_transport = get_transport(smart_server.get_url()).clone(path)
 
2696
        self.start_server(smart_server, backing_server)
 
2697
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
 
2698
                                                   ).clone(path)
2415
2699
        return remote_transport
2416
2700
 
2417
2701
    def make_branch_and_memory_tree(self, relpath, format=None):
2425
2709
 
2426
2710
    def overrideEnvironmentForTesting(self):
2427
2711
        test_home_dir = self.test_home_dir
2428
 
        if isinstance(test_home_dir, unicode):
 
2712
        if isinstance(test_home_dir, text_type):
2429
2713
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2430
 
        os.environ['HOME'] = test_home_dir
2431
 
        os.environ['BZR_HOME'] = test_home_dir
2432
 
 
2433
 
    def setUp(self):
2434
 
        super(TestCaseWithMemoryTransport, self).setUp()
2435
 
        self._make_test_root()
2436
 
        self.addCleanup(os.chdir, os.getcwdu())
2437
 
        self.makeAndChdirToTestDir()
2438
 
        self.overrideEnvironmentForTesting()
2439
 
        self.__readonly_server = None
2440
 
        self.__server = None
2441
 
        self.reduceLockdirTimeout()
 
2714
        self.overrideEnv('HOME', test_home_dir)
 
2715
        self.overrideEnv('BRZ_HOME', test_home_dir)
2442
2716
 
2443
2717
    def setup_smart_server_with_call_log(self):
2444
2718
        """Sets up a smart server as the transport server with a call log."""
2445
2719
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2720
        self.hpss_connections = []
2446
2721
        self.hpss_calls = []
2447
2722
        import traceback
2448
2723
        # Skip the current stack down to the caller of
2451
2726
        def capture_hpss_call(params):
2452
2727
            self.hpss_calls.append(
2453
2728
                CapturedCall(params, prefix_length))
 
2729
        def capture_connect(transport):
 
2730
            self.hpss_connections.append(transport)
2454
2731
        client._SmartClient.hooks.install_named_hook(
2455
2732
            'call', capture_hpss_call, None)
 
2733
        _mod_transport.Transport.hooks.install_named_hook(
 
2734
            'post_connect', capture_connect, None)
2456
2735
 
2457
2736
    def reset_smart_call_log(self):
2458
2737
        self.hpss_calls = []
 
2738
        self.hpss_connections = []
2459
2739
 
2460
2740
 
2461
2741
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2480
2760
 
2481
2761
    OVERRIDE_PYTHON = 'python'
2482
2762
 
 
2763
    def setUp(self):
 
2764
        super(TestCaseInTempDir, self).setUp()
 
2765
        # Remove the protection set in isolated_environ, we have a proper
 
2766
        # access to disk resources now.
 
2767
        self.overrideEnv('BRZ_LOG', None)
 
2768
 
2483
2769
    def check_file_contents(self, filename, expect):
2484
2770
        self.log("check contents of file %s" % filename)
2485
 
        contents = file(filename, 'r').read()
 
2771
        f = file(filename)
 
2772
        try:
 
2773
            contents = f.read()
 
2774
        finally:
 
2775
            f.close()
2486
2776
        if contents != expect:
2487
2777
            self.log("expected: %r" % expect)
2488
2778
            self.log("actually: %r" % contents)
2521
2811
        # stacking policy to honour; create a bzr dir with an unshared
2522
2812
        # repository (but not a branch - our code would be trying to escape
2523
2813
        # then!) to stop them, and permit it to be read.
2524
 
        # control = bzrdir.BzrDir.create(self.test_base_dir)
 
2814
        # control = controldir.ControlDir.create(self.test_base_dir)
2525
2815
        # control.create_repository()
2526
2816
        self.test_home_dir = self.test_base_dir + '/home'
2527
2817
        os.mkdir(self.test_home_dir)
2562
2852
                "a list or a tuple. Got %r instead" % (shape,))
2563
2853
        # It's OK to just create them using forward slashes on windows.
2564
2854
        if transport is None or transport.is_readonly():
2565
 
            transport = get_transport(".")
 
2855
            transport = _mod_transport.get_transport_from_path(".")
2566
2856
        for name in shape:
2567
2857
            self.assertIsInstance(name, basestring)
2568
2858
            if name[-1] == '/':
2578
2868
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2579
2869
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2580
2870
 
2581
 
    build_tree_contents = treeshape.build_tree_contents
 
2871
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2582
2872
 
2583
2873
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2584
2874
        """Assert whether path or paths are in the WorkingTree"""
2616
2906
    readwrite one must both define get_url() as resolving to os.getcwd().
2617
2907
    """
2618
2908
 
 
2909
    def setUp(self):
 
2910
        super(TestCaseWithTransport, self).setUp()
 
2911
        self.__vfs_server = None
 
2912
 
2619
2913
    def get_vfs_only_server(self):
2620
2914
        """See TestCaseWithMemoryTransport.
2621
2915
 
2653
2947
        # this obviously requires a format that supports branch references
2654
2948
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2655
2949
        # RBC 20060208
 
2950
        format = self.resolve_format(format=format)
 
2951
        if not format.supports_workingtrees:
 
2952
            b = self.make_branch(relpath+'.branch', format=format)
 
2953
            return b.create_checkout(relpath, lightweight=True)
2656
2954
        b = self.make_branch(relpath, format=format)
2657
2955
        try:
2658
2956
            return b.bzrdir.create_workingtree()
2663
2961
            if self.vfs_transport_factory is test_server.LocalURLServer:
2664
2962
                # the branch is colocated on disk, we cannot create a checkout.
2665
2963
                # hopefully callers will expect this.
2666
 
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
 
2964
                local_controldir = controldir.ControlDir.open(
 
2965
                    self.get_vfs_only_url(relpath))
2667
2966
                wt = local_controldir.create_workingtree()
2668
2967
                if wt.branch._format != b._format:
2669
2968
                    wt._branch = b
2699
2998
        self.assertFalse(differences.has_changed(),
2700
2999
            "Trees %r and %r are different: %r" % (left, right, differences))
2701
3000
 
2702
 
    def setUp(self):
2703
 
        super(TestCaseWithTransport, self).setUp()
2704
 
        self.__vfs_server = None
2705
 
 
2706
3001
    def disable_missing_extensions_warning(self):
2707
3002
        """Some tests expect a precise stderr content.
2708
3003
 
2709
3004
        There is no point in forcing them to duplicate the extension related
2710
3005
        warning.
2711
3006
        """
2712
 
        config.GlobalConfig().set_user_option('ignore_missing_extensions', True)
 
3007
        config.GlobalStack().set('ignore_missing_extensions', True)
2713
3008
 
2714
3009
 
2715
3010
class ChrootedTestCase(TestCaseWithTransport):
2725
3020
    """
2726
3021
 
2727
3022
    def setUp(self):
 
3023
        from breezy.tests import http_server
2728
3024
        super(ChrootedTestCase, self).setUp()
2729
3025
        if not self.vfs_transport_factory == memory.MemoryServer:
2730
 
            self.transport_readonly_server = HttpServer
 
3026
            self.transport_readonly_server = http_server.HttpServer
2731
3027
 
2732
3028
 
2733
3029
def condition_id_re(pattern):
2736
3032
    :param pattern: A regular expression string.
2737
3033
    :return: A callable that returns True if the re matches.
2738
3034
    """
2739
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2740
 
        'test filter')
 
3035
    filter_re = re.compile(pattern, 0)
2741
3036
    def condition(test):
2742
3037
        test_id = test.id()
2743
3038
        return filter_re.search(test_id)
2933
3228
              stream=None,
2934
3229
              result_decorators=None,
2935
3230
              ):
2936
 
    """Run a test suite for bzr selftest.
 
3231
    """Run a test suite for brz selftest.
2937
3232
 
2938
3233
    :param runner_class: The class of runner to use. Must support the
2939
3234
        constructor arguments passed by run_suite which are more than standard
2957
3252
                            result_decorators=result_decorators,
2958
3253
                            )
2959
3254
    runner.stop_on_failure=stop_on_failure
 
3255
    if isinstance(suite, unittest.TestSuite):
 
3256
        # Empty out _tests list of passed suite and populate new TestSuite
 
3257
        suite._tests[:], suite = [], TestSuite(suite)
2960
3258
    # built in decorator factories:
2961
3259
    decorators = [
2962
3260
        random_order(random_seed, runner),
2995
3293
 
2996
3294
 
2997
3295
def fork_decorator(suite):
 
3296
    if getattr(os, "fork", None) is None:
 
3297
        raise errors.BzrCommandError("platform does not support fork,"
 
3298
            " try --parallel=subprocess instead.")
2998
3299
    concurrency = osutils.local_concurrency()
2999
3300
    if concurrency == 1:
3000
3301
        return suite
3031
3332
 
3032
3333
def random_order(random_seed, runner):
3033
3334
    """Return a test suite decorator factory for randomising tests order.
3034
 
    
3035
 
    :param random_seed: now, a string which casts to a long, or a long.
 
3335
 
 
3336
    :param random_seed: now, a string which casts to an integer, or an integer.
3036
3337
    :param runner: A test runner with a stream attribute to report on.
3037
3338
    """
3038
3339
    if random_seed is None:
3055
3356
    return suite
3056
3357
 
3057
3358
 
3058
 
class TestDecorator(TestSuite):
 
3359
class TestDecorator(TestUtil.TestSuite):
3059
3360
    """A decorator for TestCase/TestSuite objects.
3060
 
    
3061
 
    Usually, subclasses should override __iter__(used when flattening test
3062
 
    suites), which we do to filter, reorder, parallelise and so on, run() and
3063
 
    debug().
 
3361
 
 
3362
    Contains rather than flattening suite passed on construction
3064
3363
    """
3065
3364
 
3066
 
    def __init__(self, suite):
3067
 
        TestSuite.__init__(self)
3068
 
        self.addTest(suite)
3069
 
 
3070
 
    def countTestCases(self):
3071
 
        cases = 0
3072
 
        for test in self:
3073
 
            cases += test.countTestCases()
3074
 
        return cases
3075
 
 
3076
 
    def debug(self):
3077
 
        for test in self:
3078
 
            test.debug()
3079
 
 
3080
 
    def run(self, result):
3081
 
        # Use iteration on self, not self._tests, to allow subclasses to hook
3082
 
        # into __iter__.
3083
 
        for test in self:
3084
 
            if result.shouldStop:
3085
 
                break
3086
 
            test.run(result)
3087
 
        return result
 
3365
    def __init__(self, suite=None):
 
3366
        super(TestDecorator, self).__init__()
 
3367
        if suite is not None:
 
3368
            self.addTest(suite)
 
3369
 
 
3370
    # Don't need subclass run method with suite emptying
 
3371
    run = unittest.TestSuite.run
3088
3372
 
3089
3373
 
3090
3374
class CountingDecorator(TestDecorator):
3101
3385
    """A decorator which excludes test matching an exclude pattern."""
3102
3386
 
3103
3387
    def __init__(self, suite, exclude_pattern):
3104
 
        TestDecorator.__init__(self, suite)
3105
 
        self.exclude_pattern = exclude_pattern
3106
 
        self.excluded = False
3107
 
 
3108
 
    def __iter__(self):
3109
 
        if self.excluded:
3110
 
            return iter(self._tests)
3111
 
        self.excluded = True
3112
 
        suite = exclude_tests_by_re(self, self.exclude_pattern)
3113
 
        del self._tests[:]
3114
 
        self.addTests(suite)
3115
 
        return iter(self._tests)
 
3388
        super(ExcludeDecorator, self).__init__(
 
3389
            exclude_tests_by_re(suite, exclude_pattern))
3116
3390
 
3117
3391
 
3118
3392
class FilterTestsDecorator(TestDecorator):
3119
3393
    """A decorator which filters tests to those matching a pattern."""
3120
3394
 
3121
3395
    def __init__(self, suite, pattern):
3122
 
        TestDecorator.__init__(self, suite)
3123
 
        self.pattern = pattern
3124
 
        self.filtered = False
3125
 
 
3126
 
    def __iter__(self):
3127
 
        if self.filtered:
3128
 
            return iter(self._tests)
3129
 
        self.filtered = True
3130
 
        suite = filter_suite_by_re(self, self.pattern)
3131
 
        del self._tests[:]
3132
 
        self.addTests(suite)
3133
 
        return iter(self._tests)
 
3396
        super(FilterTestsDecorator, self).__init__(
 
3397
            filter_suite_by_re(suite, pattern))
3134
3398
 
3135
3399
 
3136
3400
class RandomDecorator(TestDecorator):
3137
3401
    """A decorator which randomises the order of its tests."""
3138
3402
 
3139
3403
    def __init__(self, suite, random_seed, stream):
3140
 
        TestDecorator.__init__(self, suite)
3141
 
        self.random_seed = random_seed
3142
 
        self.randomised = False
3143
 
        self.stream = stream
3144
 
 
3145
 
    def __iter__(self):
3146
 
        if self.randomised:
3147
 
            return iter(self._tests)
3148
 
        self.randomised = True
3149
 
        self.stream.write("Randomizing test order using seed %s\n\n" %
3150
 
            (self.actual_seed()))
 
3404
        random_seed = self.actual_seed(random_seed)
 
3405
        stream.write("Randomizing test order using seed %s\n\n" %
 
3406
            (random_seed,))
3151
3407
        # Initialise the random number generator.
3152
 
        random.seed(self.actual_seed())
3153
 
        suite = randomize_suite(self)
3154
 
        del self._tests[:]
3155
 
        self.addTests(suite)
3156
 
        return iter(self._tests)
 
3408
        random.seed(random_seed)
 
3409
        super(RandomDecorator, self).__init__(randomize_suite(suite))
3157
3410
 
3158
 
    def actual_seed(self):
3159
 
        if self.random_seed == "now":
3160
 
            # We convert the seed to a long to make it reuseable across
 
3411
    @staticmethod
 
3412
    def actual_seed(seed):
 
3413
        if seed == "now":
 
3414
            # We convert the seed to an integer to make it reuseable across
3161
3415
            # invocations (because the user can reenter it).
3162
 
            self.random_seed = long(time.time())
 
3416
            return int(time.time())
3163
3417
        else:
3164
 
            # Convert the seed to a long if we can
 
3418
            # Convert the seed to an integer if we can
3165
3419
            try:
3166
 
                self.random_seed = long(self.random_seed)
3167
 
            except:
 
3420
                return int(seed)
 
3421
            except (TypeError, ValueError):
3168
3422
                pass
3169
 
        return self.random_seed
 
3423
        return seed
3170
3424
 
3171
3425
 
3172
3426
class TestFirstDecorator(TestDecorator):
3173
3427
    """A decorator which moves named tests to the front."""
3174
3428
 
3175
3429
    def __init__(self, suite, pattern):
3176
 
        TestDecorator.__init__(self, suite)
3177
 
        self.pattern = pattern
3178
 
        self.filtered = False
3179
 
 
3180
 
    def __iter__(self):
3181
 
        if self.filtered:
3182
 
            return iter(self._tests)
3183
 
        self.filtered = True
3184
 
        suites = split_suite_by_re(self, self.pattern)
3185
 
        del self._tests[:]
3186
 
        self.addTests(suites)
3187
 
        return iter(self._tests)
 
3430
        super(TestFirstDecorator, self).__init__()
 
3431
        self.addTests(split_suite_by_re(suite, pattern))
3188
3432
 
3189
3433
 
3190
3434
def partition_tests(suite, count):
3191
3435
    """Partition suite into count lists of tests."""
3192
 
    result = []
3193
 
    tests = list(iter_suite_tests(suite))
3194
 
    tests_per_process = int(math.ceil(float(len(tests)) / count))
3195
 
    for block in range(count):
3196
 
        low_test = block * tests_per_process
3197
 
        high_test = low_test + tests_per_process
3198
 
        process_tests = tests[low_test:high_test]
3199
 
        result.append(process_tests)
3200
 
    return result
 
3436
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3437
    # splits up blocks of related tests that might run faster if they shared
 
3438
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3439
    # just one partition.  So the slowest partition shouldn't be much slower
 
3440
    # than the fastest.
 
3441
    partitions = [list() for i in range(count)]
 
3442
    tests = iter_suite_tests(suite)
 
3443
    for partition, test in zip(itertools.cycle(partitions), tests):
 
3444
        partition.append(test)
 
3445
    return partitions
3201
3446
 
3202
3447
 
3203
3448
def workaround_zealous_crypto_random():
3221
3466
    """
3222
3467
    concurrency = osutils.local_concurrency()
3223
3468
    result = []
3224
 
    from subunit import TestProtocolClient, ProtocolTestCase
 
3469
    from subunit import ProtocolTestCase
3225
3470
    from subunit.test_results import AutoTimingTestResultDecorator
3226
3471
    class TestInOtherProcess(ProtocolTestCase):
3227
3472
        # Should be in subunit, I think. RBC.
3233
3478
            try:
3234
3479
                ProtocolTestCase.run(self, result)
3235
3480
            finally:
3236
 
                os.waitpid(self.pid, 0)
 
3481
                pid, status = os.waitpid(self.pid, 0)
 
3482
            # GZ 2011-10-18: If status is nonzero, should report to the result
 
3483
            #                that something went wrong.
3237
3484
 
3238
3485
    test_blocks = partition_tests(suite, concurrency)
 
3486
    # Clear the tests from the original suite so it doesn't keep them alive
 
3487
    suite._tests[:] = []
3239
3488
    for process_tests in test_blocks:
3240
 
        process_suite = TestSuite()
3241
 
        process_suite.addTests(process_tests)
 
3489
        process_suite = TestUtil.TestSuite(process_tests)
 
3490
        # Also clear each split list so new suite has only reference
 
3491
        process_tests[:] = []
3242
3492
        c2pread, c2pwrite = os.pipe()
3243
3493
        pid = os.fork()
3244
3494
        if pid == 0:
3245
 
            workaround_zealous_crypto_random()
3246
3495
            try:
 
3496
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3497
                workaround_zealous_crypto_random()
3247
3498
                os.close(c2pread)
3248
3499
                # Leave stderr and stdout open so we can see test noise
3249
3500
                # Close stdin so that the child goes away if it decides to
3250
3501
                # read from stdin (otherwise its a roulette to see what
3251
3502
                # child actually gets keystrokes for pdb etc).
3252
3503
                sys.stdin.close()
3253
 
                sys.stdin = None
3254
 
                stream = os.fdopen(c2pwrite, 'wb', 1)
3255
3504
                subunit_result = AutoTimingTestResultDecorator(
3256
 
                    TestProtocolClient(stream))
 
3505
                    SubUnitBzrProtocolClient(stream))
3257
3506
                process_suite.run(subunit_result)
3258
 
            finally:
3259
 
                os._exit(0)
 
3507
            except:
 
3508
                # Try and report traceback on stream, but exit with error even
 
3509
                # if stream couldn't be created or something else goes wrong.
 
3510
                # The traceback is formatted to a string and written in one go
 
3511
                # to avoid interleaving lines from multiple failing children.
 
3512
                try:
 
3513
                    stream.write(traceback.format_exc())
 
3514
                finally:
 
3515
                    os._exit(1)
 
3516
            os._exit(0)
3260
3517
        else:
3261
3518
            os.close(c2pwrite)
3262
3519
            stream = os.fdopen(c2pread, 'rb', 1)
3291
3548
    test_blocks = partition_tests(suite, concurrency)
3292
3549
    for process_tests in test_blocks:
3293
3550
        # ugly; currently reimplement rather than reuses TestCase methods.
3294
 
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
3551
        bzr_path = os.path.dirname(os.path.dirname(breezy.__file__))+'/bzr'
3295
3552
        if not os.path.isfile(bzr_path):
3296
3553
            # We are probably installed. Assume sys.argv is the right file
3297
3554
            bzr_path = sys.argv[0]
3309
3566
                '--subunit']
3310
3567
            if '--no-plugins' in sys.argv:
3311
3568
                argv.append('--no-plugins')
3312
 
            # stderr=STDOUT would be ideal, but until we prevent noise on
3313
 
            # stderr it can interrupt the subunit protocol.
3314
 
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3315
 
                bufsize=1)
 
3569
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3570
            # noise on stderr it can interrupt the subunit protocol.
 
3571
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3572
                                      stdout=subprocess.PIPE,
 
3573
                                      stderr=subprocess.PIPE,
 
3574
                                      bufsize=1)
3316
3575
            test = TestInSubprocess(process, test_list_file_name)
3317
3576
            result.append(test)
3318
3577
        except:
3321
3580
    return result
3322
3581
 
3323
3582
 
3324
 
class ForwardingResult(unittest.TestResult):
3325
 
 
3326
 
    def __init__(self, target):
3327
 
        unittest.TestResult.__init__(self)
3328
 
        self.result = target
3329
 
 
3330
 
    def startTest(self, test):
3331
 
        self.result.startTest(test)
3332
 
 
3333
 
    def stopTest(self, test):
3334
 
        self.result.stopTest(test)
3335
 
 
3336
 
    def startTestRun(self):
3337
 
        self.result.startTestRun()
3338
 
 
3339
 
    def stopTestRun(self):
3340
 
        self.result.stopTestRun()
3341
 
 
3342
 
    def addSkip(self, test, reason):
3343
 
        self.result.addSkip(test, reason)
3344
 
 
3345
 
    def addSuccess(self, test):
3346
 
        self.result.addSuccess(test)
3347
 
 
3348
 
    def addError(self, test, err):
3349
 
        self.result.addError(test, err)
3350
 
 
3351
 
    def addFailure(self, test, err):
3352
 
        self.result.addFailure(test, err)
3353
 
ForwardingResult = testtools.ExtendedToOriginalDecorator
3354
 
 
3355
 
 
3356
 
class ProfileResult(ForwardingResult):
 
3583
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3357
3584
    """Generate profiling data for all activity between start and success.
3358
3585
    
3359
3586
    The profile data is appended to the test's _benchcalls attribute and can
3366
3593
    """
3367
3594
 
3368
3595
    def startTest(self, test):
3369
 
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3596
        self.profiler = breezy.lsprof.BzrProfiler()
 
3597
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3598
        # unavoidably fail.
 
3599
        breezy.lsprof.BzrProfiler.profiler_block = 0
3370
3600
        self.profiler.start()
3371
 
        ForwardingResult.startTest(self, test)
 
3601
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3372
3602
 
3373
3603
    def addSuccess(self, test):
3374
3604
        stats = self.profiler.stop()
3378
3608
            test._benchcalls = []
3379
3609
            calls = test._benchcalls
3380
3610
        calls.append(((test.id(), "", ""), stats))
3381
 
        ForwardingResult.addSuccess(self, test)
 
3611
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3382
3612
 
3383
3613
    def stopTest(self, test):
3384
 
        ForwardingResult.stopTest(self, test)
 
3614
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3385
3615
        self.profiler = None
3386
3616
 
3387
3617
 
3388
 
# Controlled by "bzr selftest -E=..." option
 
3618
# Controlled by "brz selftest -E=..." option
3389
3619
# Currently supported:
3390
3620
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
3391
3621
#                           preserves any flags supplied at the command line.
3393
3623
#                           rather than failing tests. And no longer raise
3394
3624
#                           LockContention when fctnl locks are not being used
3395
3625
#                           with proper exclusion rules.
 
3626
#   -Ethreads               Will display thread ident at creation/join time to
 
3627
#                           help track thread leaks
 
3628
#   -Euncollected_cases     Display the identity of any test cases that weren't
 
3629
#                           deallocated after being completed.
 
3630
#   -Econfig_stats          Will collect statistics using addDetail
3396
3631
selftest_debug_flags = set()
3397
3632
 
3398
3633
 
3418
3653
    # XXX: Very ugly way to do this...
3419
3654
    # Disable warning about old formats because we don't want it to disturb
3420
3655
    # any blackbox tests.
3421
 
    from bzrlib import repository
 
3656
    from breezy import repository
3422
3657
    repository._deprecation_warning_done = True
3423
3658
 
3424
3659
    global default_transport
3481
3716
    test_list = []
3482
3717
    try:
3483
3718
        ftest = open(file_name, 'rt')
3484
 
    except IOError, e:
 
3719
    except IOError as e:
3485
3720
        if e.errno != errno.ENOENT:
3486
3721
            raise
3487
3722
        else:
3502
3737
 
3503
3738
    :return: (absents, duplicates) absents is a list containing the test found
3504
3739
        in id_list but not in test_suite, duplicates is a list containing the
3505
 
        test found multiple times in test_suite.
 
3740
        tests found multiple times in test_suite.
3506
3741
 
3507
3742
    When using a prefined test id list, it may occurs that some tests do not
3508
3743
    exist anymore or that some tests use the same id. This function warns the
3566
3801
 
3567
3802
    def refers_to(self, module_name):
3568
3803
        """Is there tests for the module or one of its sub modules."""
3569
 
        return self.modules.has_key(module_name)
 
3804
        return module_name in self.modules
3570
3805
 
3571
3806
    def includes(self, test_id):
3572
 
        return self.tests.has_key(test_id)
 
3807
        return test_id in self.tests
3573
3808
 
3574
3809
 
3575
3810
class TestPrefixAliasRegistry(registry.Registry):
3592
3827
                key, obj, help=help, info=info, override_existing=False)
3593
3828
        except KeyError:
3594
3829
            actual = self.get(key)
3595
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3596
 
                 % (key, actual, obj))
 
3830
            trace.note(
 
3831
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3832
                % (key, actual, obj))
3597
3833
 
3598
3834
    def resolve_alias(self, id_start):
3599
3835
        """Replace the alias by the prefix in the given string.
3614
3850
 
3615
3851
 
3616
3852
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
3617
 
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3618
 
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
 
3853
# appear prefixed ('breezy.' is "replaced" by 'breezy.').
 
3854
test_prefix_alias_registry.register('breezy', 'breezy')
3619
3855
 
3620
3856
# Obvious highest levels prefixes, feel free to add your own via a plugin
3621
 
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3622
 
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3623
 
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3624
 
test_prefix_alias_registry.register('bb', 'bzrlib.tests.blackbox')
3625
 
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
 
3857
test_prefix_alias_registry.register('bd', 'breezy.doc')
 
3858
test_prefix_alias_registry.register('bu', 'breezy.utils')
 
3859
test_prefix_alias_registry.register('bt', 'breezy.tests')
 
3860
test_prefix_alias_registry.register('bb', 'breezy.tests.blackbox')
 
3861
test_prefix_alias_registry.register('bp', 'breezy.plugins')
3626
3862
 
3627
3863
 
3628
3864
def _test_suite_testmod_names():
3629
3865
    """Return the standard list of test module names to test."""
3630
3866
    return [
3631
 
        'bzrlib.doc',
3632
 
        'bzrlib.tests.blackbox',
3633
 
        'bzrlib.tests.commands',
3634
 
        'bzrlib.tests.per_branch',
3635
 
        'bzrlib.tests.per_bzrdir',
3636
 
        'bzrlib.tests.per_bzrdir_colo',
3637
 
        'bzrlib.tests.per_foreign_vcs',
3638
 
        'bzrlib.tests.per_interrepository',
3639
 
        'bzrlib.tests.per_intertree',
3640
 
        'bzrlib.tests.per_inventory',
3641
 
        'bzrlib.tests.per_interbranch',
3642
 
        'bzrlib.tests.per_lock',
3643
 
        'bzrlib.tests.per_merger',
3644
 
        'bzrlib.tests.per_transport',
3645
 
        'bzrlib.tests.per_tree',
3646
 
        'bzrlib.tests.per_pack_repository',
3647
 
        'bzrlib.tests.per_repository',
3648
 
        'bzrlib.tests.per_repository_chk',
3649
 
        'bzrlib.tests.per_repository_reference',
3650
 
        'bzrlib.tests.per_uifactory',
3651
 
        'bzrlib.tests.per_versionedfile',
3652
 
        'bzrlib.tests.per_workingtree',
3653
 
        'bzrlib.tests.test__annotator',
3654
 
        'bzrlib.tests.test__bencode',
3655
 
        'bzrlib.tests.test__chk_map',
3656
 
        'bzrlib.tests.test__dirstate_helpers',
3657
 
        'bzrlib.tests.test__groupcompress',
3658
 
        'bzrlib.tests.test__known_graph',
3659
 
        'bzrlib.tests.test__rio',
3660
 
        'bzrlib.tests.test__simple_set',
3661
 
        'bzrlib.tests.test__static_tuple',
3662
 
        'bzrlib.tests.test__walkdirs_win32',
3663
 
        'bzrlib.tests.test_ancestry',
3664
 
        'bzrlib.tests.test_annotate',
3665
 
        'bzrlib.tests.test_api',
3666
 
        'bzrlib.tests.test_atomicfile',
3667
 
        'bzrlib.tests.test_bad_files',
3668
 
        'bzrlib.tests.test_bisect_multi',
3669
 
        'bzrlib.tests.test_branch',
3670
 
        'bzrlib.tests.test_branchbuilder',
3671
 
        'bzrlib.tests.test_btree_index',
3672
 
        'bzrlib.tests.test_bugtracker',
3673
 
        'bzrlib.tests.test_bundle',
3674
 
        'bzrlib.tests.test_bzrdir',
3675
 
        'bzrlib.tests.test__chunks_to_lines',
3676
 
        'bzrlib.tests.test_cache_utf8',
3677
 
        'bzrlib.tests.test_chk_map',
3678
 
        'bzrlib.tests.test_chk_serializer',
3679
 
        'bzrlib.tests.test_chunk_writer',
3680
 
        'bzrlib.tests.test_clean_tree',
3681
 
        'bzrlib.tests.test_cleanup',
3682
 
        'bzrlib.tests.test_cmdline',
3683
 
        'bzrlib.tests.test_commands',
3684
 
        'bzrlib.tests.test_commit',
3685
 
        'bzrlib.tests.test_commit_merge',
3686
 
        'bzrlib.tests.test_config',
3687
 
        'bzrlib.tests.test_conflicts',
3688
 
        'bzrlib.tests.test_counted_lock',
3689
 
        'bzrlib.tests.test_crash',
3690
 
        'bzrlib.tests.test_decorators',
3691
 
        'bzrlib.tests.test_delta',
3692
 
        'bzrlib.tests.test_debug',
3693
 
        'bzrlib.tests.test_deprecated_graph',
3694
 
        'bzrlib.tests.test_diff',
3695
 
        'bzrlib.tests.test_directory_service',
3696
 
        'bzrlib.tests.test_dirstate',
3697
 
        'bzrlib.tests.test_email_message',
3698
 
        'bzrlib.tests.test_eol_filters',
3699
 
        'bzrlib.tests.test_errors',
3700
 
        'bzrlib.tests.test_export',
3701
 
        'bzrlib.tests.test_extract',
3702
 
        'bzrlib.tests.test_fetch',
3703
 
        'bzrlib.tests.test_fifo_cache',
3704
 
        'bzrlib.tests.test_filters',
3705
 
        'bzrlib.tests.test_ftp_transport',
3706
 
        'bzrlib.tests.test_foreign',
3707
 
        'bzrlib.tests.test_generate_docs',
3708
 
        'bzrlib.tests.test_generate_ids',
3709
 
        'bzrlib.tests.test_globbing',
3710
 
        'bzrlib.tests.test_gpg',
3711
 
        'bzrlib.tests.test_graph',
3712
 
        'bzrlib.tests.test_groupcompress',
3713
 
        'bzrlib.tests.test_hashcache',
3714
 
        'bzrlib.tests.test_help',
3715
 
        'bzrlib.tests.test_hooks',
3716
 
        'bzrlib.tests.test_http',
3717
 
        'bzrlib.tests.test_http_response',
3718
 
        'bzrlib.tests.test_https_ca_bundle',
3719
 
        'bzrlib.tests.test_identitymap',
3720
 
        'bzrlib.tests.test_ignores',
3721
 
        'bzrlib.tests.test_index',
3722
 
        'bzrlib.tests.test_import_tariff',
3723
 
        'bzrlib.tests.test_info',
3724
 
        'bzrlib.tests.test_inv',
3725
 
        'bzrlib.tests.test_inventory_delta',
3726
 
        'bzrlib.tests.test_knit',
3727
 
        'bzrlib.tests.test_lazy_import',
3728
 
        'bzrlib.tests.test_lazy_regex',
3729
 
        'bzrlib.tests.test_lock',
3730
 
        'bzrlib.tests.test_lockable_files',
3731
 
        'bzrlib.tests.test_lockdir',
3732
 
        'bzrlib.tests.test_log',
3733
 
        'bzrlib.tests.test_lru_cache',
3734
 
        'bzrlib.tests.test_lsprof',
3735
 
        'bzrlib.tests.test_mail_client',
3736
 
        'bzrlib.tests.test_memorytree',
3737
 
        'bzrlib.tests.test_merge',
3738
 
        'bzrlib.tests.test_merge3',
3739
 
        'bzrlib.tests.test_merge_core',
3740
 
        'bzrlib.tests.test_merge_directive',
3741
 
        'bzrlib.tests.test_missing',
3742
 
        'bzrlib.tests.test_msgeditor',
3743
 
        'bzrlib.tests.test_multiparent',
3744
 
        'bzrlib.tests.test_mutabletree',
3745
 
        'bzrlib.tests.test_nonascii',
3746
 
        'bzrlib.tests.test_options',
3747
 
        'bzrlib.tests.test_osutils',
3748
 
        'bzrlib.tests.test_osutils_encodings',
3749
 
        'bzrlib.tests.test_pack',
3750
 
        'bzrlib.tests.test_patch',
3751
 
        'bzrlib.tests.test_patches',
3752
 
        'bzrlib.tests.test_permissions',
3753
 
        'bzrlib.tests.test_plugins',
3754
 
        'bzrlib.tests.test_progress',
3755
 
        'bzrlib.tests.test_read_bundle',
3756
 
        'bzrlib.tests.test_reconcile',
3757
 
        'bzrlib.tests.test_reconfigure',
3758
 
        'bzrlib.tests.test_registry',
3759
 
        'bzrlib.tests.test_remote',
3760
 
        'bzrlib.tests.test_rename_map',
3761
 
        'bzrlib.tests.test_repository',
3762
 
        'bzrlib.tests.test_revert',
3763
 
        'bzrlib.tests.test_revision',
3764
 
        'bzrlib.tests.test_revisionspec',
3765
 
        'bzrlib.tests.test_revisiontree',
3766
 
        'bzrlib.tests.test_rio',
3767
 
        'bzrlib.tests.test_rules',
3768
 
        'bzrlib.tests.test_sampler',
3769
 
        'bzrlib.tests.test_script',
3770
 
        'bzrlib.tests.test_selftest',
3771
 
        'bzrlib.tests.test_serializer',
3772
 
        'bzrlib.tests.test_setup',
3773
 
        'bzrlib.tests.test_sftp_transport',
3774
 
        'bzrlib.tests.test_shelf',
3775
 
        'bzrlib.tests.test_shelf_ui',
3776
 
        'bzrlib.tests.test_smart',
3777
 
        'bzrlib.tests.test_smart_add',
3778
 
        'bzrlib.tests.test_smart_request',
3779
 
        'bzrlib.tests.test_smart_transport',
3780
 
        'bzrlib.tests.test_smtp_connection',
3781
 
        'bzrlib.tests.test_source',
3782
 
        'bzrlib.tests.test_ssh_transport',
3783
 
        'bzrlib.tests.test_status',
3784
 
        'bzrlib.tests.test_store',
3785
 
        'bzrlib.tests.test_strace',
3786
 
        'bzrlib.tests.test_subsume',
3787
 
        'bzrlib.tests.test_switch',
3788
 
        'bzrlib.tests.test_symbol_versioning',
3789
 
        'bzrlib.tests.test_tag',
3790
 
        'bzrlib.tests.test_testament',
3791
 
        'bzrlib.tests.test_textfile',
3792
 
        'bzrlib.tests.test_textmerge',
3793
 
        'bzrlib.tests.test_timestamp',
3794
 
        'bzrlib.tests.test_trace',
3795
 
        'bzrlib.tests.test_transactions',
3796
 
        'bzrlib.tests.test_transform',
3797
 
        'bzrlib.tests.test_transport',
3798
 
        'bzrlib.tests.test_transport_log',
3799
 
        'bzrlib.tests.test_tree',
3800
 
        'bzrlib.tests.test_treebuilder',
3801
 
        'bzrlib.tests.test_tsort',
3802
 
        'bzrlib.tests.test_tuned_gzip',
3803
 
        'bzrlib.tests.test_ui',
3804
 
        'bzrlib.tests.test_uncommit',
3805
 
        'bzrlib.tests.test_upgrade',
3806
 
        'bzrlib.tests.test_upgrade_stacked',
3807
 
        'bzrlib.tests.test_urlutils',
3808
 
        'bzrlib.tests.test_version',
3809
 
        'bzrlib.tests.test_version_info',
3810
 
        'bzrlib.tests.test_weave',
3811
 
        'bzrlib.tests.test_whitebox',
3812
 
        'bzrlib.tests.test_win32utils',
3813
 
        'bzrlib.tests.test_workingtree',
3814
 
        'bzrlib.tests.test_workingtree_4',
3815
 
        'bzrlib.tests.test_wsgi',
3816
 
        'bzrlib.tests.test_xml',
 
3867
        'breezy.doc',
 
3868
        'breezy.tests.blackbox',
 
3869
        'breezy.tests.commands',
 
3870
        'breezy.tests.per_branch',
 
3871
        'breezy.tests.per_bzrdir',
 
3872
        'breezy.tests.per_controldir',
 
3873
        'breezy.tests.per_controldir_colo',
 
3874
        'breezy.tests.per_foreign_vcs',
 
3875
        'breezy.tests.per_interrepository',
 
3876
        'breezy.tests.per_intertree',
 
3877
        'breezy.tests.per_inventory',
 
3878
        'breezy.tests.per_interbranch',
 
3879
        'breezy.tests.per_lock',
 
3880
        'breezy.tests.per_merger',
 
3881
        'breezy.tests.per_transport',
 
3882
        'breezy.tests.per_tree',
 
3883
        'breezy.tests.per_pack_repository',
 
3884
        'breezy.tests.per_repository',
 
3885
        'breezy.tests.per_repository_chk',
 
3886
        'breezy.tests.per_repository_reference',
 
3887
        'breezy.tests.per_repository_vf',
 
3888
        'breezy.tests.per_uifactory',
 
3889
        'breezy.tests.per_versionedfile',
 
3890
        'breezy.tests.per_workingtree',
 
3891
        'breezy.tests.test__annotator',
 
3892
        'breezy.tests.test__bencode',
 
3893
        'breezy.tests.test__btree_serializer',
 
3894
        'breezy.tests.test__chk_map',
 
3895
        'breezy.tests.test__dirstate_helpers',
 
3896
        'breezy.tests.test__groupcompress',
 
3897
        'breezy.tests.test__known_graph',
 
3898
        'breezy.tests.test__rio',
 
3899
        'breezy.tests.test__simple_set',
 
3900
        'breezy.tests.test__static_tuple',
 
3901
        'breezy.tests.test__walkdirs_win32',
 
3902
        'breezy.tests.test_ancestry',
 
3903
        'breezy.tests.test_annotate',
 
3904
        'breezy.tests.test_api',
 
3905
        'breezy.tests.test_atomicfile',
 
3906
        'breezy.tests.test_bad_files',
 
3907
        'breezy.tests.test_bisect_multi',
 
3908
        'breezy.tests.test_branch',
 
3909
        'breezy.tests.test_branchbuilder',
 
3910
        'breezy.tests.test_btree_index',
 
3911
        'breezy.tests.test_bugtracker',
 
3912
        'breezy.tests.test_bundle',
 
3913
        'breezy.tests.test_bzrdir',
 
3914
        'breezy.tests.test__chunks_to_lines',
 
3915
        'breezy.tests.test_cache_utf8',
 
3916
        'breezy.tests.test_chk_map',
 
3917
        'breezy.tests.test_chk_serializer',
 
3918
        'breezy.tests.test_chunk_writer',
 
3919
        'breezy.tests.test_clean_tree',
 
3920
        'breezy.tests.test_cleanup',
 
3921
        'breezy.tests.test_cmdline',
 
3922
        'breezy.tests.test_commands',
 
3923
        'breezy.tests.test_commit',
 
3924
        'breezy.tests.test_commit_merge',
 
3925
        'breezy.tests.test_config',
 
3926
        'breezy.tests.test_conflicts',
 
3927
        'breezy.tests.test_controldir',
 
3928
        'breezy.tests.test_counted_lock',
 
3929
        'breezy.tests.test_crash',
 
3930
        'breezy.tests.test_decorators',
 
3931
        'breezy.tests.test_delta',
 
3932
        'breezy.tests.test_debug',
 
3933
        'breezy.tests.test_diff',
 
3934
        'breezy.tests.test_directory_service',
 
3935
        'breezy.tests.test_dirstate',
 
3936
        'breezy.tests.test_email_message',
 
3937
        'breezy.tests.test_eol_filters',
 
3938
        'breezy.tests.test_errors',
 
3939
        'breezy.tests.test_estimate_compressed_size',
 
3940
        'breezy.tests.test_export',
 
3941
        'breezy.tests.test_export_pot',
 
3942
        'breezy.tests.test_extract',
 
3943
        'breezy.tests.test_features',
 
3944
        'breezy.tests.test_fetch',
 
3945
        'breezy.tests.test_fixtures',
 
3946
        'breezy.tests.test_fifo_cache',
 
3947
        'breezy.tests.test_filters',
 
3948
        'breezy.tests.test_filter_tree',
 
3949
        'breezy.tests.test_ftp_transport',
 
3950
        'breezy.tests.test_foreign',
 
3951
        'breezy.tests.test_generate_docs',
 
3952
        'breezy.tests.test_generate_ids',
 
3953
        'breezy.tests.test_globbing',
 
3954
        'breezy.tests.test_gpg',
 
3955
        'breezy.tests.test_graph',
 
3956
        'breezy.tests.test_groupcompress',
 
3957
        'breezy.tests.test_hashcache',
 
3958
        'breezy.tests.test_help',
 
3959
        'breezy.tests.test_hooks',
 
3960
        'breezy.tests.test_http',
 
3961
        'breezy.tests.test_http_response',
 
3962
        'breezy.tests.test_https_ca_bundle',
 
3963
        'breezy.tests.test_https_urllib',
 
3964
        'breezy.tests.test_i18n',
 
3965
        'breezy.tests.test_identitymap',
 
3966
        'breezy.tests.test_ignores',
 
3967
        'breezy.tests.test_index',
 
3968
        'breezy.tests.test_import_tariff',
 
3969
        'breezy.tests.test_info',
 
3970
        'breezy.tests.test_inv',
 
3971
        'breezy.tests.test_inventory_delta',
 
3972
        'breezy.tests.test_knit',
 
3973
        'breezy.tests.test_lazy_import',
 
3974
        'breezy.tests.test_lazy_regex',
 
3975
        'breezy.tests.test_library_state',
 
3976
        'breezy.tests.test_lock',
 
3977
        'breezy.tests.test_lockable_files',
 
3978
        'breezy.tests.test_lockdir',
 
3979
        'breezy.tests.test_log',
 
3980
        'breezy.tests.test_lru_cache',
 
3981
        'breezy.tests.test_lsprof',
 
3982
        'breezy.tests.test_mail_client',
 
3983
        'breezy.tests.test_matchers',
 
3984
        'breezy.tests.test_memorytree',
 
3985
        'breezy.tests.test_merge',
 
3986
        'breezy.tests.test_merge3',
 
3987
        'breezy.tests.test_merge_core',
 
3988
        'breezy.tests.test_merge_directive',
 
3989
        'breezy.tests.test_mergetools',
 
3990
        'breezy.tests.test_missing',
 
3991
        'breezy.tests.test_msgeditor',
 
3992
        'breezy.tests.test_multiparent',
 
3993
        'breezy.tests.test_mutabletree',
 
3994
        'breezy.tests.test_nonascii',
 
3995
        'breezy.tests.test_options',
 
3996
        'breezy.tests.test_osutils',
 
3997
        'breezy.tests.test_osutils_encodings',
 
3998
        'breezy.tests.test_pack',
 
3999
        'breezy.tests.test_patch',
 
4000
        'breezy.tests.test_patches',
 
4001
        'breezy.tests.test_permissions',
 
4002
        'breezy.tests.test_plugins',
 
4003
        'breezy.tests.test_progress',
 
4004
        'breezy.tests.test_pyutils',
 
4005
        'breezy.tests.test_read_bundle',
 
4006
        'breezy.tests.test_reconcile',
 
4007
        'breezy.tests.test_reconfigure',
 
4008
        'breezy.tests.test_registry',
 
4009
        'breezy.tests.test_remote',
 
4010
        'breezy.tests.test_rename_map',
 
4011
        'breezy.tests.test_repository',
 
4012
        'breezy.tests.test_revert',
 
4013
        'breezy.tests.test_revision',
 
4014
        'breezy.tests.test_revisionspec',
 
4015
        'breezy.tests.test_revisiontree',
 
4016
        'breezy.tests.test_rio',
 
4017
        'breezy.tests.test_rules',
 
4018
        'breezy.tests.test_url_policy_open',
 
4019
        'breezy.tests.test_sampler',
 
4020
        'breezy.tests.test_scenarios',
 
4021
        'breezy.tests.test_script',
 
4022
        'breezy.tests.test_selftest',
 
4023
        'breezy.tests.test_serializer',
 
4024
        'breezy.tests.test_setup',
 
4025
        'breezy.tests.test_sftp_transport',
 
4026
        'breezy.tests.test_shelf',
 
4027
        'breezy.tests.test_shelf_ui',
 
4028
        'breezy.tests.test_smart',
 
4029
        'breezy.tests.test_smart_add',
 
4030
        'breezy.tests.test_smart_request',
 
4031
        'breezy.tests.test_smart_signals',
 
4032
        'breezy.tests.test_smart_transport',
 
4033
        'breezy.tests.test_smtp_connection',
 
4034
        'breezy.tests.test_source',
 
4035
        'breezy.tests.test_ssh_transport',
 
4036
        'breezy.tests.test_status',
 
4037
        'breezy.tests.test_store',
 
4038
        'breezy.tests.test_strace',
 
4039
        'breezy.tests.test_subsume',
 
4040
        'breezy.tests.test_switch',
 
4041
        'breezy.tests.test_symbol_versioning',
 
4042
        'breezy.tests.test_tag',
 
4043
        'breezy.tests.test_test_server',
 
4044
        'breezy.tests.test_testament',
 
4045
        'breezy.tests.test_textfile',
 
4046
        'breezy.tests.test_textmerge',
 
4047
        'breezy.tests.test_cethread',
 
4048
        'breezy.tests.test_timestamp',
 
4049
        'breezy.tests.test_trace',
 
4050
        'breezy.tests.test_transactions',
 
4051
        'breezy.tests.test_transform',
 
4052
        'breezy.tests.test_transport',
 
4053
        'breezy.tests.test_transport_log',
 
4054
        'breezy.tests.test_tree',
 
4055
        'breezy.tests.test_treebuilder',
 
4056
        'breezy.tests.test_treeshape',
 
4057
        'breezy.tests.test_tsort',
 
4058
        'breezy.tests.test_tuned_gzip',
 
4059
        'breezy.tests.test_ui',
 
4060
        'breezy.tests.test_uncommit',
 
4061
        'breezy.tests.test_upgrade',
 
4062
        'breezy.tests.test_upgrade_stacked',
 
4063
        'breezy.tests.test_upstream_import',
 
4064
        'breezy.tests.test_urlutils',
 
4065
        'breezy.tests.test_utextwrap',
 
4066
        'breezy.tests.test_version',
 
4067
        'breezy.tests.test_version_info',
 
4068
        'breezy.tests.test_versionedfile',
 
4069
        'breezy.tests.test_vf_search',
 
4070
        'breezy.tests.test_weave',
 
4071
        'breezy.tests.test_whitebox',
 
4072
        'breezy.tests.test_win32utils',
 
4073
        'breezy.tests.test_workingtree',
 
4074
        'breezy.tests.test_workingtree_4',
 
4075
        'breezy.tests.test_wsgi',
 
4076
        'breezy.tests.test_xml',
3817
4077
        ]
3818
4078
 
3819
4079
 
3823
4083
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
3824
4084
        return []
3825
4085
    return [
3826
 
        'bzrlib',
3827
 
        'bzrlib.branchbuilder',
3828
 
        'bzrlib.decorators',
3829
 
        'bzrlib.export',
3830
 
        'bzrlib.inventory',
3831
 
        'bzrlib.iterablefile',
3832
 
        'bzrlib.lockdir',
3833
 
        'bzrlib.merge3',
3834
 
        'bzrlib.option',
3835
 
        'bzrlib.symbol_versioning',
3836
 
        'bzrlib.tests',
3837
 
        'bzrlib.timestamp',
3838
 
        'bzrlib.version_info_formats.format_custom',
 
4086
        'breezy',
 
4087
        'breezy.branchbuilder',
 
4088
        'breezy.decorators',
 
4089
        'breezy.inventory',
 
4090
        'breezy.iterablefile',
 
4091
        'breezy.lockdir',
 
4092
        'breezy.merge3',
 
4093
        'breezy.option',
 
4094
        'breezy.pyutils',
 
4095
        'breezy.symbol_versioning',
 
4096
        'breezy.tests',
 
4097
        'breezy.tests.fixtures',
 
4098
        'breezy.timestamp',
 
4099
        'breezy.transport.http',
 
4100
        'breezy.version_info_formats.format_custom',
3839
4101
        ]
3840
4102
 
3841
4103
 
3842
4104
def test_suite(keep_only=None, starting_with=None):
3843
 
    """Build and return TestSuite for the whole of bzrlib.
 
4105
    """Build and return TestSuite for the whole of breezy.
3844
4106
 
3845
4107
    :param keep_only: A list of test ids limiting the suite returned.
3846
4108
 
3893
4155
        try:
3894
4156
            # note that this really does mean "report only" -- doctest
3895
4157
            # still runs the rest of the examples
3896
 
            doc_suite = doctest.DocTestSuite(mod,
3897
 
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3898
 
        except ValueError, e:
3899
 
            print '**failed to get doctest for: %s\n%s' % (mod, e)
 
4158
            doc_suite = IsolatedDocTestSuite(
 
4159
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4160
        except ValueError as e:
 
4161
            print('**failed to get doctest for: %s\n%s' % (mod, e))
3900
4162
            raise
3901
4163
        if len(doc_suite._tests) == 0:
3902
4164
            raise errors.BzrError("no doctests found in %s" % (mod,))
3903
4165
        suite.addTest(doc_suite)
3904
4166
 
3905
4167
    default_encoding = sys.getdefaultencoding()
3906
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4168
    for name, plugin in _mod_plugin.plugins().items():
3907
4169
        if not interesting_module(plugin.module.__name__):
3908
4170
            continue
3909
4171
        plugin_suite = plugin.test_suite()
3915
4177
        if plugin_suite is not None:
3916
4178
            suite.addTest(plugin_suite)
3917
4179
        if default_encoding != sys.getdefaultencoding():
3918
 
            bzrlib.trace.warning(
 
4180
            trace.warning(
3919
4181
                'Plugin "%s" tried to reset default encoding to: %s', name,
3920
4182
                sys.getdefaultencoding())
3921
4183
            reload(sys)
3936
4198
            # Some tests mentioned in the list are not in the test suite. The
3937
4199
            # list may be out of date, report to the tester.
3938
4200
            for id in not_found:
3939
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4201
                trace.warning('"%s" not found in the test suite', id)
3940
4202
        for id in duplicates:
3941
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4203
            trace.warning('"%s" is used as an id by several tests', id)
3942
4204
 
3943
4205
    return suite
3944
4206
 
3945
4207
 
3946
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4208
def multiply_scenarios(*scenarios):
 
4209
    """Multiply two or more iterables of scenarios.
 
4210
 
 
4211
    It is safe to pass scenario generators or iterators.
 
4212
 
 
4213
    :returns: A list of compound scenarios: the cross-product of all 
 
4214
        scenarios, with the names concatenated and the parameters
 
4215
        merged together.
 
4216
    """
 
4217
    return reduce(_multiply_two_scenarios, map(list, scenarios))
 
4218
 
 
4219
 
 
4220
def _multiply_two_scenarios(scenarios_left, scenarios_right):
3947
4221
    """Multiply two sets of scenarios.
3948
4222
 
3949
4223
    :returns: the cartesian product of the two sets of scenarios, that is
3975
4249
    the scenario name at the end of its id(), and updating the test object's
3976
4250
    __dict__ with the scenario_param_dict.
3977
4251
 
3978
 
    >>> import bzrlib.tests.test_sampler
 
4252
    >>> import breezy.tests.test_sampler
3979
4253
    >>> r = multiply_tests(
3980
 
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
 
4254
    ...     breezy.tests.test_sampler.DemoTest('test_nothing'),
3981
4255
    ...     [('one', dict(param=1)),
3982
4256
    ...      ('two', dict(param=2))],
3983
 
    ...     TestSuite())
 
4257
    ...     TestUtil.TestSuite())
3984
4258
    >>> tests = list(iter_suite_tests(r))
3985
4259
    >>> len(tests)
3986
4260
    2
3987
4261
    >>> tests[0].id()
3988
 
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
 
4262
    'breezy.tests.test_sampler.DemoTest.test_nothing(one)'
3989
4263
    >>> tests[0].param
3990
4264
    1
3991
4265
    >>> tests[1].param
4013
4287
    """Copy test and apply scenario to it.
4014
4288
 
4015
4289
    :param test: A test to adapt.
4016
 
    :param scenario: A tuple describing the scenarion.
 
4290
    :param scenario: A tuple describing the scenario.
4017
4291
        The first element of the tuple is the new test id.
4018
4292
        The second element is a dict containing attributes to set on the
4019
4293
        test.
4033
4307
    :param new_id: The id to assign to it.
4034
4308
    :return: The new test.
4035
4309
    """
4036
 
    new_test = copy(test)
 
4310
    new_test = copy.copy(test)
4037
4311
    new_test.id = lambda: new_id
 
4312
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4313
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4314
    # read the test output for parameterized tests, because tracebacks will be
 
4315
    # associated with irrelevant tests.
 
4316
    try:
 
4317
        details = new_test._TestCase__details
 
4318
    except AttributeError:
 
4319
        # must be a different version of testtools than expected.  Do nothing.
 
4320
        pass
 
4321
    else:
 
4322
        # Reset the '__details' dict.
 
4323
        new_test._TestCase__details = {}
4038
4324
    return new_test
4039
4325
 
4040
4326
 
4045
4331
    This is meant to be used inside a modules 'load_tests()' function. It will
4046
4332
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
4047
4333
    against both implementations. Setting 'test.module' to the appropriate
4048
 
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
 
4334
    module. See breezy.tests.test__chk_map.load_tests as an example.
4049
4335
 
4050
4336
    :param standard_tests: A test suite to permute
4051
4337
    :param loader: A TestLoader
4052
4338
    :param py_module_name: The python path to a python module that can always
4053
4339
        be loaded, and will be considered the 'python' implementation. (eg
4054
 
        'bzrlib._chk_map_py')
 
4340
        'breezy._chk_map_py')
4055
4341
    :param ext_module_name: The python path to an extension module. If the
4056
4342
        module cannot be loaded, a single test will be added, which notes that
4057
4343
        the module is not available. If it can be loaded, all standard_tests
4061
4347
        the module is available.
4062
4348
    """
4063
4349
 
4064
 
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4350
    from .features import ModuleAvailableFeature
 
4351
    py_module = pyutils.get_named_object(py_module_name)
4065
4352
    scenarios = [
4066
4353
        ('python', {'module': py_module}),
4067
4354
    ]
4088
4375
    # (they are either ascii or mbcs)
4089
4376
    if sys.platform == 'win32':
4090
4377
        # make sure we are using the unicode win32 api
4091
 
        dirname = unicode(dirname)
 
4378
        dirname = text_type(dirname)
4092
4379
    else:
4093
4380
        dirname = dirname.encode(sys.getfilesystemencoding())
4094
4381
    try:
4095
4382
        osutils.rmtree(dirname)
4096
 
    except OSError, e:
 
4383
    except OSError as e:
4097
4384
        # We don't want to fail here because some useful display will be lost
4098
4385
        # otherwise. Polluting the tmp dir is bad, but not giving all the
4099
4386
        # possible info to the test runner is even worse.
4100
4387
        if test_id != None:
4101
4388
            ui.ui_factory.clear_term()
4102
4389
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4390
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4391
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4392
                                    ).encode('ascii', 'replace')
4103
4393
        sys.stderr.write('Unable to remove testing dir %s\n%s'
4104
 
                         % (os.path.basename(dirname), e))
4105
 
 
4106
 
 
4107
 
class Feature(object):
4108
 
    """An operating system Feature."""
4109
 
 
4110
 
    def __init__(self):
4111
 
        self._available = None
4112
 
 
4113
 
    def available(self):
4114
 
        """Is the feature available?
4115
 
 
4116
 
        :return: True if the feature is available.
4117
 
        """
4118
 
        if self._available is None:
4119
 
            self._available = self._probe()
4120
 
        return self._available
4121
 
 
4122
 
    def _probe(self):
4123
 
        """Implement this method in concrete features.
4124
 
 
4125
 
        :return: True if the feature is available.
4126
 
        """
4127
 
        raise NotImplementedError
4128
 
 
4129
 
    def __str__(self):
4130
 
        if getattr(self, 'feature_name', None):
4131
 
            return self.feature_name()
4132
 
        return self.__class__.__name__
4133
 
 
4134
 
 
4135
 
class _SymlinkFeature(Feature):
4136
 
 
4137
 
    def _probe(self):
4138
 
        return osutils.has_symlinks()
4139
 
 
4140
 
    def feature_name(self):
4141
 
        return 'symlinks'
4142
 
 
4143
 
SymlinkFeature = _SymlinkFeature()
4144
 
 
4145
 
 
4146
 
class _HardlinkFeature(Feature):
4147
 
 
4148
 
    def _probe(self):
4149
 
        return osutils.has_hardlinks()
4150
 
 
4151
 
    def feature_name(self):
4152
 
        return 'hardlinks'
4153
 
 
4154
 
HardlinkFeature = _HardlinkFeature()
4155
 
 
4156
 
 
4157
 
class _OsFifoFeature(Feature):
4158
 
 
4159
 
    def _probe(self):
4160
 
        return getattr(os, 'mkfifo', None)
4161
 
 
4162
 
    def feature_name(self):
4163
 
        return 'filesystem fifos'
4164
 
 
4165
 
OsFifoFeature = _OsFifoFeature()
4166
 
 
4167
 
 
4168
 
class _UnicodeFilenameFeature(Feature):
4169
 
    """Does the filesystem support Unicode filenames?"""
4170
 
 
4171
 
    def _probe(self):
4172
 
        try:
4173
 
            # Check for character combinations unlikely to be covered by any
4174
 
            # single non-unicode encoding. We use the characters
4175
 
            # - greek small letter alpha (U+03B1) and
4176
 
            # - braille pattern dots-123456 (U+283F).
4177
 
            os.stat(u'\u03b1\u283f')
4178
 
        except UnicodeEncodeError:
4179
 
            return False
4180
 
        except (IOError, OSError):
4181
 
            # The filesystem allows the Unicode filename but the file doesn't
4182
 
            # exist.
4183
 
            return True
4184
 
        else:
4185
 
            # The filesystem allows the Unicode filename and the file exists,
4186
 
            # for some reason.
4187
 
            return True
4188
 
 
4189
 
UnicodeFilenameFeature = _UnicodeFilenameFeature()
4190
 
 
4191
 
 
4192
 
class _CompatabilityThunkFeature(Feature):
4193
 
    """This feature is just a thunk to another feature.
4194
 
 
4195
 
    It issues a deprecation warning if it is accessed, to let you know that you
4196
 
    should really use a different feature.
4197
 
    """
4198
 
 
4199
 
    def __init__(self, dep_version, module, name,
4200
 
                 replacement_name, replacement_module=None):
4201
 
        super(_CompatabilityThunkFeature, self).__init__()
4202
 
        self._module = module
4203
 
        if replacement_module is None:
4204
 
            replacement_module = module
4205
 
        self._replacement_module = replacement_module
4206
 
        self._name = name
4207
 
        self._replacement_name = replacement_name
4208
 
        self._dep_version = dep_version
4209
 
        self._feature = None
4210
 
 
4211
 
    def _ensure(self):
4212
 
        if self._feature is None:
4213
 
            depr_msg = self._dep_version % ('%s.%s'
4214
 
                                            % (self._module, self._name))
4215
 
            use_msg = ' Use %s.%s instead.' % (self._replacement_module,
4216
 
                                               self._replacement_name)
4217
 
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
4218
 
            # Import the new feature and use it as a replacement for the
4219
 
            # deprecated one.
4220
 
            mod = __import__(self._replacement_module, {}, {},
4221
 
                             [self._replacement_name])
4222
 
            self._feature = getattr(mod, self._replacement_name)
4223
 
 
4224
 
    def _probe(self):
4225
 
        self._ensure()
4226
 
        return self._feature._probe()
4227
 
 
4228
 
 
4229
 
class ModuleAvailableFeature(Feature):
4230
 
    """This is a feature than describes a module we want to be available.
4231
 
 
4232
 
    Declare the name of the module in __init__(), and then after probing, the
4233
 
    module will be available as 'self.module'.
4234
 
 
4235
 
    :ivar module: The module if it is available, else None.
4236
 
    """
4237
 
 
4238
 
    def __init__(self, module_name):
4239
 
        super(ModuleAvailableFeature, self).__init__()
4240
 
        self.module_name = module_name
4241
 
 
4242
 
    def _probe(self):
4243
 
        try:
4244
 
            self._module = __import__(self.module_name, {}, {}, [''])
4245
 
            return True
4246
 
        except ImportError:
4247
 
            return False
4248
 
 
4249
 
    @property
4250
 
    def module(self):
4251
 
        if self.available(): # Make sure the probe has been done
4252
 
            return self._module
4253
 
        return None
4254
 
 
4255
 
    def feature_name(self):
4256
 
        return self.module_name
4257
 
 
4258
 
 
4259
 
# This is kept here for compatibility, it is recommended to use
4260
 
# 'bzrlib.tests.feature.paramiko' instead
4261
 
ParamikoFeature = _CompatabilityThunkFeature(
4262
 
    deprecated_in((2,1,0)),
4263
 
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
 
4394
                         % (os.path.basename(dirname), printable_e))
4264
4395
 
4265
4396
 
4266
4397
def probe_unicode_in_user_encoding():
4296
4427
    return None
4297
4428
 
4298
4429
 
4299
 
class _HTTPSServerFeature(Feature):
4300
 
    """Some tests want an https Server, check if one is available.
4301
 
 
4302
 
    Right now, the only way this is available is under python2.6 which provides
4303
 
    an ssl module.
4304
 
    """
4305
 
 
4306
 
    def _probe(self):
4307
 
        try:
4308
 
            import ssl
4309
 
            return True
4310
 
        except ImportError:
4311
 
            return False
4312
 
 
4313
 
    def feature_name(self):
4314
 
        return 'HTTPSServer'
4315
 
 
4316
 
 
4317
 
HTTPSServerFeature = _HTTPSServerFeature()
4318
 
 
4319
 
 
4320
 
class _UnicodeFilename(Feature):
4321
 
    """Does the filesystem support Unicode filenames?"""
4322
 
 
4323
 
    def _probe(self):
4324
 
        try:
4325
 
            os.stat(u'\u03b1')
4326
 
        except UnicodeEncodeError:
4327
 
            return False
4328
 
        except (IOError, OSError):
4329
 
            # The filesystem allows the Unicode filename but the file doesn't
4330
 
            # exist.
4331
 
            return True
4332
 
        else:
4333
 
            # The filesystem allows the Unicode filename and the file exists,
4334
 
            # for some reason.
4335
 
            return True
4336
 
 
4337
 
UnicodeFilename = _UnicodeFilename()
4338
 
 
4339
 
 
4340
 
class _UTF8Filesystem(Feature):
4341
 
    """Is the filesystem UTF-8?"""
4342
 
 
4343
 
    def _probe(self):
4344
 
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
4345
 
            return True
4346
 
        return False
4347
 
 
4348
 
UTF8Filesystem = _UTF8Filesystem()
4349
 
 
4350
 
 
4351
 
class _BreakinFeature(Feature):
4352
 
    """Does this platform support the breakin feature?"""
4353
 
 
4354
 
    def _probe(self):
4355
 
        from bzrlib import breakin
4356
 
        if breakin.determine_signal() is None:
4357
 
            return False
4358
 
        if sys.platform == 'win32':
4359
 
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
4360
 
            # We trigger SIGBREAK via a Console api so we need ctypes to
4361
 
            # access the function
4362
 
            try:
4363
 
                import ctypes
4364
 
            except OSError:
4365
 
                return False
4366
 
        return True
4367
 
 
4368
 
    def feature_name(self):
4369
 
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
4370
 
 
4371
 
 
4372
 
BreakinFeature = _BreakinFeature()
4373
 
 
4374
 
 
4375
 
class _CaseInsCasePresFilenameFeature(Feature):
4376
 
    """Is the file-system case insensitive, but case-preserving?"""
4377
 
 
4378
 
    def _probe(self):
4379
 
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
4380
 
        try:
4381
 
            # first check truly case-preserving for created files, then check
4382
 
            # case insensitive when opening existing files.
4383
 
            name = osutils.normpath(name)
4384
 
            base, rel = osutils.split(name)
4385
 
            found_rel = osutils.canonical_relpath(base, name)
4386
 
            return (found_rel == rel
4387
 
                    and os.path.isfile(name.upper())
4388
 
                    and os.path.isfile(name.lower()))
4389
 
        finally:
4390
 
            os.close(fileno)
4391
 
            os.remove(name)
4392
 
 
4393
 
    def feature_name(self):
4394
 
        return "case-insensitive case-preserving filesystem"
4395
 
 
4396
 
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
4397
 
 
4398
 
 
4399
 
class _CaseInsensitiveFilesystemFeature(Feature):
4400
 
    """Check if underlying filesystem is case-insensitive but *not* case
4401
 
    preserving.
4402
 
    """
4403
 
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
4404
 
    # more likely to be case preserving, so this case is rare.
4405
 
 
4406
 
    def _probe(self):
4407
 
        if CaseInsCasePresFilenameFeature.available():
4408
 
            return False
4409
 
 
4410
 
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
4411
 
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
4412
 
            TestCaseWithMemoryTransport.TEST_ROOT = root
4413
 
        else:
4414
 
            root = TestCaseWithMemoryTransport.TEST_ROOT
4415
 
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
4416
 
            dir=root)
4417
 
        name_a = osutils.pathjoin(tdir, 'a')
4418
 
        name_A = osutils.pathjoin(tdir, 'A')
4419
 
        os.mkdir(name_a)
4420
 
        result = osutils.isdir(name_A)
4421
 
        _rmtree_temp_dir(tdir)
4422
 
        return result
4423
 
 
4424
 
    def feature_name(self):
4425
 
        return 'case-insensitive filesystem'
4426
 
 
4427
 
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
4428
 
 
4429
 
 
4430
 
class _CaseSensitiveFilesystemFeature(Feature):
4431
 
 
4432
 
    def _probe(self):
4433
 
        if CaseInsCasePresFilenameFeature.available():
4434
 
            return False
4435
 
        elif CaseInsensitiveFilesystemFeature.available():
4436
 
            return False
4437
 
        else:
4438
 
            return True
4439
 
 
4440
 
    def feature_name(self):
4441
 
        return 'case-sensitive filesystem'
4442
 
 
4443
 
# new coding style is for feature instances to be lowercase
4444
 
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
4445
 
 
4446
 
 
4447
 
# Kept for compatibility, use bzrlib.tests.features.subunit instead
4448
 
SubUnitFeature = _CompatabilityThunkFeature(
4449
 
    deprecated_in((2,1,0)),
4450
 
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
4451
4430
# Only define SubUnitBzrRunner if subunit is available.
4452
4431
try:
4453
4432
    from subunit import TestProtocolClient
4454
4433
    from subunit.test_results import AutoTimingTestResultDecorator
 
4434
    class SubUnitBzrProtocolClient(TestProtocolClient):
 
4435
 
 
4436
        def stopTest(self, test):
 
4437
            super(SubUnitBzrProtocolClient, self).stopTest(test)
 
4438
            _clear__type_equality_funcs(test)
 
4439
 
 
4440
        def addSuccess(self, test, details=None):
 
4441
            # The subunit client always includes the details in the subunit
 
4442
            # stream, but we don't want to include it in ours.
 
4443
            if details is not None and 'log' in details:
 
4444
                del details['log']
 
4445
            return super(SubUnitBzrProtocolClient, self).addSuccess(
 
4446
                test, details)
 
4447
 
4455
4448
    class SubUnitBzrRunner(TextTestRunner):
4456
4449
        def run(self, test):
4457
4450
            result = AutoTimingTestResultDecorator(
4458
 
                TestProtocolClient(self.stream))
 
4451
                SubUnitBzrProtocolClient(self.stream))
4459
4452
            test.run(result)
4460
4453
            return result
4461
4454
except ImportError:
4462
4455
    pass
4463
 
 
4464
 
class _PosixPermissionsFeature(Feature):
4465
 
 
4466
 
    def _probe(self):
4467
 
        def has_perms():
4468
 
            # create temporary file and check if specified perms are maintained.
4469
 
            import tempfile
4470
 
 
4471
 
            write_perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
4472
 
            f = tempfile.mkstemp(prefix='bzr_perms_chk_')
4473
 
            fd, name = f
4474
 
            os.close(fd)
4475
 
            os.chmod(name, write_perms)
4476
 
 
4477
 
            read_perms = os.stat(name).st_mode & 0777
4478
 
            os.unlink(name)
4479
 
            return (write_perms == read_perms)
4480
 
 
4481
 
        return (os.name == 'posix') and has_perms()
4482
 
 
4483
 
    def feature_name(self):
4484
 
        return 'POSIX permissions support'
4485
 
 
4486
 
posix_permissions_feature = _PosixPermissionsFeature()