/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: 2018-09-14 09:56:35 UTC
  • mto: This revision was merged to the branch mainline in revision 7110.
  • Revision ID: jelmer@jelmer.uk-20180914095635-3ggdkb45o3cs48dk
Fix peeled error.

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 functools
 
33
from io import (
 
34
    BytesIO,
 
35
    StringIO,
 
36
    TextIOWrapper,
 
37
    )
 
38
import itertools
37
39
import logging
38
40
import math
39
41
import os
40
 
from pprint import pformat
 
42
import platform
 
43
import pprint
41
44
import random
42
45
import re
43
46
import shlex
 
47
import site
44
48
import stat
45
 
from subprocess import Popen, PIPE, STDOUT
 
49
import subprocess
46
50
import sys
47
51
import tempfile
48
52
import threading
54
58
import testtools
55
59
# nb: check this before importing anything else from within it
56
60
_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"
 
61
if _testtools_version < (0, 9, 5):
 
62
    raise ImportError("need at least testtools 0.9.5: %s is %r"
59
63
        % (testtools.__file__, _testtools_version))
60
64
from testtools import content
61
65
 
62
 
from bzrlib import (
 
66
import breezy
 
67
from .. import (
63
68
    branchbuilder,
64
 
    bzrdir,
65
 
    chk_map,
 
69
    controldir,
 
70
    commands as _mod_commands,
66
71
    config,
 
72
    i18n,
67
73
    debug,
68
74
    errors,
69
75
    hooks,
70
76
    lock as _mod_lock,
 
77
    lockdir,
71
78
    memorytree,
72
79
    osutils,
73
 
    progress,
 
80
    plugin as _mod_plugin,
 
81
    pyutils,
74
82
    ui,
75
83
    urlutils,
76
84
    registry,
 
85
    symbol_versioning,
 
86
    trace,
 
87
    transport as _mod_transport,
77
88
    workingtree,
78
89
    )
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
 
90
from breezy.bzr import (
 
91
    chk_map,
 
92
    )
86
93
try:
87
 
    import bzrlib.lsprof
 
94
    import breezy.lsprof
88
95
except ImportError:
89
96
    # lsprof not available
90
97
    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,
 
98
from ..sixish import (
 
99
    int2byte,
 
100
    PY3,
 
101
    string_types,
 
102
    text_type,
103
103
    )
104
 
import bzrlib.trace
105
 
from bzrlib.transport import (
106
 
    get_transport,
 
104
from ..bzr.smart import client, request
 
105
from ..transport import (
107
106
    memory,
108
107
    pathfilter,
109
108
    )
110
 
import bzrlib.transport
111
 
from bzrlib.trace import mutter, note
112
 
from bzrlib.tests import (
 
109
from ..tests import (
 
110
    fixtures,
113
111
    test_server,
114
112
    TestUtil,
 
113
    treeshape,
 
114
    ui_testing,
115
115
    )
116
 
from bzrlib.tests.http_server import HttpServer
117
 
from bzrlib.tests.TestUtil import (
118
 
                          TestSuite,
119
 
                          TestLoader,
120
 
                          )
121
 
from bzrlib.tests.treeshape import build_tree_contents
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
 
116
from ..tests.features import _CompatabilityThunkFeature
126
117
 
127
118
# Mark this python module as being part of the implementation
128
119
# of unittest: this gives us better tracebacks where the last
140
131
SUBUNIT_SEEK_SET = 0
141
132
SUBUNIT_SEEK_CUR = 1
142
133
 
143
 
 
144
 
class ExtendedTestResult(unittest._TextTestResult):
 
134
# These are intentionally brought into this namespace. That way plugins, etc
 
135
# can just "from breezy.tests import TestCase, TestLoader, etc"
 
136
TestSuite = TestUtil.TestSuite
 
137
TestLoader = TestUtil.TestLoader
 
138
 
 
139
# Tests should run in a clean and clearly defined environment. The goal is to
 
140
# keep them isolated from the running environment as mush as possible. The test
 
141
# framework ensures the variables defined below are set (or deleted if the
 
142
# value is None) before a test is run and reset to their original value after
 
143
# the test is run. Generally if some code depends on an environment variable,
 
144
# the tests should start without this variable in the environment. There are a
 
145
# few exceptions but you shouldn't violate this rule lightly.
 
146
isolated_environ = {
 
147
    'BRZ_HOME': None,
 
148
    'HOME': None,
 
149
    'GNUPGHOME': None,
 
150
    'XDG_CONFIG_HOME': None,
 
151
    # brz now uses the Win32 API and doesn't rely on APPDATA, but the
 
152
    # tests do check our impls match APPDATA
 
153
    'BRZ_EDITOR': None, # test_msgeditor manipulates this variable
 
154
    'VISUAL': None,
 
155
    'EDITOR': None,
 
156
    'BRZ_EMAIL': None,
 
157
    'BZREMAIL': None, # may still be present in the environment
 
158
    'EMAIL': 'jrandom@example.com', # set EMAIL as brz does not guess
 
159
    'BRZ_PROGRESS_BAR': None,
 
160
    # This should trap leaks to ~/.brz.log. This occurs when tests use TestCase
 
161
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
 
162
    # TestCase should not use disk resources, BRZ_LOG is one.
 
163
    'BRZ_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
164
    'BRZ_PLUGIN_PATH': '-site',
 
165
    'BRZ_DISABLE_PLUGINS': None,
 
166
    'BRZ_PLUGINS_AT': None,
 
167
    'BRZ_CONCURRENCY': None,
 
168
    # Make sure that any text ui tests are consistent regardless of
 
169
    # the environment the test case is run in; you may want tests that
 
170
    # test other combinations.  'dumb' is a reasonable guess for tests
 
171
    # going to a pipe or a BytesIO.
 
172
    'TERM': 'dumb',
 
173
    'LINES': '25',
 
174
    'COLUMNS': '80',
 
175
    'BRZ_COLUMNS': '80',
 
176
    # Disable SSH Agent
 
177
    'SSH_AUTH_SOCK': None,
 
178
    # Proxies
 
179
    'http_proxy': None,
 
180
    'HTTP_PROXY': None,
 
181
    'https_proxy': None,
 
182
    'HTTPS_PROXY': None,
 
183
    'no_proxy': None,
 
184
    'NO_PROXY': None,
 
185
    'all_proxy': None,
 
186
    'ALL_PROXY': None,
 
187
    'BZR_REMOTE_PATH': None,
 
188
    # Generally speaking, we don't want apport reporting on crashes in
 
189
    # the test envirnoment unless we're specifically testing apport,
 
190
    # so that it doesn't leak into the real system environment.  We
 
191
    # use an env var so it propagates to subprocesses.
 
192
    'APPORT_DISABLE': '1',
 
193
    }
 
194
 
 
195
 
 
196
def override_os_environ(test, env=None):
 
197
    """Modify os.environ keeping a copy.
 
198
 
 
199
    :param test: A test instance
 
200
 
 
201
    :param env: A dict containing variable definitions to be installed
 
202
    """
 
203
    if env is None:
 
204
        env = isolated_environ
 
205
    test._original_os_environ = dict(**os.environ)
 
206
    for var in env:
 
207
        osutils.set_or_unset_env(var, env[var])
 
208
        if var not in test._original_os_environ:
 
209
            # The var is new, add it with a value of None, so
 
210
            # restore_os_environ will delete it
 
211
            test._original_os_environ[var] = None
 
212
 
 
213
 
 
214
def restore_os_environ(test):
 
215
    """Restore os.environ to its original state.
 
216
 
 
217
    :param test: A test instance previously passed to override_os_environ.
 
218
    """
 
219
    for var, value in test._original_os_environ.items():
 
220
        # Restore the original value (or delete it if the value has been set to
 
221
        # None in override_os_environ).
 
222
        osutils.set_or_unset_env(var, value)
 
223
 
 
224
 
 
225
def _clear__type_equality_funcs(test):
 
226
    """Cleanup bound methods stored on TestCase instances
 
227
 
 
228
    Clear the dict breaking a few (mostly) harmless cycles in the affected
 
229
    unittests released with Python 2.6 and initial Python 2.7 versions.
 
230
 
 
231
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
 
232
    shipped in Oneiric, an object with no clear method was used, hence the
 
233
    extra complications, see bug 809048 for details.
 
234
    """
 
235
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
236
    if type_equality_funcs is not None:
 
237
        tef_clear = getattr(type_equality_funcs, "clear", None)
 
238
        if tef_clear is None:
 
239
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
 
240
            if tef_instance_dict is not None:
 
241
                tef_clear = tef_instance_dict.clear
 
242
        if tef_clear is not None:
 
243
            tef_clear()
 
244
 
 
245
 
 
246
class ExtendedTestResult(testtools.TextTestResult):
145
247
    """Accepts, reports and accumulates the results of running tests.
146
248
 
147
249
    Compared to the unittest version this class adds support for
150
252
    different types of display.
151
253
 
152
254
    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
 
255
    addFailure or addError methods.  These in turn may redirect to a more
154
256
    specific case for the special test results supported by our extended
155
257
    tests.
156
258
 
168
270
        :param bench_history: Optionally, a writable file object to accumulate
169
271
            benchmark results.
170
272
        """
171
 
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
273
        testtools.TextTestResult.__init__(self, stream)
172
274
        if bench_history is not None:
173
 
            from bzrlib.version import _get_bzr_source_tree
 
275
            from breezy.version import _get_bzr_source_tree
174
276
            src_tree = _get_bzr_source_tree()
175
277
            if src_tree:
176
278
                try:
178
280
                except IndexError:
179
281
                    # XXX: if this is a brand new tree, do the same as if there
180
282
                    # is no branch.
181
 
                    revision_id = ''
 
283
                    revision_id = b''
182
284
            else:
183
285
                # XXX: If there's no branch, what should we do?
184
 
                revision_id = ''
 
286
                revision_id = b''
185
287
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
186
288
        self._bench_history = bench_history
187
289
        self.ui = ui.ui_factory
195
297
        self.count = 0
196
298
        self._overall_start_time = time.time()
197
299
        self._strict = strict
 
300
        self._first_thread_leaker_id = None
 
301
        self._tests_leaking_threads_count = 0
 
302
        self._traceback_from_test = None
198
303
 
199
304
    def stopTestRun(self):
200
305
        run = self.testsRun
201
306
        actionTaken = "Ran"
202
307
        stopTime = time.time()
203
308
        timeTaken = stopTime - self.startTime
204
 
        self.printErrors()
205
 
        self.stream.writeln(self.separator2)
206
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
309
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
 
310
        #                the parent class method is similar have to duplicate
 
311
        self._show_list('ERROR', self.errors)
 
312
        self._show_list('FAIL', self.failures)
 
313
        self.stream.write(self.sep2)
 
314
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
207
315
                            run, run != 1 and "s" or "", timeTaken))
208
 
        self.stream.writeln()
209
316
        if not self.wasSuccessful():
210
317
            self.stream.write("FAILED (")
211
318
            failed, errored = map(len, (self.failures, self.errors))
218
325
                if failed or errored: self.stream.write(", ")
219
326
                self.stream.write("known_failure_count=%d" %
220
327
                    self.known_failure_count)
221
 
            self.stream.writeln(")")
 
328
            self.stream.write(")\n")
222
329
        else:
223
330
            if self.known_failure_count:
224
 
                self.stream.writeln("OK (known_failures=%d)" %
 
331
                self.stream.write("OK (known_failures=%d)\n" %
225
332
                    self.known_failure_count)
226
333
            else:
227
 
                self.stream.writeln("OK")
 
334
                self.stream.write("OK\n")
228
335
        if self.skip_count > 0:
229
336
            skipped = self.skip_count
230
 
            self.stream.writeln('%d test%s skipped' %
 
337
            self.stream.write('%d test%s skipped\n' %
231
338
                                (skipped, skipped != 1 and "s" or ""))
232
339
        if self.unsupported:
233
340
            for feature, count in sorted(self.unsupported.items()):
234
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
341
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
235
342
                    (feature, count))
236
343
        if self._strict:
237
344
            ok = self.wasStrictlySuccessful()
238
345
        else:
239
346
            ok = self.wasSuccessful()
240
 
        if TestCase._first_thread_leaker_id:
 
347
        if self._first_thread_leaker_id:
241
348
            self.stream.write(
242
349
                '%s is leaking threads among %d leaking tests.\n' % (
243
 
                TestCase._first_thread_leaker_id,
244
 
                TestCase._leaking_threads_tests))
 
350
                self._first_thread_leaker_id,
 
351
                self._tests_leaking_threads_count))
245
352
            # We don't report the main thread as an active one.
246
353
            self.stream.write(
247
354
                '%d non-main threads were left active in the end.\n'
248
 
                % (TestCase._active_threads - 1))
 
355
                % (len(self._active_threads) - 1))
249
356
 
250
357
    def getDescription(self, test):
251
358
        return test.id()
256
363
            return float(''.join(details['benchtime'].iter_bytes()))
257
364
        return getattr(testCase, "_benchtime", None)
258
365
 
 
366
    def _delta_to_float(self, a_timedelta, precision):
 
367
        # This calls ceiling to ensure that the most pessimistic view of time
 
368
        # taken is shown (rather than leaving it to the Python %f operator
 
369
        # to decide whether to round/floor/ceiling. This was added when we
 
370
        # had pyp3 test failures that suggest a floor was happening.
 
371
        shift = 10 ** precision
 
372
        return math.ceil((a_timedelta.days * 86400.0 + a_timedelta.seconds +
 
373
            a_timedelta.microseconds / 1000000.0) * shift) / shift
 
374
 
259
375
    def _elapsedTestTimeString(self):
260
376
        """Return a time string for the overall time the current test has taken."""
261
 
        return self._formatTime(time.time() - self._start_time)
 
377
        return self._formatTime(self._delta_to_float(
 
378
            self._now() - self._start_datetime, 3))
262
379
 
263
380
    def _testTimeString(self, testCase):
264
381
        benchmark_time = self._extractBenchmarkTime(testCase)
275
392
 
276
393
    def _shortened_test_description(self, test):
277
394
        what = test.id()
278
 
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
395
        what = re.sub(r'^breezy\.tests\.', '', what)
279
396
        return what
280
397
 
 
398
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
399
    #                multiple times in a row, because the handler is added for
 
400
    #                each test but the container list is shared between cases.
 
401
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
402
    def _record_traceback_from_test(self, exc_info):
 
403
        """Store the traceback from passed exc_info tuple till"""
 
404
        self._traceback_from_test = exc_info[2]
 
405
 
281
406
    def startTest(self, test):
282
 
        unittest.TestResult.startTest(self, test)
 
407
        super(ExtendedTestResult, self).startTest(test)
283
408
        if self.count == 0:
284
409
            self.startTests()
 
410
        self.count += 1
285
411
        self.report_test_start(test)
286
412
        test.number = self.count
287
413
        self._recordTestStartTime()
 
414
        # Make testtools cases give us the real traceback on failure
 
415
        addOnException = getattr(test, "addOnException", None)
 
416
        if addOnException is not None:
 
417
            addOnException(self._record_traceback_from_test)
 
418
        # Only check for thread leaks on breezy derived test cases
 
419
        if isinstance(test, TestCase):
 
420
            test.addCleanup(self._check_leaked_threads, test)
 
421
 
 
422
    def stopTest(self, test):
 
423
        super(ExtendedTestResult, self).stopTest(test)
 
424
        # Manually break cycles, means touching various private things but hey
 
425
        getDetails = getattr(test, "getDetails", None)
 
426
        if getDetails is not None:
 
427
            getDetails().clear()
 
428
        _clear__type_equality_funcs(test)
 
429
        self._traceback_from_test = None
288
430
 
289
431
    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')
 
432
        self.report_tests_starting()
 
433
        self._active_threads = threading.enumerate()
 
434
 
 
435
    def _check_leaked_threads(self, test):
 
436
        """See if any threads have leaked since last call
 
437
 
 
438
        A sample of live threads is stored in the _active_threads attribute,
 
439
        when this method runs it compares the current live threads and any not
 
440
        in the previous sample are treated as having leaked.
 
441
        """
 
442
        now_active_threads = set(threading.enumerate())
 
443
        threads_leaked = now_active_threads.difference(self._active_threads)
 
444
        if threads_leaked:
 
445
            self._report_thread_leak(test, threads_leaked, now_active_threads)
 
446
            self._tests_leaking_threads_count += 1
 
447
            if self._first_thread_leaker_id is None:
 
448
                self._first_thread_leaker_id = test.id()
 
449
            self._active_threads = now_active_threads
307
450
 
308
451
    def _recordTestStartTime(self):
309
452
        """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()
 
453
        self._start_datetime = self._now()
318
454
 
319
455
    def addError(self, test, err):
320
456
        """Tell result that test finished with an error.
322
458
        Called from the TestCase run() method when the test
323
459
        fails with an unexpected error.
324
460
        """
325
 
        self._post_mortem()
326
 
        unittest.TestResult.addError(self, test, err)
 
461
        self._post_mortem(self._traceback_from_test or err[2])
 
462
        super(ExtendedTestResult, self).addError(test, err)
327
463
        self.error_count += 1
328
464
        self.report_error(test, err)
329
465
        if self.stop_early:
330
466
            self.stop()
331
 
        self._cleanupLogFile(test)
332
467
 
333
468
    def addFailure(self, test, err):
334
469
        """Tell result that test failed.
336
471
        Called from the TestCase run() method when the test
337
472
        fails because e.g. an assert() method failed.
338
473
        """
339
 
        self._post_mortem()
340
 
        unittest.TestResult.addFailure(self, test, err)
 
474
        self._post_mortem(self._traceback_from_test or err[2])
 
475
        super(ExtendedTestResult, self).addFailure(test, err)
341
476
        self.failure_count += 1
342
477
        self.report_failure(test, err)
343
478
        if self.stop_early:
344
479
            self.stop()
345
 
        self._cleanupLogFile(test)
346
480
 
347
481
    def addSuccess(self, test, details=None):
348
482
        """Tell result that test completed successfully.
356
490
                    self._formatTime(benchmark_time),
357
491
                    test.id()))
358
492
        self.report_success(test)
359
 
        self._cleanupLogFile(test)
360
 
        unittest.TestResult.addSuccess(self, test)
 
493
        super(ExtendedTestResult, self).addSuccess(test)
361
494
        test._log_contents = ''
362
495
 
363
496
    def addExpectedFailure(self, test, err):
364
497
        self.known_failure_count += 1
365
498
        self.report_known_failure(test, err)
366
499
 
 
500
    def addUnexpectedSuccess(self, test, details=None):
 
501
        """Tell result the test unexpectedly passed, counting as a failure
 
502
 
 
503
        When the minimum version of testtools required becomes 0.9.8 this
 
504
        can be updated to use the new handling there.
 
505
        """
 
506
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
507
        self.failure_count += 1
 
508
        self.report_unexpected_success(test,
 
509
            "".join(details["reason"].iter_text()))
 
510
        if self.stop_early:
 
511
            self.stop()
 
512
 
367
513
    def addNotSupported(self, test, feature):
368
514
        """The test will not be run because of a missing feature.
369
515
        """
386
532
        self.not_applicable_count += 1
387
533
        self.report_not_applicable(test, reason)
388
534
 
389
 
    def _post_mortem(self):
 
535
    def _count_stored_tests(self):
 
536
        """Count of tests instances kept alive due to not succeeding"""
 
537
        return self.error_count + self.failure_count + self.known_failure_count
 
538
 
 
539
    def _post_mortem(self, tb=None):
390
540
        """Start a PDB post mortem session."""
391
 
        if os.environ.get('BZR_TEST_PDB', None):
392
 
            import pdb;pdb.post_mortem()
 
541
        if os.environ.get('BRZ_TEST_PDB', None):
 
542
            import pdb
 
543
            pdb.post_mortem(tb)
393
544
 
394
545
    def progress(self, offset, whence):
395
546
        """The test is adjusting the count of tests to run."""
400
551
        else:
401
552
            raise errors.BzrError("Unknown whence %r" % whence)
402
553
 
403
 
    def report_cleaning_up(self):
404
 
        pass
 
554
    def report_tests_starting(self):
 
555
        """Display information before the test run begins"""
 
556
        if getattr(sys, 'frozen', None) is None:
 
557
            bzr_path = osutils.realpath(sys.argv[0])
 
558
        else:
 
559
            bzr_path = sys.executable
 
560
        self.stream.write(
 
561
            'brz selftest: %s\n' % (bzr_path,))
 
562
        self.stream.write(
 
563
            '   %s\n' % (
 
564
                    breezy.__path__[0],))
 
565
        self.stream.write(
 
566
            '   bzr-%s python-%s %s\n' % (
 
567
                    breezy.version_string,
 
568
                    breezy._format_version_tuple(sys.version_info),
 
569
                    platform.platform(aliased=1),
 
570
                    ))
 
571
        self.stream.write('\n')
 
572
 
 
573
    def report_test_start(self, test):
 
574
        """Display information on the test just about to be run"""
 
575
 
 
576
    def _report_thread_leak(self, test, leaked_threads, active_threads):
 
577
        """Display information on a test that leaked one or more threads"""
 
578
        # GZ 2010-09-09: A leak summary reported separately from the general
 
579
        #                thread debugging would be nice. Tests under subunit
 
580
        #                need something not using stream, perhaps adding a
 
581
        #                testtools details object would be fitting.
 
582
        if 'threads' in selftest_debug_flags:
 
583
            self.stream.write('%s is leaking, active is now %d\n' %
 
584
                (test.id(), len(active_threads)))
405
585
 
406
586
    def startTestRun(self):
407
587
        self.startTime = time.time()
420
600
 
421
601
    def __init__(self, stream, descriptions, verbosity,
422
602
                 bench_history=None,
423
 
                 pb=None,
424
603
                 strict=None,
425
604
                 ):
426
605
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
427
606
            bench_history, strict)
428
 
        # We no longer pass them around, but just rely on the UIFactory stack
429
 
        # for state
430
 
        if pb is not None:
431
 
            warnings.warn("Passing pb to TextTestResult is deprecated")
432
607
        self.pb = self.ui.nested_progress_bar()
433
608
        self.pb.show_pct = False
434
609
        self.pb.show_spinner = False
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:
616
 
            # Python 2.4
617
 
            encode = codec[0]
618
 
        else:
619
 
            encode = codec.encode
620
 
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream)
 
793
        encode = codec.encode
 
794
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
795
        #                so should swap to the plain codecs.StreamWriter
 
796
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
797
            "backslashreplace")
621
798
        stream.encoding = new_encoding
622
 
        self.stream = unittest._WritelnDecorator(stream)
 
799
        self.stream = stream
623
800
        self.descriptions = descriptions
624
801
        self.verbosity = verbosity
625
802
        self._bench_history = bench_history
707
884
    """
708
885
 
709
886
 
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
 
 
 
887
class StringIOWrapper(ui_testing.BytesIOWithEncoding):
 
888
 
 
889
    @symbol_versioning.deprecated_method(
 
890
        symbol_versioning.deprecated_in((3, 0)))
720
891
    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.
 
892
        super(StringIOWrapper, self).__init__(s)
 
893
 
 
894
 
 
895
TestUIFactory = ui_testing.TestUIFactory
 
896
 
 
897
 
 
898
def isolated_doctest_setUp(test):
 
899
    override_os_environ(test)
 
900
    osutils.set_or_unset_env('BRZ_HOME', '/nonexistent')
 
901
    test._orig_ui_factory = ui.ui_factory
 
902
    ui.ui_factory = ui.SilentUIFactory()
 
903
 
 
904
 
 
905
def isolated_doctest_tearDown(test):
 
906
    restore_os_environ(test)
 
907
    ui.ui_factory = test._orig_ui_factory
 
908
 
 
909
 
 
910
def IsolatedDocTestSuite(*args, **kwargs):
 
911
    """Overrides doctest.DocTestSuite to handle isolation.
 
912
 
 
913
    The method is really a factory and users are expected to use it as such.
745
914
    """
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()
 
915
 
 
916
    kwargs['setUp'] = isolated_doctest_setUp
 
917
    kwargs['tearDown'] = isolated_doctest_tearDown
 
918
    return doctest.DocTestSuite(*args, **kwargs)
774
919
 
775
920
 
776
921
class TestCase(testtools.TestCase):
777
 
    """Base class for bzr unit tests.
 
922
    """Base class for brz unit tests.
778
923
 
779
924
    Tests that need access to disk resources should subclass
780
925
    TestCaseInTempDir not TestCase.
786
931
    is read into memory and removed from disk.
787
932
 
788
933
    There are also convenience functions to invoke bzr's command-line
789
 
    routine, and to build and check bzr trees.
 
934
    routine, and to build and check brz trees.
790
935
 
791
936
    In addition to the usual method of overriding tearDown(), this class also
792
 
    allows subclasses to register functions into the _cleanups list, which is
 
937
    allows subclasses to register cleanup functions via addCleanup, which are
793
938
    run in order as the object is torn down.  It's less likely this will be
794
939
    accidentally overlooked.
795
940
    """
796
941
 
797
 
    _active_threads = None
798
 
    _leaking_threads_tests = 0
799
 
    _first_thread_leaker_id = None
800
 
    _log_file_name = None
 
942
    _log_file = None
801
943
    # record lsprof data when performing benchmark calls.
802
944
    _gather_lsprof_in_benchmarks = False
803
945
 
804
946
    def __init__(self, methodName='testMethod'):
805
947
        super(TestCase, self).__init__(methodName)
806
 
        self._cleanups = []
807
948
        self._directory_isolation = True
808
949
        self.exception_handlers.insert(0,
809
950
            (UnavailableFeature, self._do_unsupported_or_skip))
812
953
 
813
954
    def setUp(self):
814
955
        super(TestCase, self).setUp()
 
956
 
 
957
        # At this point we're still accessing the config files in $BRZ_HOME (as
 
958
        # set by the user running selftest).
 
959
        timeout = config.GlobalStack().get('selftest.timeout')
 
960
        if timeout:
 
961
            timeout_fixture = fixtures.TimeoutFixture(timeout)
 
962
            timeout_fixture.setUp()
 
963
            self.addCleanup(timeout_fixture.cleanUp)
 
964
 
815
965
        for feature in getattr(self, '_test_needs_features', []):
816
966
            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
967
        self._cleanEnvironment()
 
968
 
 
969
        self.overrideAttr(breezy.get_global_state(), 'cmdline_overrides',
 
970
                          config.CommandLineStore())
 
971
 
822
972
        self._silenceUI()
823
973
        self._startLogFile()
824
974
        self._benchcalls = []
827
977
        self._track_transports()
828
978
        self._track_locks()
829
979
        self._clear_debug_flags()
830
 
        TestCase._active_threads = threading.activeCount()
831
 
        self.addCleanup(self._check_leaked_threads)
 
980
        # Isolate global verbosity level, to make sure it's reproducible
 
981
        # between tests.  We should get rid of this altogether: bug 656694. --
 
982
        # mbp 20101008
 
983
        self.overrideAttr(breezy.trace, '_verbosity_level', 0)
 
984
        self._log_files = set()
 
985
        # Each key in the ``_counters`` dict holds a value for a different
 
986
        # counter. When the test ends, addDetail() should be used to output the
 
987
        # counter values. This happens in install_counter_hook().
 
988
        self._counters = {}
 
989
        if 'config_stats' in selftest_debug_flags:
 
990
            self._install_config_stats_hooks()
 
991
        # Do not use i18n for tests (unless the test reverses this)
 
992
        i18n.disable_i18n()
832
993
 
833
994
    def debug(self):
834
995
        # debug a frame up.
835
996
        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()
 
997
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
998
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
999
                ).set_trace(sys._getframe().f_back)
 
1000
 
 
1001
    def discardDetail(self, name):
 
1002
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1003
 
 
1004
        eg. brz always adds the 'log' detail at startup, but we don't want to
 
1005
        include it for skipped, xfail, etc tests.
 
1006
 
 
1007
        It is safe to call this for a detail that doesn't exist, in case this
 
1008
        gets called multiple times.
 
1009
        """
 
1010
        # We cheat. details is stored in __details which means we shouldn't
 
1011
        # touch it. but getDetails() returns the dict directly, so we can
 
1012
        # mutate it.
 
1013
        details = self.getDetails()
 
1014
        if name in details:
 
1015
            del details[name]
 
1016
 
 
1017
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1018
        """Install a counting hook.
 
1019
 
 
1020
        Any hook can be counted as long as it doesn't need to return a value.
 
1021
 
 
1022
        :param hooks: Where the hook should be installed.
 
1023
 
 
1024
        :param name: The hook name that will be counted.
 
1025
 
 
1026
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1027
            to ``name``.
 
1028
        """
 
1029
        _counters = self._counters # Avoid closing over self
 
1030
        if counter_name is None:
 
1031
            counter_name = name
 
1032
        if counter_name in _counters:
 
1033
            raise AssertionError('%s is already used as a counter name'
 
1034
                                  % (counter_name,))
 
1035
        _counters[counter_name] = 0
 
1036
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1037
            lambda: [b'%d' % (_counters[counter_name],)]))
 
1038
        def increment_counter(*args, **kwargs):
 
1039
            _counters[counter_name] += 1
 
1040
        label = 'count %s calls' % (counter_name,)
 
1041
        hooks.install_named_hook(name, increment_counter, label)
 
1042
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1043
 
 
1044
    def _install_config_stats_hooks(self):
 
1045
        """Install config hooks to count hook calls.
 
1046
 
 
1047
        """
 
1048
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1049
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1050
                                       'config.%s' % (hook_name,))
 
1051
 
 
1052
        # The OldConfigHooks are private and need special handling to protect
 
1053
        # against recursive tests (tests that run other tests), so we just do
 
1054
        # manually what registering them into _builtin_known_hooks will provide
 
1055
        # us.
 
1056
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1057
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1058
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1059
                                      'old_config.%s' % (hook_name,))
852
1060
 
853
1061
    def _clear_debug_flags(self):
854
1062
        """Prevent externally set debug flags affecting tests.
865
1073
 
866
1074
    def _clear_hooks(self):
867
1075
        # prevent hooks affecting tests
 
1076
        known_hooks = hooks.known_hooks
868
1077
        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)
 
1078
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1079
            current_hooks = getattr(parent, name)
872
1080
            self._preserved_hooks[parent] = (name, current_hooks)
 
1081
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1082
        hooks._lazy_hooks = {}
873
1083
        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)
 
1084
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1085
            factory = known_hooks.get(key)
876
1086
            setattr(parent, name, factory())
877
1087
        # this hook should always be installed
878
1088
        request._install_hook()
907
1117
        # break some locks on purpose and should be taken into account by
908
1118
        # considering that breaking a lock is just a dirty way of releasing it.
909
1119
        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))
 
1120
            message = (
 
1121
                'Different number of acquired and '
 
1122
                'released or broken locks.\n'
 
1123
                'acquired=%s\n'
 
1124
                'released=%s\n'
 
1125
                'broken=%s\n' %
 
1126
                (acquired_locks, released_locks, broken_locks))
913
1127
            if not self._lock_check_thorough:
914
1128
                # Rather than fail, just warn
915
 
                print "Broken test %s: %s" % (self, message)
 
1129
                print("Broken test %s: %s" % (self, message))
916
1130
                return
917
1131
            self.fail(message)
918
1132
 
943
1157
 
944
1158
    def permit_dir(self, name):
945
1159
        """Permit a directory to be used by this test. See permit_url."""
946
 
        name_transport = get_transport(name)
 
1160
        name_transport = _mod_transport.get_transport_from_path(name)
947
1161
        self.permit_url(name)
948
1162
        self.permit_url(name_transport.base)
949
1163
 
950
1164
    def permit_url(self, url):
951
1165
        """Declare that url is an ok url to use in this test.
952
 
        
 
1166
 
953
1167
        Do this for memory transports, temporary test directory etc.
954
 
        
 
1168
 
955
1169
        Do not do this for the current working directory, /tmp, or any other
956
1170
        preexisting non isolated url.
957
1171
        """
960
1174
        self._bzr_selftest_roots.append(url)
961
1175
 
962
1176
    def permit_source_tree_branch_repo(self):
963
 
        """Permit the source tree bzr is running from to be opened.
 
1177
        """Permit the source tree brz is running from to be opened.
964
1178
 
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
 
1179
        Some code such as breezy.version attempts to read from the brz branch
 
1180
        that brz is executing from (if any). This method permits that directory
967
1181
        to be used in the test suite.
968
1182
        """
969
1183
        path = self.get_source_path()
972
1186
            try:
973
1187
                workingtree.WorkingTree.open(path)
974
1188
            except (errors.NotBranchError, errors.NoWorkingTree):
975
 
                return
 
1189
                raise TestSkipped('Needs a working tree of brz sources')
976
1190
        finally:
977
1191
            self.enable_directory_isolation()
978
1192
 
1010
1224
 
1011
1225
    def record_directory_isolation(self):
1012
1226
        """Gather accessed directories to permit later access.
1013
 
        
1014
 
        This is used for tests that access the branch bzr is running from.
 
1227
 
 
1228
        This is used for tests that access the branch brz is running from.
1015
1229
        """
1016
1230
        self._directory_isolation = "record"
1017
1231
 
1028
1242
        self.addCleanup(transport_server.stop_server)
1029
1243
        # Obtain a real transport because if the server supplies a password, it
1030
1244
        # will be hidden from the base on the client side.
1031
 
        t = get_transport(transport_server.get_url())
 
1245
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1032
1246
        # Some transport servers effectively chroot the backing transport;
1033
1247
        # others like SFTPServer don't - users of the transport can walk up the
1034
1248
        # transport to read the entire backing transport. This wouldn't matter
1062
1276
        # TestCase has no safe place it can write to.
1063
1277
        self._bzr_selftest_roots = []
1064
1278
        # 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
 
1279
        # hook into brz dir opening. This leaves a small window of error for
1066
1280
        # transport tests, but they are well known, and we can improve on this
1067
1281
        # step.
1068
 
        bzrdir.BzrDir.hooks.install_named_hook("pre_open",
1069
 
            self._preopen_isolate_transport, "Check bzr directories are safe.")
 
1282
        controldir.ControlDir.hooks.install_named_hook("pre_open",
 
1283
            self._preopen_isolate_transport, "Check brz directories are safe.")
1070
1284
 
1071
1285
    def _ndiff_strings(self, a, b):
1072
1286
        """Return ndiff between two strings containing lines.
1073
1287
 
1074
1288
        A trailing newline is added if missing to make the strings
1075
1289
        print properly."""
1076
 
        if b and b[-1] != '\n':
 
1290
        if b and not b.endswith('\n'):
1077
1291
            b += '\n'
1078
 
        if a and a[-1] != '\n':
 
1292
        if a and not a.endswith('\n'):
1079
1293
            a += '\n'
1080
1294
        difflines = difflib.ndiff(a.splitlines(True),
1081
1295
                                  b.splitlines(True),
1087
1301
        try:
1088
1302
            if a == b:
1089
1303
                return
1090
 
        except UnicodeError, e:
 
1304
        except UnicodeError as e:
1091
1305
            # If we can't compare without getting a UnicodeError, then
1092
1306
            # obviously they are different
1093
 
            mutter('UnicodeError: %s', e)
 
1307
            trace.mutter('UnicodeError: %s', e)
1094
1308
        if message:
1095
1309
            message += '\n'
1096
1310
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1097
1311
            % (message,
1098
 
               pformat(a), pformat(b)))
 
1312
               pprint.pformat(a), pprint.pformat(b)))
1099
1313
 
 
1314
    # FIXME: This is deprecated in unittest2 but plugins may still use it so we
 
1315
    # need a deprecation period for them -- vila 2016-02-01
1100
1316
    assertEquals = assertEqual
1101
1317
 
1102
1318
    def assertEqualDiff(self, a, b, message=None):
1105
1321
        This is intended for use with multi-line strings where it can
1106
1322
        be hard to find the differences by eye.
1107
1323
        """
1108
 
        # TODO: perhaps override assertEquals to call this for strings?
 
1324
        # TODO: perhaps override assertEqual to call this for strings?
1109
1325
        if a == b:
1110
1326
            return
1111
1327
        if message is None:
1112
1328
            message = "texts not equal:\n"
1113
 
        if a + '\n' == b:
 
1329
        if a + ('\n' if isinstance(a, text_type) else b'\n') == b:
1114
1330
            message = 'first string is missing a final newline.\n'
1115
 
        if a == b + '\n':
 
1331
        if a == b + ('\n' if isinstance(b, text_type) else b'\n'):
1116
1332
            message = 'second string is missing a final newline.\n'
1117
1333
        raise AssertionError(message +
1118
1334
                             self._ndiff_strings(a, b))
1135
1351
                         'st_mtime did not match')
1136
1352
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1137
1353
                         'st_ctime did not match')
1138
 
        if sys.platform != 'win32':
 
1354
        if sys.platform == 'win32':
1139
1355
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1140
1356
            # 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
 
1357
            # odd. We just force it to always be 0 to avoid any problems.
 
1358
            self.assertEqual(0, expected.st_dev)
 
1359
            self.assertEqual(0, actual.st_dev)
 
1360
            self.assertEqual(0, expected.st_ino)
 
1361
            self.assertEqual(0, actual.st_ino)
 
1362
        else:
1143
1363
            self.assertEqual(expected.st_dev, actual.st_dev,
1144
1364
                             'st_dev did not match')
1145
1365
            self.assertEqual(expected.st_ino, actual.st_ino,
1154
1374
                length, len(obj_with_len), obj_with_len))
1155
1375
 
1156
1376
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1157
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1377
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1158
1378
        """
1159
 
        from bzrlib import trace
1160
1379
        captured = []
1161
1380
        orig_log_exception_quietly = trace.log_exception_quietly
1162
1381
        try:
1163
1382
            def capture():
1164
1383
                orig_log_exception_quietly()
1165
 
                captured.append(sys.exc_info())
 
1384
                captured.append(sys.exc_info()[1])
1166
1385
            trace.log_exception_quietly = capture
1167
1386
            func(*args, **kwargs)
1168
1387
        finally:
1169
1388
            trace.log_exception_quietly = orig_log_exception_quietly
1170
1389
        self.assertLength(1, captured)
1171
 
        err = captured[0][1]
 
1390
        err = captured[0]
1172
1391
        self.assertIsInstance(err, exception_class)
1173
1392
        return err
1174
1393
 
1192
1411
    def assertContainsRe(self, haystack, needle_re, flags=0):
1193
1412
        """Assert that a contains something matching a regular expression."""
1194
1413
        if not re.search(needle_re, haystack, flags):
1195
 
            if '\n' in haystack or len(haystack) > 60:
 
1414
            if ('\n' if isinstance(haystack, str) else b'\n') in haystack or len(haystack) > 60:
1196
1415
                # a long string, format it in a more readable way
1197
1416
                raise AssertionError(
1198
1417
                        'pattern "%s" not found in\n"""\\\n%s"""\n'
1211
1430
        if haystack.find(needle) == -1:
1212
1431
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1213
1432
 
 
1433
    def assertNotContainsString(self, haystack, needle):
 
1434
        if haystack.find(needle) != -1:
 
1435
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1436
 
1214
1437
    def assertSubset(self, sublist, superlist):
1215
1438
        """Assert that every entry in sublist is present in superlist."""
1216
1439
        missing = set(sublist) - set(superlist)
1227
1450
        """
1228
1451
        try:
1229
1452
            list(func(*args, **kwargs))
1230
 
        except excClass, e:
 
1453
        except excClass as e:
1231
1454
            return e
1232
1455
        else:
1233
 
            if getattr(excClass,'__name__', None) is not None:
 
1456
            if getattr(excClass, '__name__', None) is not None:
1234
1457
                excName = excClass.__name__
1235
1458
            else:
1236
1459
                excName = str(excClass)
1237
 
            raise self.failureException, "%s not raised" % excName
 
1460
            raise self.failureException("%s not raised" % excName)
1238
1461
 
1239
1462
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
1240
1463
        """Assert that a callable raises a particular exception.
1248
1471
        """
1249
1472
        try:
1250
1473
            callableObj(*args, **kwargs)
1251
 
        except excClass, e:
 
1474
        except excClass as e:
1252
1475
            return e
1253
1476
        else:
1254
 
            if getattr(excClass,'__name__', None) is not None:
 
1477
            if getattr(excClass, '__name__', None) is not None:
1255
1478
                excName = excClass.__name__
1256
1479
            else:
1257
1480
                # probably a tuple
1258
1481
                excName = str(excClass)
1259
 
            raise self.failureException, "%s not raised" % excName
 
1482
            raise self.failureException("%s not raised" % excName)
1260
1483
 
1261
1484
    def assertIs(self, left, right, message=None):
1262
1485
        if not (left is right):
1305
1528
 
1306
1529
    def assertFileEqual(self, content, path):
1307
1530
        """Fail if path does not contain 'content'."""
1308
 
        self.failUnlessExists(path)
1309
 
        f = file(path, 'rb')
1310
 
        try:
 
1531
        self.assertPathExists(path)
 
1532
        
 
1533
        with open(path, 'r' + ('b' if isinstance(content, bytes) else '')) as f:
1311
1534
            s = f.read()
1312
 
        finally:
1313
 
            f.close()
1314
1535
        self.assertEqualDiff(content, s)
1315
1536
 
1316
1537
    def assertDocstring(self, expected_docstring, obj):
1321
1542
        else:
1322
1543
            self.assertEqual(expected_docstring, obj.__doc__)
1323
1544
 
1324
 
    def failUnlessExists(self, path):
 
1545
    def assertPathExists(self, path):
1325
1546
        """Fail unless path or paths, which may be abs or relative, exist."""
1326
 
        if not isinstance(path, basestring):
 
1547
        # TODO(jelmer): Clean this up for pad.lv/1696545
 
1548
        if not isinstance(path, (bytes, str, text_type)):
1327
1549
            for p in path:
1328
 
                self.failUnlessExists(p)
 
1550
                self.assertPathExists(p)
1329
1551
        else:
1330
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1552
            self.assertTrue(osutils.lexists(path),
 
1553
                path + " does not exist")
1331
1554
 
1332
 
    def failIfExists(self, path):
 
1555
    def assertPathDoesNotExist(self, path):
1333
1556
        """Fail if path or paths, which may be abs or relative, exist."""
1334
 
        if not isinstance(path, basestring):
 
1557
        if not isinstance(path, (str, text_type)):
1335
1558
            for p in path:
1336
 
                self.failIfExists(p)
 
1559
                self.assertPathDoesNotExist(p)
1337
1560
        else:
1338
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1561
            self.assertFalse(osutils.lexists(path),
 
1562
                path + " exists")
1339
1563
 
1340
1564
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1341
1565
        """A helper for callDeprecated and applyDeprecated.
1367
1591
        not other callers that go direct to the warning module.
1368
1592
 
1369
1593
        To test that a deprecated method raises an error, do something like
1370
 
        this::
 
1594
        this (remember that both assertRaises and applyDeprecated delays *args
 
1595
        and **kwargs passing)::
1371
1596
 
1372
1597
            self.assertRaises(errors.ReservedId,
1373
1598
                self.applyDeprecated,
1451
1676
        return result
1452
1677
 
1453
1678
    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
 
1679
        """Setup a in-memory target for bzr and testcase log messages"""
 
1680
        pseudo_log_file = BytesIO()
 
1681
        def _get_log_contents_for_weird_testtools_api():
 
1682
            return [pseudo_log_file.getvalue().decode(
 
1683
                "utf-8", "replace").encode("utf-8")]
 
1684
        self.addDetail("log", content.Content(content.ContentType("text",
 
1685
            "plain", {"charset": "utf8"}),
 
1686
            _get_log_contents_for_weird_testtools_api))
 
1687
        self._log_file = pseudo_log_file
 
1688
        self._log_memento = trace.push_log_file(self._log_file)
1462
1689
        self.addCleanup(self._finishLogFile)
1463
1690
 
1464
1691
    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:
 
1692
        """Flush and dereference the in-memory log for this testcase"""
 
1693
        if trace._trace_file:
1470
1694
            # 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)
 
1695
            trace._trace_file.flush()
 
1696
        trace.pop_log_file(self._log_memento)
 
1697
        # The logging module now tracks references for cleanup so discard ours
 
1698
        del self._log_memento
1475
1699
 
1476
1700
    def thisFailsStrictLockCheck(self):
1477
1701
        """It is known that this test would fail with -Dstrict_locks.
1486
1710
        """
1487
1711
        debug.debug_flags.discard('strict_locks')
1488
1712
 
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
1713
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1498
1714
        """Overrides an object attribute restoring it after the test.
1499
1715
 
 
1716
        :note: This should be used with discretion; you should think about
 
1717
        whether it's better to make the code testable without monkey-patching.
 
1718
 
1500
1719
        :param obj: The object that will be mutated.
1501
1720
 
1502
1721
        :param attr_name: The attribute name we want to preserve/override in
1506
1725
 
1507
1726
        :returns: The actual attr value.
1508
1727
        """
1509
 
        value = getattr(obj, attr_name)
1510
1728
        # The actual value is captured by the call below
1511
 
        self.addCleanup(setattr, obj, attr_name, value)
 
1729
        value = getattr(obj, attr_name, _unitialized_attr)
 
1730
        if value is _unitialized_attr:
 
1731
            # When the test completes, the attribute should not exist, but if
 
1732
            # we aren't setting a value, we don't need to do anything.
 
1733
            if new is not _unitialized_attr:
 
1734
                self.addCleanup(delattr, obj, attr_name)
 
1735
        else:
 
1736
            self.addCleanup(setattr, obj, attr_name, value)
1512
1737
        if new is not _unitialized_attr:
1513
1738
            setattr(obj, attr_name, new)
1514
1739
        return value
1515
1740
 
 
1741
    def overrideEnv(self, name, new):
 
1742
        """Set an environment variable, and reset it after the test.
 
1743
 
 
1744
        :param name: The environment variable name.
 
1745
 
 
1746
        :param new: The value to set the variable to. If None, the 
 
1747
            variable is deleted from the environment.
 
1748
 
 
1749
        :returns: The actual variable value.
 
1750
        """
 
1751
        value = osutils.set_or_unset_env(name, new)
 
1752
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1753
        return value
 
1754
 
 
1755
    def recordCalls(self, obj, attr_name):
 
1756
        """Monkeypatch in a wrapper that will record calls.
 
1757
 
 
1758
        The monkeypatch is automatically removed when the test concludes.
 
1759
 
 
1760
        :param obj: The namespace holding the reference to be replaced;
 
1761
            typically a module, class, or object.
 
1762
        :param attr_name: A string for the name of the attribute to 
 
1763
            patch.
 
1764
        :returns: A list that will be extended with one item every time the
 
1765
            function is called, with a tuple of (args, kwargs).
 
1766
        """
 
1767
        calls = []
 
1768
 
 
1769
        def decorator(*args, **kwargs):
 
1770
            calls.append((args, kwargs))
 
1771
            return orig(*args, **kwargs)
 
1772
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1773
        return calls
 
1774
 
1516
1775
    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)
 
1776
        for name, value in isolated_environ.items():
 
1777
            self.overrideEnv(name, value)
1577
1778
 
1578
1779
    def _restoreHooks(self):
1579
1780
        for klass, (name, hooks) in self._preserved_hooks.items():
1580
1781
            setattr(klass, name, hooks)
 
1782
        self._preserved_hooks.clear()
 
1783
        breezy.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1784
        self._preserved_lazy_hooks.clear()
1581
1785
 
1582
1786
    def knownFailure(self, reason):
1583
 
        """This test has failed for some known reason."""
1584
 
        raise KnownFailure(reason)
 
1787
        """Declare that this test fails for a known reason
 
1788
 
 
1789
        Tests that are known to fail should generally be using expectedFailure
 
1790
        with an appropriate reverse assertion if a change could cause the test
 
1791
        to start passing. Conversely if the test has no immediate prospect of
 
1792
        succeeding then using skip is more suitable.
 
1793
 
 
1794
        When this method is called while an exception is being handled, that
 
1795
        traceback will be used, otherwise a new exception will be thrown to
 
1796
        provide one but won't be reported.
 
1797
        """
 
1798
        self._add_reason(reason)
 
1799
        try:
 
1800
            exc_info = sys.exc_info()
 
1801
            if exc_info != (None, None, None):
 
1802
                self._report_traceback(exc_info)
 
1803
            else:
 
1804
                try:
 
1805
                    raise self.failureException(reason)
 
1806
                except self.failureException:
 
1807
                    exc_info = sys.exc_info()
 
1808
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1809
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1810
        finally:
 
1811
            del exc_info
 
1812
 
 
1813
    def _suppress_log(self):
 
1814
        """Remove the log info from details."""
 
1815
        self.discardDetail('log')
1585
1816
 
1586
1817
    def _do_skip(self, result, reason):
 
1818
        self._suppress_log()
1587
1819
        addSkip = getattr(result, 'addSkip', None)
1588
1820
        if not callable(addSkip):
1589
1821
            result.addSuccess(result)
1590
1822
        else:
1591
 
            addSkip(self, reason)
 
1823
            addSkip(self, str(reason))
1592
1824
 
1593
1825
    @staticmethod
1594
1826
    def _do_known_failure(self, result, e):
 
1827
        self._suppress_log()
1595
1828
        err = sys.exc_info()
1596
1829
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1597
1830
        if addExpectedFailure is not None:
1605
1838
            reason = 'No reason given'
1606
1839
        else:
1607
1840
            reason = e.args[0]
 
1841
        self._suppress_log ()
1608
1842
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1609
1843
        if addNotApplicable is not None:
1610
1844
            result.addNotApplicable(self, reason)
1612
1846
            self._do_skip(result, reason)
1613
1847
 
1614
1848
    @staticmethod
 
1849
    def _report_skip(self, result, err):
 
1850
        """Override the default _report_skip.
 
1851
 
 
1852
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1853
        already been formatted into the 'reason' string, and we can't pull it
 
1854
        out again.
 
1855
        """
 
1856
        self._suppress_log()
 
1857
        super(TestCase, self)._report_skip(self, result, err)
 
1858
 
 
1859
    @staticmethod
 
1860
    def _report_expected_failure(self, result, err):
 
1861
        """Strip the log.
 
1862
 
 
1863
        See _report_skip for motivation.
 
1864
        """
 
1865
        self._suppress_log()
 
1866
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1867
 
 
1868
    @staticmethod
1615
1869
    def _do_unsupported_or_skip(self, result, e):
1616
1870
        reason = e.args[0]
 
1871
        self._suppress_log()
1617
1872
        addNotSupported = getattr(result, 'addNotSupported', None)
1618
1873
        if addNotSupported is not None:
1619
1874
            result.addNotSupported(self, reason)
1623
1878
    def time(self, callable, *args, **kwargs):
1624
1879
        """Run callable and accrue the time it takes to the benchmark time.
1625
1880
 
1626
 
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
 
1881
        If lsprofiling is enabled (i.e. by --lsprof-time to brz selftest) then
1627
1882
        this will cause lsprofile statistics to be gathered and stored in
1628
1883
        self._benchcalls.
1629
1884
        """
1630
1885
        if self._benchtime is None:
1631
 
            self.addDetail('benchtime', content.Content(content.ContentType(
1632
 
                "text", "plain"), lambda:[str(self._benchtime)]))
 
1886
            self.addDetail('benchtime', content.Content(content.UTF8_TEXT,
 
1887
                lambda:[str(self._benchtime).encode('utf-8')]))
1633
1888
            self._benchtime = 0
1634
1889
        start = time.time()
1635
1890
        try:
1637
1892
                return callable(*args, **kwargs)
1638
1893
            else:
1639
1894
                # record this benchmark
1640
 
                ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
 
1895
                ret, stats = breezy.lsprof.profile(callable, *args, **kwargs)
1641
1896
                stats.sort()
1642
1897
                self._benchcalls.append(((callable, args, kwargs), stats))
1643
1898
                return ret
1645
1900
            self._benchtime += time.time() - start
1646
1901
 
1647
1902
    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."
 
1903
        trace.mutter(*args)
1728
1904
 
1729
1905
    def get_log(self):
1730
 
        """Get a unicode string containing the log from bzrlib.trace.
 
1906
        """Get a unicode string containing the log from breezy.trace.
1731
1907
 
1732
1908
        Undecodable characters are replaced.
1733
1909
        """
1741
1917
        if not feature.available():
1742
1918
            raise UnavailableFeature(feature)
1743
1919
 
1744
 
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1745
 
            working_dir):
1746
 
        """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)))
1751
 
        return self._run_bzr_core(args, retcode=retcode,
1752
 
                encoding=encoding, stdin=stdin, working_dir=working_dir,
1753
 
                )
1754
 
 
1755
 
    def _run_bzr_core(self, args, retcode, encoding, stdin,
 
1920
    def _run_bzr_core(self, args, encoding, stdin, stdout, stderr,
1756
1921
            working_dir):
1757
1922
        # Clear chk_map page cache, because the contents are likely to mask
1758
1923
        # locking errors.
1759
1924
        chk_map.clear_cache()
1760
 
        if encoding is None:
1761
 
            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)
1768
 
        # FIXME: don't call into logging here
1769
 
        handler = logging.StreamHandler(stderr)
1770
 
        handler.setLevel(logging.INFO)
1771
 
        logger = logging.getLogger('')
1772
 
        logger.addHandler(handler)
 
1925
 
 
1926
        self.log('run brz: %r', args)
 
1927
 
 
1928
        if PY3:
 
1929
            self._last_cmd_stdout = stdout
 
1930
            self._last_cmd_stderr = stderr
 
1931
        else:
 
1932
            self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
 
1933
            self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
 
1934
 
1773
1935
        old_ui_factory = ui.ui_factory
1774
 
        ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
 
1936
        ui.ui_factory = ui_testing.TestUIFactory(
 
1937
            stdin=stdin,
 
1938
            stdout=self._last_cmd_stdout,
 
1939
            stderr=self._last_cmd_stderr)
1775
1940
 
1776
1941
        cwd = None
1777
1942
        if working_dir is not None:
1779
1944
            os.chdir(working_dir)
1780
1945
 
1781
1946
        try:
1782
 
            try:
1783
 
                result = self.apply_redirected(ui.ui_factory.stdin,
 
1947
            with ui.ui_factory:
 
1948
                result = self.apply_redirected(
 
1949
                    ui.ui_factory.stdin,
1784
1950
                    stdout, stderr,
1785
 
                    bzrlib.commands.run_bzr_catch_user_errors,
 
1951
                    _mod_commands.run_bzr_catch_user_errors,
1786
1952
                    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)
1798
1953
        finally:
1799
 
            logger.removeHandler(handler)
1800
1954
            ui.ui_factory = old_ui_factory
1801
1955
            if cwd is not None:
1802
1956
                os.chdir(cwd)
1803
1957
 
1804
 
        out = stdout.getvalue()
1805
 
        err = stderr.getvalue()
1806
 
        if out:
1807
 
            self.log('output:\n%r', out)
1808
 
        if err:
1809
 
            self.log('errors:\n%r', err)
1810
 
        if retcode is not None:
1811
 
            self.assertEquals(retcode, result,
1812
 
                              message='Unexpected return code')
1813
 
        return result, out, err
1814
 
 
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.
1818
 
 
1819
 
        The argument list should not include the bzr program name - the
1820
 
        first argument is normally the bzr command.  Arguments may be
1821
 
        passed in three ways:
1822
 
 
1823
 
        1- A list of strings, eg ["commit", "a"].  This is recommended
1824
 
        when the command contains whitespace or metacharacters, or
1825
 
        is built up at run time.
1826
 
 
1827
 
        2- A single string, eg "add a".  This is the most convenient
1828
 
        for hardcoded commands.
1829
 
 
1830
 
        This runs bzr through the interface that catches and reports
1831
 
        errors, and with logging set to something approximating the
1832
 
        default, so that error reporting can be checked.
1833
 
 
1834
 
        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
1836
 
        or a functional test of the library.)
1837
 
 
1838
 
        This sends the stdout/stderr results into the test's log,
1839
 
        where it may be useful for debugging.  See also run_captured.
1840
 
 
1841
 
        :keyword stdin: A string to be used as stdin for the command.
1842
 
        :keyword retcode: The status code the command should return;
1843
 
            default 0.
1844
 
        :keyword working_dir: The directory to run the command in
1845
 
        :keyword error_regexes: A list of expected error messages.  If
1846
 
            specified they must be seen in the error output of the command.
1847
 
        """
1848
 
        retcode, out, err = self._run_bzr_autosplit(
1849
 
            args=args,
1850
 
            retcode=retcode,
1851
 
            encoding=encoding,
1852
 
            stdin=stdin,
1853
 
            working_dir=working_dir,
1854
 
            )
 
1958
        return result
 
1959
 
 
1960
    def run_bzr_raw(self, args, retcode=0, stdin=None, encoding=None,
 
1961
                working_dir=None, error_regexes=[]):
 
1962
        """Invoke brz, as if it were run from the command line.
 
1963
 
 
1964
        The argument list should not include the brz program name - the
 
1965
        first argument is normally the brz command.  Arguments may be
 
1966
        passed in three ways:
 
1967
 
 
1968
        1- A list of strings, eg ["commit", "a"].  This is recommended
 
1969
        when the command contains whitespace or metacharacters, or
 
1970
        is built up at run time.
 
1971
 
 
1972
        2- A single string, eg "add a".  This is the most convenient
 
1973
        for hardcoded commands.
 
1974
 
 
1975
        This runs brz through the interface that catches and reports
 
1976
        errors, and with logging set to something approximating the
 
1977
        default, so that error reporting can be checked.
 
1978
 
 
1979
        This should be the main method for tests that want to exercise the
 
1980
        overall behavior of the brz application (rather than a unit test
 
1981
        or a functional test of the library.)
 
1982
 
 
1983
        This sends the stdout/stderr results into the test's log,
 
1984
        where it may be useful for debugging.  See also run_captured.
 
1985
 
 
1986
        :keyword stdin: A string to be used as stdin for the command.
 
1987
        :keyword retcode: The status code the command should return;
 
1988
            default 0.
 
1989
        :keyword working_dir: The directory to run the command in
 
1990
        :keyword error_regexes: A list of expected error messages.  If
 
1991
            specified they must be seen in the error output of the command.
 
1992
        """
 
1993
        if isinstance(args, string_types):
 
1994
            args = shlex.split(args)
 
1995
 
 
1996
        if encoding is None:
 
1997
            encoding = osutils.get_user_encoding()
 
1998
 
 
1999
        if sys.version_info[0] == 2:
 
2000
            wrapped_stdout = stdout = ui_testing.BytesIOWithEncoding()
 
2001
            wrapped_stderr = stderr = ui_testing.BytesIOWithEncoding()
 
2002
            stdout.encoding = stderr.encoding = encoding
 
2003
 
 
2004
            # FIXME: don't call into logging here
 
2005
            handler = trace.EncodedStreamHandler(
 
2006
                stderr, errors="replace")
 
2007
        else:
 
2008
            stdout = BytesIO()
 
2009
            stderr = BytesIO()
 
2010
            wrapped_stdout = TextIOWrapper(stdout, encoding)
 
2011
            wrapped_stderr = TextIOWrapper(stderr, encoding)
 
2012
            handler = logging.StreamHandler(wrapped_stderr)
 
2013
        handler.setLevel(logging.INFO)
 
2014
 
 
2015
        logger = logging.getLogger('')
 
2016
        logger.addHandler(handler)
 
2017
        try:
 
2018
            result = self._run_bzr_core(
 
2019
                    args, encoding=encoding, stdin=stdin, stdout=wrapped_stdout,
 
2020
                    stderr=wrapped_stderr, working_dir=working_dir,
 
2021
                    )
 
2022
        finally:
 
2023
            logger.removeHandler(handler)
 
2024
 
 
2025
        if PY3:
 
2026
            wrapped_stdout.flush()
 
2027
            wrapped_stderr.flush()
 
2028
 
 
2029
        out = stdout.getvalue()
 
2030
        err = stderr.getvalue()
 
2031
        if out:
 
2032
            self.log('output:\n%r', out)
 
2033
        if err:
 
2034
            self.log('errors:\n%r', err)
 
2035
        if retcode is not None:
 
2036
            self.assertEqual(retcode, result,
 
2037
                              message='Unexpected return code')
 
2038
        self.assertIsInstance(error_regexes, (list, tuple))
 
2039
        for regex in error_regexes:
 
2040
            self.assertContainsRe(err, regex)
 
2041
        return out, err
 
2042
 
 
2043
    def run_bzr(self, args, retcode=0, stdin=None, encoding=None,
 
2044
                working_dir=None, error_regexes=[]):
 
2045
        """Invoke brz, as if it were run from the command line.
 
2046
 
 
2047
        The argument list should not include the brz program name - the
 
2048
        first argument is normally the brz command.  Arguments may be
 
2049
        passed in three ways:
 
2050
 
 
2051
        1- A list of strings, eg ["commit", "a"].  This is recommended
 
2052
        when the command contains whitespace or metacharacters, or
 
2053
        is built up at run time.
 
2054
 
 
2055
        2- A single string, eg "add a".  This is the most convenient
 
2056
        for hardcoded commands.
 
2057
 
 
2058
        This runs brz through the interface that catches and reports
 
2059
        errors, and with logging set to something approximating the
 
2060
        default, so that error reporting can be checked.
 
2061
 
 
2062
        This should be the main method for tests that want to exercise the
 
2063
        overall behavior of the brz application (rather than a unit test
 
2064
        or a functional test of the library.)
 
2065
 
 
2066
        This sends the stdout/stderr results into the test's log,
 
2067
        where it may be useful for debugging.  See also run_captured.
 
2068
 
 
2069
        :keyword stdin: A string to be used as stdin for the command.
 
2070
        :keyword retcode: The status code the command should return;
 
2071
            default 0.
 
2072
        :keyword working_dir: The directory to run the command in
 
2073
        :keyword error_regexes: A list of expected error messages.  If
 
2074
            specified they must be seen in the error output of the command.
 
2075
        """
 
2076
        if isinstance(args, string_types):
 
2077
            args = shlex.split(args)
 
2078
 
 
2079
        if encoding is None:
 
2080
            encoding = osutils.get_user_encoding()
 
2081
 
 
2082
        if sys.version_info[0] == 2:
 
2083
            stdout = ui_testing.BytesIOWithEncoding()
 
2084
            stderr = ui_testing.BytesIOWithEncoding()
 
2085
            stdout.encoding = stderr.encoding = encoding
 
2086
            # FIXME: don't call into logging here
 
2087
            handler = trace.EncodedStreamHandler(
 
2088
                stderr, errors="replace")
 
2089
        else:
 
2090
            stdout = ui_testing.StringIOWithEncoding()
 
2091
            stderr = ui_testing.StringIOWithEncoding()
 
2092
            stdout.encoding = stderr.encoding = encoding
 
2093
            handler = logging.StreamHandler(stream=stderr)
 
2094
        handler.setLevel(logging.INFO)
 
2095
 
 
2096
        logger = logging.getLogger('')
 
2097
        logger.addHandler(handler)
 
2098
 
 
2099
        try:
 
2100
            result = self._run_bzr_core(args,
 
2101
                    encoding=encoding, stdin=stdin, stdout=stdout,
 
2102
                    stderr=stderr, working_dir=working_dir,
 
2103
                    )
 
2104
        finally:
 
2105
            logger.removeHandler(handler)
 
2106
 
 
2107
        out = stdout.getvalue()
 
2108
        err = stderr.getvalue()
 
2109
        if out:
 
2110
            self.log('output:\n%r', out)
 
2111
        if err:
 
2112
            self.log('errors:\n%r', err)
 
2113
        if retcode is not None:
 
2114
            self.assertEqual(retcode, result,
 
2115
                              message='Unexpected return code')
1855
2116
        self.assertIsInstance(error_regexes, (list, tuple))
1856
2117
        for regex in error_regexes:
1857
2118
            self.assertContainsRe(err, regex)
1858
2119
        return out, err
1859
2120
 
1860
2121
    def run_bzr_error(self, error_regexes, *args, **kwargs):
1861
 
        """Run bzr, and check that stderr contains the supplied regexes
 
2122
        """Run brz, and check that stderr contains the supplied regexes
1862
2123
 
1863
2124
        :param error_regexes: Sequence of regular expressions which
1864
2125
            must each be found in the error output. The relative ordering
1865
2126
            is not enforced.
1866
 
        :param args: command-line arguments for bzr
1867
 
        :param kwargs: Keyword arguments which are interpreted by run_bzr
 
2127
        :param args: command-line arguments for brz
 
2128
        :param kwargs: Keyword arguments which are interpreted by run_brz
1868
2129
            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.
 
2130
            since in most cases this is run when you expect brz to fail.
1870
2131
 
1871
2132
        :return: (out, err) The actual output of running the command (in case
1872
2133
            you want to do more inspection)
1888
2149
        return out, err
1889
2150
 
1890
2151
    def run_bzr_subprocess(self, *args, **kwargs):
1891
 
        """Run bzr in a subprocess for testing.
 
2152
        """Run brz in a subprocess for testing.
1892
2153
 
1893
 
        This starts a new Python interpreter and runs bzr in there.
 
2154
        This starts a new Python interpreter and runs brz in there.
1894
2155
        This should only be used for tests that have a justifiable need for
1895
2156
        this isolation: e.g. they are testing startup time, or signal
1896
2157
        handling, or early startup code, etc.  Subprocess code can't be
1914
2175
        if len(args) == 1:
1915
2176
            if isinstance(args[0], list):
1916
2177
                args = args[0]
1917
 
            elif isinstance(args[0], basestring):
 
2178
            elif isinstance(args[0], (str, text_type)):
1918
2179
                args = list(shlex.split(args[0]))
1919
2180
        else:
1920
2181
            raise ValueError("passing varargs to run_bzr_subprocess")
1930
2191
    def start_bzr_subprocess(self, process_args, env_changes=None,
1931
2192
                             skip_if_plan_to_signal=False,
1932
2193
                             working_dir=None,
1933
 
                             allow_plugins=False):
1934
 
        """Start bzr in a subprocess for testing.
 
2194
                             allow_plugins=False, stderr=subprocess.PIPE):
 
2195
        """Start brz in a subprocess for testing.
1935
2196
 
1936
 
        This starts a new Python interpreter and runs bzr in there.
 
2197
        This starts a new Python interpreter and runs brz in there.
1937
2198
        This should only be used for tests that have a justifiable need for
1938
2199
        this isolation: e.g. they are testing startup time, or signal
1939
2200
        handling, or early startup code, etc.  Subprocess code can't be
1940
2201
        profiled or debugged so easily.
1941
2202
 
1942
 
        :param process_args: a list of arguments to pass to the bzr executable,
 
2203
        :param process_args: a list of arguments to pass to the brz executable,
1943
2204
            for example ``['--version']``.
1944
2205
        :param env_changes: A dictionary which lists changes to environment
1945
2206
            variables. A value of None will unset the env variable.
1946
2207
            The values must be strings. The change will only occur in the
1947
2208
            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.
 
2209
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2210
            doesn't support signalling subprocesses.
 
2211
        :param allow_plugins: If False (default) pass --no-plugins to brz.
 
2212
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2213
            are those valid for the stderr argument of `subprocess.Popen`.
 
2214
            Default value is ``subprocess.PIPE``.
1951
2215
 
1952
2216
        :returns: Popen object for the started process.
1953
2217
        """
1954
2218
        if skip_if_plan_to_signal:
1955
 
            if not getattr(os, 'kill', None):
1956
 
                raise TestSkipped("os.kill not available.")
 
2219
            if os.name != "posix":
 
2220
                raise TestSkipped("Sending signals not supported")
1957
2221
 
1958
2222
        if env_changes is None:
1959
2223
            env_changes = {}
 
2224
        # Because $HOME is set to a tempdir for the context of a test, modules
 
2225
        # installed in the user dir will not be found unless $PYTHONUSERBASE
 
2226
        # gets set to the computed directory of this parent process.
 
2227
        if site.USER_BASE is not None:
 
2228
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
1960
2229
        old_env = {}
1961
2230
 
1962
2231
        def cleanup_environment():
1963
 
            for env_var, value in env_changes.iteritems():
 
2232
            for env_var, value in env_changes.items():
1964
2233
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
1965
2234
 
1966
2235
        def restore_environment():
1967
 
            for env_var, value in old_env.iteritems():
 
2236
            for env_var, value in old_env.items():
1968
2237
                osutils.set_or_unset_env(env_var, value)
1969
2238
 
1970
 
        bzr_path = self.get_bzr_path()
 
2239
        bzr_path = self.get_brz_path()
1971
2240
 
1972
2241
        cwd = None
1973
2242
        if working_dir is not None:
1979
2248
            # so we will avoid using it on all platforms, just to
1980
2249
            # make sure the code path is used, and we don't break on win32
1981
2250
            cleanup_environment()
 
2251
            # Include the subprocess's log file in the test details, in case
 
2252
            # the test fails due to an error in the subprocess.
 
2253
            self._add_subprocess_log(trace._get_brz_log_filename())
1982
2254
            command = [sys.executable]
1983
2255
            # frozen executables don't need the path to bzr
1984
2256
            if getattr(sys, "frozen", None) is None:
1986
2258
            if not allow_plugins:
1987
2259
                command.append('--no-plugins')
1988
2260
            command.extend(process_args)
1989
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
2261
            process = self._popen(command, stdin=subprocess.PIPE,
 
2262
                                  stdout=subprocess.PIPE,
 
2263
                                  stderr=stderr, bufsize=0)
1990
2264
        finally:
1991
2265
            restore_environment()
1992
2266
            if cwd is not None:
1994
2268
 
1995
2269
        return process
1996
2270
 
 
2271
    def _add_subprocess_log(self, log_file_path):
 
2272
        if len(self._log_files) == 0:
 
2273
            # Register an addCleanup func.  We do this on the first call to
 
2274
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2275
            # addCleanup is registered after any cleanups for tempdirs that
 
2276
            # subclasses might create, which will probably remove the log file
 
2277
            # we want to read.
 
2278
            self.addCleanup(self._subprocess_log_cleanup)
 
2279
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2280
        # twice.
 
2281
        self._log_files.add(log_file_path)
 
2282
 
 
2283
    def _subprocess_log_cleanup(self):
 
2284
        for count, log_file_path in enumerate(self._log_files):
 
2285
            # We use buffer_now=True to avoid holding the file open beyond
 
2286
            # the life of this function, which might interfere with e.g.
 
2287
            # cleaning tempdirs on Windows.
 
2288
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2289
            #detail_content = content.content_from_file(
 
2290
            #    log_file_path, buffer_now=True)
 
2291
            with open(log_file_path, 'rb') as log_file:
 
2292
                log_file_bytes = log_file.read()
 
2293
            detail_content = content.Content(content.ContentType("text",
 
2294
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2295
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2296
                detail_content)
 
2297
 
1997
2298
    def _popen(self, *args, **kwargs):
1998
2299
        """Place a call to Popen.
1999
2300
 
2000
2301
        Allows tests to override this method to intercept the calls made to
2001
2302
        Popen for introspection.
2002
2303
        """
2003
 
        return Popen(*args, **kwargs)
 
2304
        return subprocess.Popen(*args, **kwargs)
2004
2305
 
2005
2306
    def get_source_path(self):
2006
 
        """Return the path of the directory containing bzrlib."""
2007
 
        return os.path.dirname(os.path.dirname(bzrlib.__file__))
 
2307
        """Return the path of the directory containing breezy."""
 
2308
        return os.path.dirname(os.path.dirname(breezy.__file__))
2008
2309
 
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):
 
2310
    def get_brz_path(self):
 
2311
        """Return the path of the 'brz' executable for this test suite."""
 
2312
        brz_path = os.path.join(self.get_source_path(), "brz")
 
2313
        if not os.path.isfile(brz_path):
2013
2314
            # We are probably installed. Assume sys.argv is the right file
2014
 
            bzr_path = sys.argv[0]
2015
 
        return bzr_path
 
2315
            brz_path = sys.argv[0]
 
2316
        return brz_path
2016
2317
 
2017
2318
    def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
2018
2319
                              universal_newlines=False, process_args=None):
2030
2331
        out, err = process.communicate()
2031
2332
 
2032
2333
        if universal_newlines:
2033
 
            out = out.replace('\r\n', '\n')
2034
 
            err = err.replace('\r\n', '\n')
 
2334
            out = out.replace(b'\r\n', b'\n')
 
2335
            err = err.replace(b'\r\n', b'\n')
2035
2336
 
2036
2337
        if retcode is not None and retcode != process.returncode:
2037
2338
            if process_args is None:
2038
2339
                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'
 
2340
            trace.mutter('Output of brz %r:\n%s', process_args, out)
 
2341
            trace.mutter('Error for brz %r:\n%s', process_args, err)
 
2342
            self.fail('Command brz %r failed with retcode %d != %d'
2042
2343
                      % (process_args, retcode, process.returncode))
2043
2344
        return [out, err]
2044
2345
 
2045
 
    def check_inventory_shape(self, inv, shape):
2046
 
        """Compare an inventory to a list of expected names.
 
2346
    def check_tree_shape(self, tree, shape):
 
2347
        """Compare a tree to a list of expected names.
2047
2348
 
2048
2349
        Fail if they are not precisely equal.
2049
2350
        """
2050
2351
        extras = []
2051
2352
        shape = list(shape)             # copy
2052
 
        for path, ie in inv.entries():
 
2353
        for path, ie in tree.iter_entries_by_dir():
2053
2354
            name = path.replace('\\', '/')
2054
2355
            if ie.kind == 'directory':
2055
2356
                name = name + '/'
2056
 
            if name in shape:
 
2357
            if name == "/":
 
2358
                pass # ignore root entry
 
2359
            elif name in shape:
2057
2360
                shape.remove(name)
2058
2361
            else:
2059
2362
                extras.append(name)
2070
2373
        if not callable(a_callable):
2071
2374
            raise ValueError("a_callable must be callable.")
2072
2375
        if stdin is None:
2073
 
            stdin = StringIO("")
 
2376
            stdin = BytesIO(b"")
2074
2377
        if stdout is None:
2075
2378
            if getattr(self, "_log_file", None) is not None:
2076
2379
                stdout = self._log_file
2077
2380
            else:
2078
 
                stdout = StringIO()
 
2381
                if sys.version_info[0] == 2:
 
2382
                    stdout = BytesIO()
 
2383
                else:
 
2384
                    stdout = StringIO()
2079
2385
        if stderr is None:
2080
2386
            if getattr(self, "_log_file", None is not None):
2081
2387
                stderr = self._log_file
2082
2388
            else:
2083
 
                stderr = StringIO()
 
2389
                if sys.version_info[0] == 2:
 
2390
                    stderr = BytesIO()
 
2391
                else:
 
2392
                    stderr = StringIO()
2084
2393
        real_stdin = sys.stdin
2085
2394
        real_stdout = sys.stdout
2086
2395
        real_stderr = sys.stderr
2100
2409
 
2101
2410
        Tests that expect to provoke LockContention errors should call this.
2102
2411
        """
2103
 
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2412
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2104
2413
 
2105
2414
    def make_utf8_encoded_stringio(self, encoding_type=None):
2106
 
        """Return a StringIOWrapper instance, that will encode Unicode
2107
 
        input to UTF-8.
2108
 
        """
 
2415
        """Return a wrapped BytesIO, that will encode text input to UTF-8."""
2109
2416
        if encoding_type is None:
2110
2417
            encoding_type = 'strict'
2111
 
        sio = StringIO()
 
2418
        bio = BytesIO()
2112
2419
        output_encoding = 'utf-8'
2113
 
        sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
 
2420
        sio = codecs.getwriter(output_encoding)(bio, errors=encoding_type)
2114
2421
        sio.encoding = output_encoding
2115
2422
        return sio
2116
2423
 
2117
2424
    def disable_verb(self, verb):
2118
2425
        """Disable a smart server verb for one test."""
2119
 
        from bzrlib.smart import request
 
2426
        from breezy.bzr.smart import request
2120
2427
        request_handlers = request.request_handlers
2121
2428
        orig_method = request_handlers.get(verb)
 
2429
        orig_info = request_handlers.get_info(verb)
2122
2430
        request_handlers.remove(verb)
2123
 
        self.addCleanup(request_handlers.register, verb, orig_method)
 
2431
        self.addCleanup(request_handlers.register, verb, orig_method,
 
2432
            info=orig_info)
 
2433
 
 
2434
    def __hash__(self):
 
2435
        return id(self)
2124
2436
 
2125
2437
 
2126
2438
class CapturedCall(object):
2149
2461
class TestCaseWithMemoryTransport(TestCase):
2150
2462
    """Common test class for tests that do not need disk resources.
2151
2463
 
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
 
2464
    Tests that need disk resources should derive from TestCaseInTempDir
 
2465
    orTestCaseWithTransport.
 
2466
 
 
2467
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all brz tests.
 
2468
 
 
2469
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2157
2470
    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
 
2471
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2472
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2473
    defaults for the transport in tests, nor does it obey the command line
2161
2474
    override, so tests that accidentally write to the common directory should
2162
2475
    be rare.
2163
2476
 
2164
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
2165
 
    a .bzr directory that stops us ascending higher into the filesystem.
 
2477
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2478
        ``.bzr`` directory that stops us ascending higher into the filesystem.
2166
2479
    """
2167
2480
 
2168
2481
    TEST_ROOT = None
2178
2491
        self.transport_readonly_server = None
2179
2492
        self.__vfs_server = None
2180
2493
 
 
2494
    def setUp(self):
 
2495
        super(TestCaseWithMemoryTransport, self).setUp()
 
2496
 
 
2497
        def _add_disconnect_cleanup(transport):
 
2498
            """Schedule disconnection of given transport at test cleanup
 
2499
 
 
2500
            This needs to happen for all connected transports or leaks occur.
 
2501
 
 
2502
            Note reconnections may mean we call disconnect multiple times per
 
2503
            transport which is suboptimal but seems harmless.
 
2504
            """
 
2505
            self.addCleanup(transport.disconnect)
 
2506
 
 
2507
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
 
2508
            _add_disconnect_cleanup, None)
 
2509
 
 
2510
        self._make_test_root()
 
2511
        self.addCleanup(os.chdir, osutils.getcwd())
 
2512
        self.makeAndChdirToTestDir()
 
2513
        self.overrideEnvironmentForTesting()
 
2514
        self.__readonly_server = None
 
2515
        self.__server = None
 
2516
        self.reduceLockdirTimeout()
 
2517
        # Each test may use its own config files even if the local config files
 
2518
        # don't actually exist. They'll rightly fail if they try to create them
 
2519
        # though.
 
2520
        self.overrideAttr(config, '_shared_stores', {})
 
2521
 
2181
2522
    def get_transport(self, relpath=None):
2182
2523
        """Return a writeable transport.
2183
2524
 
2186
2527
 
2187
2528
        :param relpath: a path relative to the base url.
2188
2529
        """
2189
 
        t = get_transport(self.get_url(relpath))
 
2530
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2190
2531
        self.assertFalse(t.is_readonly())
2191
2532
        return t
2192
2533
 
2198
2539
 
2199
2540
        :param relpath: a path relative to the base url.
2200
2541
        """
2201
 
        t = get_transport(self.get_readonly_url(relpath))
 
2542
        t = _mod_transport.get_transport_from_url(
 
2543
            self.get_readonly_url(relpath))
2202
2544
        self.assertTrue(t.is_readonly())
2203
2545
        return t
2204
2546
 
2325
2667
        real branch.
2326
2668
        """
2327
2669
        root = TestCaseWithMemoryTransport.TEST_ROOT
2328
 
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2670
        try:
 
2671
            # Make sure we get a readable and accessible home for .brz.log
 
2672
            # and/or config files, and not fallback to weird defaults (see
 
2673
            # http://pad.lv/825027).
 
2674
            self.assertIs(None, os.environ.get('BRZ_HOME', None))
 
2675
            os.environ['BRZ_HOME'] = root
 
2676
            wt = controldir.ControlDir.create_standalone_workingtree(root)
 
2677
            del os.environ['BRZ_HOME']
 
2678
        except Exception as e:
 
2679
            self.fail("Fail to initialize the safety net: %r\n" % (e,))
 
2680
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2681
        # we don't need to re-open the wt to check it hasn't changed.
 
2682
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2683
            wt.control_transport.get_bytes('dirstate'))
2329
2684
 
2330
2685
    def _check_safety_net(self):
2331
2686
        """Check that the safety .bzr directory have not been touched.
2334
2689
        propagating. This method ensures than a test did not leaked.
2335
2690
        """
2336
2691
        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:':
 
2692
        t = _mod_transport.get_transport_from_path(root)
 
2693
        self.permit_url(t.base)
 
2694
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2695
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2341
2696
            # The current test have modified the /bzr directory, we need to
2342
2697
            # recreate a new one or all the followng tests will fail.
2343
2698
            # If you need to inspect its content uncomment the following line
2375
2730
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2376
2731
        self.permit_dir(self.test_dir)
2377
2732
 
2378
 
    def make_branch(self, relpath, format=None):
 
2733
    def make_branch(self, relpath, format=None, name=None):
2379
2734
        """Create a branch on the transport at relpath."""
2380
2735
        repo = self.make_repository(relpath, format=format)
2381
 
        return repo.bzrdir.create_branch()
2382
 
 
2383
 
    def make_bzrdir(self, relpath, format=None):
 
2736
        return repo.controldir.create_branch(append_revisions_only=False, name=name)
 
2737
 
 
2738
    def get_default_format(self):
 
2739
        return 'default'
 
2740
 
 
2741
    def resolve_format(self, format):
 
2742
        """Resolve an object to a ControlDir format object.
 
2743
 
 
2744
        The initial format object can either already be
 
2745
        a ControlDirFormat, None (for the default format),
 
2746
        or a string with the name of the control dir format.
 
2747
 
 
2748
        :param format: Object to resolve
 
2749
        :return A ControlDirFormat instance
 
2750
        """
 
2751
        if format is None:
 
2752
            format = self.get_default_format()
 
2753
        if isinstance(format, str):
 
2754
            format = controldir.format_registry.make_controldir(format)
 
2755
        return format
 
2756
 
 
2757
    def make_controldir(self, relpath, format=None):
2384
2758
        try:
2385
2759
            # might be a relative or absolute path
2386
2760
            maybe_a_url = self.get_url(relpath)
2387
2761
            segments = maybe_a_url.rsplit('/', 1)
2388
 
            t = get_transport(maybe_a_url)
 
2762
            t = _mod_transport.get_transport(maybe_a_url)
2389
2763
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2390
2764
                t.ensure_base()
2391
 
            if format is None:
2392
 
                format = 'default'
2393
 
            if isinstance(format, basestring):
2394
 
                format = bzrdir.format_registry.make_bzrdir(format)
 
2765
            format = self.resolve_format(format)
2395
2766
            return format.initialize_on_transport(t)
2396
2767
        except errors.UninitializableFormat:
2397
2768
            raise TestSkipped("Format %s is not initializable." % format)
2398
2769
 
2399
 
    def make_repository(self, relpath, shared=False, format=None):
 
2770
    def make_repository(self, relpath, shared=None, format=None):
2400
2771
        """Create a repository on our default transport at relpath.
2401
2772
 
2402
2773
        Note that relpath must be a relative path, not a full url.
2405
2776
        # real format, which is incorrect.  Actually we should make sure that
2406
2777
        # RemoteBzrDir returns a RemoteRepository.
2407
2778
        # maybe  mbp 20070410
2408
 
        made_control = self.make_bzrdir(relpath, format=format)
 
2779
        made_control = self.make_controldir(relpath, format=format)
2409
2780
        return made_control.create_repository(shared=shared)
2410
2781
 
2411
 
    def make_smart_server(self, path):
 
2782
    def make_smart_server(self, path, backing_server=None):
 
2783
        if backing_server is None:
 
2784
            backing_server = self.get_server()
2412
2785
        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)
 
2786
        self.start_server(smart_server, backing_server)
 
2787
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
 
2788
                                                   ).clone(path)
2415
2789
        return remote_transport
2416
2790
 
2417
2791
    def make_branch_and_memory_tree(self, relpath, format=None):
2418
2792
        """Create a branch on the default transport and a MemoryTree for it."""
2419
2793
        b = self.make_branch(relpath, format=format)
2420
 
        return memorytree.MemoryTree.create_on_branch(b)
 
2794
        return b.create_memorytree()
2421
2795
 
2422
2796
    def make_branch_builder(self, relpath, format=None):
2423
2797
        branch = self.make_branch(relpath, format=format)
2425
2799
 
2426
2800
    def overrideEnvironmentForTesting(self):
2427
2801
        test_home_dir = self.test_home_dir
2428
 
        if isinstance(test_home_dir, unicode):
 
2802
        if not PY3 and isinstance(test_home_dir, text_type):
2429
2803
            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()
 
2804
        self.overrideEnv('HOME', test_home_dir)
 
2805
        self.overrideEnv('BRZ_HOME', test_home_dir)
 
2806
        self.overrideEnv('GNUPGHOME', os.path.join(test_home_dir, '.gnupg'))
2442
2807
 
2443
2808
    def setup_smart_server_with_call_log(self):
2444
2809
        """Sets up a smart server as the transport server with a call log."""
2445
2810
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2811
        self.hpss_connections = []
2446
2812
        self.hpss_calls = []
2447
2813
        import traceback
2448
2814
        # Skip the current stack down to the caller of
2451
2817
        def capture_hpss_call(params):
2452
2818
            self.hpss_calls.append(
2453
2819
                CapturedCall(params, prefix_length))
 
2820
        def capture_connect(transport):
 
2821
            self.hpss_connections.append(transport)
2454
2822
        client._SmartClient.hooks.install_named_hook(
2455
2823
            'call', capture_hpss_call, None)
 
2824
        _mod_transport.Transport.hooks.install_named_hook(
 
2825
            'post_connect', capture_connect, None)
2456
2826
 
2457
2827
    def reset_smart_call_log(self):
2458
2828
        self.hpss_calls = []
 
2829
        self.hpss_connections = []
2459
2830
 
2460
2831
 
2461
2832
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2480
2851
 
2481
2852
    OVERRIDE_PYTHON = 'python'
2482
2853
 
 
2854
    def setUp(self):
 
2855
        super(TestCaseInTempDir, self).setUp()
 
2856
        # Remove the protection set in isolated_environ, we have a proper
 
2857
        # access to disk resources now.
 
2858
        self.overrideEnv('BRZ_LOG', None)
 
2859
 
2483
2860
    def check_file_contents(self, filename, expect):
2484
2861
        self.log("check contents of file %s" % filename)
2485
 
        contents = file(filename, 'r').read()
 
2862
        with open(filename, 'rb') as f:
 
2863
            contents = f.read()
2486
2864
        if contents != expect:
2487
2865
            self.log("expected: %r" % expect)
2488
2866
            self.log("actually: %r" % contents)
2521
2899
        # stacking policy to honour; create a bzr dir with an unshared
2522
2900
        # repository (but not a branch - our code would be trying to escape
2523
2901
        # then!) to stop them, and permit it to be read.
2524
 
        # control = bzrdir.BzrDir.create(self.test_base_dir)
 
2902
        # control = controldir.ControlDir.create(self.test_base_dir)
2525
2903
        # control.create_repository()
2526
2904
        self.test_home_dir = self.test_base_dir + '/home'
2527
2905
        os.mkdir(self.test_home_dir)
2529
2907
        os.mkdir(self.test_dir)
2530
2908
        os.chdir(self.test_dir)
2531
2909
        # put name of test inside
2532
 
        f = file(self.test_base_dir + '/name', 'w')
2533
 
        try:
 
2910
        with open(self.test_base_dir + '/name', 'w') as f:
2534
2911
            f.write(self.id())
2535
 
        finally:
2536
 
            f.close()
2537
2912
 
2538
2913
    def deleteTestDir(self):
2539
2914
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2562
2937
                "a list or a tuple. Got %r instead" % (shape,))
2563
2938
        # It's OK to just create them using forward slashes on windows.
2564
2939
        if transport is None or transport.is_readonly():
2565
 
            transport = get_transport(".")
 
2940
            transport = _mod_transport.get_transport_from_path(".")
2566
2941
        for name in shape:
2567
 
            self.assertIsInstance(name, basestring)
 
2942
            self.assertIsInstance(name, (str, text_type))
2568
2943
            if name[-1] == '/':
2569
2944
                transport.mkdir(urlutils.escape(name[:-1]))
2570
2945
            else:
2571
2946
                if line_endings == 'binary':
2572
 
                    end = '\n'
 
2947
                    end = b'\n'
2573
2948
                elif line_endings == 'native':
2574
 
                    end = os.linesep
 
2949
                    end = os.linesep.encode('ascii')
2575
2950
                else:
2576
2951
                    raise errors.BzrError(
2577
2952
                        'Invalid line ending request %r' % line_endings)
2578
 
                content = "contents of %s%s" % (name.encode('utf-8'), end)
 
2953
                content = b"contents of %s%s" % (name.encode('utf-8'), end)
2579
2954
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2580
2955
 
2581
 
    def build_tree_contents(self, shape):
2582
 
        build_tree_contents(shape)
 
2956
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2583
2957
 
2584
2958
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2585
2959
        """Assert whether path or paths are in the WorkingTree"""
2586
2960
        if tree is None:
2587
2961
            tree = workingtree.WorkingTree.open(root_path)
2588
 
        if not isinstance(path, basestring):
 
2962
        if not isinstance(path, (str, text_type)):
2589
2963
            for p in path:
2590
2964
                self.assertInWorkingTree(p, tree=tree)
2591
2965
        else:
2592
 
            self.assertIsNot(tree.path2id(path), None,
 
2966
            self.assertTrue(tree.is_versioned(path),
2593
2967
                path+' not in working tree.')
2594
2968
 
2595
2969
    def assertNotInWorkingTree(self, path, root_path='.', tree=None):
2596
2970
        """Assert whether path or paths are not in the WorkingTree"""
2597
2971
        if tree is None:
2598
2972
            tree = workingtree.WorkingTree.open(root_path)
2599
 
        if not isinstance(path, basestring):
 
2973
        if not isinstance(path, (str, text_type)):
2600
2974
            for p in path:
2601
 
                self.assertNotInWorkingTree(p,tree=tree)
 
2975
                self.assertNotInWorkingTree(p, tree=tree)
2602
2976
        else:
2603
 
            self.assertIs(tree.path2id(path), None, path+' in working tree.')
 
2977
            self.assertFalse(tree.is_versioned(path), path+' in working tree.')
2604
2978
 
2605
2979
 
2606
2980
class TestCaseWithTransport(TestCaseInTempDir):
2617
2991
    readwrite one must both define get_url() as resolving to os.getcwd().
2618
2992
    """
2619
2993
 
 
2994
    def setUp(self):
 
2995
        super(TestCaseWithTransport, self).setUp()
 
2996
        self.__vfs_server = None
 
2997
 
2620
2998
    def get_vfs_only_server(self):
2621
2999
        """See TestCaseWithMemoryTransport.
2622
3000
 
2654
3032
        # this obviously requires a format that supports branch references
2655
3033
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2656
3034
        # RBC 20060208
 
3035
        format = self.resolve_format(format=format)
 
3036
        if not format.supports_workingtrees:
 
3037
            b = self.make_branch(relpath+'.branch', format=format)
 
3038
            return b.create_checkout(relpath, lightweight=True)
2657
3039
        b = self.make_branch(relpath, format=format)
2658
3040
        try:
2659
 
            return b.bzrdir.create_workingtree()
 
3041
            return b.controldir.create_workingtree()
2660
3042
        except errors.NotLocalUrl:
2661
3043
            # We can only make working trees locally at the moment.  If the
2662
3044
            # transport can't support them, then we keep the non-disk-backed
2664
3046
            if self.vfs_transport_factory is test_server.LocalURLServer:
2665
3047
                # the branch is colocated on disk, we cannot create a checkout.
2666
3048
                # hopefully callers will expect this.
2667
 
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
 
3049
                local_controldir = controldir.ControlDir.open(
 
3050
                    self.get_vfs_only_url(relpath))
2668
3051
                wt = local_controldir.create_workingtree()
2669
3052
                if wt.branch._format != b._format:
2670
3053
                    wt._branch = b
2700
3083
        self.assertFalse(differences.has_changed(),
2701
3084
            "Trees %r and %r are different: %r" % (left, right, differences))
2702
3085
 
2703
 
    def setUp(self):
2704
 
        super(TestCaseWithTransport, self).setUp()
2705
 
        self.__vfs_server = None
2706
 
 
2707
3086
    def disable_missing_extensions_warning(self):
2708
3087
        """Some tests expect a precise stderr content.
2709
3088
 
2710
3089
        There is no point in forcing them to duplicate the extension related
2711
3090
        warning.
2712
3091
        """
2713
 
        config.GlobalConfig().set_user_option('ignore_missing_extensions', True)
 
3092
        config.GlobalConfig().set_user_option(
 
3093
            'suppress_warnings', 'missing_extensions')
2714
3094
 
2715
3095
 
2716
3096
class ChrootedTestCase(TestCaseWithTransport):
2726
3106
    """
2727
3107
 
2728
3108
    def setUp(self):
 
3109
        from breezy.tests import http_server
2729
3110
        super(ChrootedTestCase, self).setUp()
2730
3111
        if not self.vfs_transport_factory == memory.MemoryServer:
2731
 
            self.transport_readonly_server = HttpServer
 
3112
            self.transport_readonly_server = http_server.HttpServer
2732
3113
 
2733
3114
 
2734
3115
def condition_id_re(pattern):
2737
3118
    :param pattern: A regular expression string.
2738
3119
    :return: A callable that returns True if the re matches.
2739
3120
    """
2740
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2741
 
        'test filter')
 
3121
    filter_re = re.compile(pattern, 0)
2742
3122
    def condition(test):
2743
3123
        test_id = test.id()
2744
3124
        return filter_re.search(test_id)
2934
3314
              stream=None,
2935
3315
              result_decorators=None,
2936
3316
              ):
2937
 
    """Run a test suite for bzr selftest.
 
3317
    """Run a test suite for brz selftest.
2938
3318
 
2939
3319
    :param runner_class: The class of runner to use. Must support the
2940
3320
        constructor arguments passed by run_suite which are more than standard
2958
3338
                            result_decorators=result_decorators,
2959
3339
                            )
2960
3340
    runner.stop_on_failure=stop_on_failure
 
3341
    if isinstance(suite, unittest.TestSuite):
 
3342
        # Empty out _tests list of passed suite and populate new TestSuite
 
3343
        suite._tests[:], suite = [], TestSuite(suite)
2961
3344
    # built in decorator factories:
2962
3345
    decorators = [
2963
3346
        random_order(random_seed, runner),
2981
3364
        # to take effect, though that is of marginal benefit.
2982
3365
        if verbosity >= 2:
2983
3366
            stream.write("Listing tests only ...\n")
2984
 
        for t in iter_suite_tests(suite):
2985
 
            stream.write("%s\n" % (t.id()))
 
3367
        if getattr(runner, 'list', None) is not None:
 
3368
            runner.list(suite)
 
3369
        else:
 
3370
            for t in iter_suite_tests(suite):
 
3371
                stream.write("%s\n" % (t.id()))
2986
3372
        return True
2987
3373
    result = runner.run(suite)
2988
 
    if strict:
 
3374
    if strict and getattr(result, 'wasStrictlySuccessful', False):
2989
3375
        return result.wasStrictlySuccessful()
2990
3376
    else:
2991
3377
        return result.wasSuccessful()
2996
3382
 
2997
3383
 
2998
3384
def fork_decorator(suite):
 
3385
    if getattr(os, "fork", None) is None:
 
3386
        raise errors.BzrCommandError("platform does not support fork,"
 
3387
            " try --parallel=subprocess instead.")
2999
3388
    concurrency = osutils.local_concurrency()
3000
3389
    if concurrency == 1:
3001
3390
        return suite
3032
3421
 
3033
3422
def random_order(random_seed, runner):
3034
3423
    """Return a test suite decorator factory for randomising tests order.
3035
 
    
3036
 
    :param random_seed: now, a string which casts to a long, or a long.
 
3424
 
 
3425
    :param random_seed: now, a string which casts to an integer, or an integer.
3037
3426
    :param runner: A test runner with a stream attribute to report on.
3038
3427
    """
3039
3428
    if random_seed is None:
3056
3445
    return suite
3057
3446
 
3058
3447
 
3059
 
class TestDecorator(TestSuite):
 
3448
class TestDecorator(TestUtil.TestSuite):
3060
3449
    """A decorator for TestCase/TestSuite objects.
3061
 
    
3062
 
    Usually, subclasses should override __iter__(used when flattening test
3063
 
    suites), which we do to filter, reorder, parallelise and so on, run() and
3064
 
    debug().
 
3450
 
 
3451
    Contains rather than flattening suite passed on construction
3065
3452
    """
3066
3453
 
3067
 
    def __init__(self, suite):
3068
 
        TestSuite.__init__(self)
3069
 
        self.addTest(suite)
3070
 
 
3071
 
    def countTestCases(self):
3072
 
        cases = 0
3073
 
        for test in self:
3074
 
            cases += test.countTestCases()
3075
 
        return cases
3076
 
 
3077
 
    def debug(self):
3078
 
        for test in self:
3079
 
            test.debug()
3080
 
 
3081
 
    def run(self, result):
3082
 
        # Use iteration on self, not self._tests, to allow subclasses to hook
3083
 
        # into __iter__.
3084
 
        for test in self:
3085
 
            if result.shouldStop:
3086
 
                break
3087
 
            test.run(result)
3088
 
        return result
 
3454
    def __init__(self, suite=None):
 
3455
        super(TestDecorator, self).__init__()
 
3456
        if suite is not None:
 
3457
            self.addTest(suite)
 
3458
 
 
3459
    # Don't need subclass run method with suite emptying
 
3460
    run = unittest.TestSuite.run
3089
3461
 
3090
3462
 
3091
3463
class CountingDecorator(TestDecorator):
3102
3474
    """A decorator which excludes test matching an exclude pattern."""
3103
3475
 
3104
3476
    def __init__(self, suite, exclude_pattern):
3105
 
        TestDecorator.__init__(self, suite)
3106
 
        self.exclude_pattern = exclude_pattern
3107
 
        self.excluded = False
3108
 
 
3109
 
    def __iter__(self):
3110
 
        if self.excluded:
3111
 
            return iter(self._tests)
3112
 
        self.excluded = True
3113
 
        suite = exclude_tests_by_re(self, self.exclude_pattern)
3114
 
        del self._tests[:]
3115
 
        self.addTests(suite)
3116
 
        return iter(self._tests)
 
3477
        super(ExcludeDecorator, self).__init__(
 
3478
            exclude_tests_by_re(suite, exclude_pattern))
3117
3479
 
3118
3480
 
3119
3481
class FilterTestsDecorator(TestDecorator):
3120
3482
    """A decorator which filters tests to those matching a pattern."""
3121
3483
 
3122
3484
    def __init__(self, suite, pattern):
3123
 
        TestDecorator.__init__(self, suite)
3124
 
        self.pattern = pattern
3125
 
        self.filtered = False
3126
 
 
3127
 
    def __iter__(self):
3128
 
        if self.filtered:
3129
 
            return iter(self._tests)
3130
 
        self.filtered = True
3131
 
        suite = filter_suite_by_re(self, self.pattern)
3132
 
        del self._tests[:]
3133
 
        self.addTests(suite)
3134
 
        return iter(self._tests)
 
3485
        super(FilterTestsDecorator, self).__init__(
 
3486
            filter_suite_by_re(suite, pattern))
3135
3487
 
3136
3488
 
3137
3489
class RandomDecorator(TestDecorator):
3138
3490
    """A decorator which randomises the order of its tests."""
3139
3491
 
3140
3492
    def __init__(self, suite, random_seed, stream):
3141
 
        TestDecorator.__init__(self, suite)
3142
 
        self.random_seed = random_seed
3143
 
        self.randomised = False
3144
 
        self.stream = stream
3145
 
 
3146
 
    def __iter__(self):
3147
 
        if self.randomised:
3148
 
            return iter(self._tests)
3149
 
        self.randomised = True
3150
 
        self.stream.write("Randomizing test order using seed %s\n\n" %
3151
 
            (self.actual_seed()))
 
3493
        random_seed = self.actual_seed(random_seed)
 
3494
        stream.write("Randomizing test order using seed %s\n\n" %
 
3495
            (random_seed,))
3152
3496
        # Initialise the random number generator.
3153
 
        random.seed(self.actual_seed())
3154
 
        suite = randomize_suite(self)
3155
 
        del self._tests[:]
3156
 
        self.addTests(suite)
3157
 
        return iter(self._tests)
 
3497
        random.seed(random_seed)
 
3498
        super(RandomDecorator, self).__init__(randomize_suite(suite))
3158
3499
 
3159
 
    def actual_seed(self):
3160
 
        if self.random_seed == "now":
3161
 
            # We convert the seed to a long to make it reuseable across
 
3500
    @staticmethod
 
3501
    def actual_seed(seed):
 
3502
        if seed == "now":
 
3503
            # We convert the seed to an integer to make it reuseable across
3162
3504
            # invocations (because the user can reenter it).
3163
 
            self.random_seed = long(time.time())
 
3505
            return int(time.time())
3164
3506
        else:
3165
 
            # Convert the seed to a long if we can
 
3507
            # Convert the seed to an integer if we can
3166
3508
            try:
3167
 
                self.random_seed = long(self.random_seed)
3168
 
            except:
 
3509
                return int(seed)
 
3510
            except (TypeError, ValueError):
3169
3511
                pass
3170
 
        return self.random_seed
 
3512
        return seed
3171
3513
 
3172
3514
 
3173
3515
class TestFirstDecorator(TestDecorator):
3174
3516
    """A decorator which moves named tests to the front."""
3175
3517
 
3176
3518
    def __init__(self, suite, pattern):
3177
 
        TestDecorator.__init__(self, suite)
3178
 
        self.pattern = pattern
3179
 
        self.filtered = False
3180
 
 
3181
 
    def __iter__(self):
3182
 
        if self.filtered:
3183
 
            return iter(self._tests)
3184
 
        self.filtered = True
3185
 
        suites = split_suite_by_re(self, self.pattern)
3186
 
        del self._tests[:]
3187
 
        self.addTests(suites)
3188
 
        return iter(self._tests)
 
3519
        super(TestFirstDecorator, self).__init__()
 
3520
        self.addTests(split_suite_by_re(suite, pattern))
3189
3521
 
3190
3522
 
3191
3523
def partition_tests(suite, count):
3192
3524
    """Partition suite into count lists of tests."""
3193
 
    result = []
3194
 
    tests = list(iter_suite_tests(suite))
3195
 
    tests_per_process = int(math.ceil(float(len(tests)) / count))
3196
 
    for block in range(count):
3197
 
        low_test = block * tests_per_process
3198
 
        high_test = low_test + tests_per_process
3199
 
        process_tests = tests[low_test:high_test]
3200
 
        result.append(process_tests)
3201
 
    return result
 
3525
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3526
    # splits up blocks of related tests that might run faster if they shared
 
3527
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3528
    # just one partition.  So the slowest partition shouldn't be much slower
 
3529
    # than the fastest.
 
3530
    partitions = [list() for i in range(count)]
 
3531
    tests = iter_suite_tests(suite)
 
3532
    for partition, test in zip(itertools.cycle(partitions), tests):
 
3533
        partition.append(test)
 
3534
    return partitions
3202
3535
 
3203
3536
 
3204
3537
def workaround_zealous_crypto_random():
3222
3555
    """
3223
3556
    concurrency = osutils.local_concurrency()
3224
3557
    result = []
3225
 
    from subunit import TestProtocolClient, ProtocolTestCase
 
3558
    from subunit import ProtocolTestCase
3226
3559
    from subunit.test_results import AutoTimingTestResultDecorator
3227
3560
    class TestInOtherProcess(ProtocolTestCase):
3228
3561
        # Should be in subunit, I think. RBC.
3234
3567
            try:
3235
3568
                ProtocolTestCase.run(self, result)
3236
3569
            finally:
3237
 
                os.waitpid(self.pid, 0)
 
3570
                pid, status = os.waitpid(self.pid, 0)
 
3571
            # GZ 2011-10-18: If status is nonzero, should report to the result
 
3572
            #                that something went wrong.
3238
3573
 
3239
3574
    test_blocks = partition_tests(suite, concurrency)
 
3575
    # Clear the tests from the original suite so it doesn't keep them alive
 
3576
    suite._tests[:] = []
3240
3577
    for process_tests in test_blocks:
3241
 
        process_suite = TestSuite()
3242
 
        process_suite.addTests(process_tests)
 
3578
        process_suite = TestUtil.TestSuite(process_tests)
 
3579
        # Also clear each split list so new suite has only reference
 
3580
        process_tests[:] = []
3243
3581
        c2pread, c2pwrite = os.pipe()
3244
3582
        pid = os.fork()
3245
3583
        if pid == 0:
3246
 
            workaround_zealous_crypto_random()
3247
3584
            try:
 
3585
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3586
                workaround_zealous_crypto_random()
 
3587
                try:
 
3588
                    import coverage
 
3589
                except ImportError:
 
3590
                    pass
 
3591
                else:
 
3592
                    coverage.process_startup()
3248
3593
                os.close(c2pread)
3249
3594
                # Leave stderr and stdout open so we can see test noise
3250
3595
                # Close stdin so that the child goes away if it decides to
3251
3596
                # read from stdin (otherwise its a roulette to see what
3252
3597
                # child actually gets keystrokes for pdb etc).
3253
3598
                sys.stdin.close()
3254
 
                sys.stdin = None
3255
 
                stream = os.fdopen(c2pwrite, 'wb', 1)
3256
3599
                subunit_result = AutoTimingTestResultDecorator(
3257
 
                    TestProtocolClient(stream))
 
3600
                    SubUnitBzrProtocolClientv1(stream))
3258
3601
                process_suite.run(subunit_result)
3259
 
            finally:
3260
 
                os._exit(0)
 
3602
            except:
 
3603
                # Try and report traceback on stream, but exit with error even
 
3604
                # if stream couldn't be created or something else goes wrong.
 
3605
                # The traceback is formatted to a string and written in one go
 
3606
                # to avoid interleaving lines from multiple failing children.
 
3607
                tb = traceback.format_exc()
 
3608
                if isinstance(tb, text_type):
 
3609
                    tb = tb.encode('utf-8')
 
3610
                try:
 
3611
                    stream.write(tb)
 
3612
                finally:
 
3613
                    stream.flush()
 
3614
                    os._exit(1)
 
3615
            os._exit(0)
3261
3616
        else:
3262
3617
            os.close(c2pwrite)
3263
3618
            stream = os.fdopen(c2pread, 'rb', 1)
3292
3647
    test_blocks = partition_tests(suite, concurrency)
3293
3648
    for process_tests in test_blocks:
3294
3649
        # ugly; currently reimplement rather than reuses TestCase methods.
3295
 
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
3650
        bzr_path = os.path.dirname(os.path.dirname(breezy.__file__))+'/bzr'
3296
3651
        if not os.path.isfile(bzr_path):
3297
3652
            # We are probably installed. Assume sys.argv is the right file
3298
3653
            bzr_path = sys.argv[0]
3310
3665
                '--subunit']
3311
3666
            if '--no-plugins' in sys.argv:
3312
3667
                argv.append('--no-plugins')
3313
 
            # stderr=STDOUT would be ideal, but until we prevent noise on
3314
 
            # stderr it can interrupt the subunit protocol.
3315
 
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3316
 
                bufsize=1)
 
3668
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3669
            # noise on stderr it can interrupt the subunit protocol.
 
3670
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3671
                                      stdout=subprocess.PIPE,
 
3672
                                      stderr=subprocess.PIPE,
 
3673
                                      bufsize=1)
3317
3674
            test = TestInSubprocess(process, test_list_file_name)
3318
3675
            result.append(test)
3319
3676
        except:
3322
3679
    return result
3323
3680
 
3324
3681
 
3325
 
class ForwardingResult(unittest.TestResult):
3326
 
 
3327
 
    def __init__(self, target):
3328
 
        unittest.TestResult.__init__(self)
3329
 
        self.result = target
3330
 
 
3331
 
    def startTest(self, test):
3332
 
        self.result.startTest(test)
3333
 
 
3334
 
    def stopTest(self, test):
3335
 
        self.result.stopTest(test)
3336
 
 
3337
 
    def startTestRun(self):
3338
 
        self.result.startTestRun()
3339
 
 
3340
 
    def stopTestRun(self):
3341
 
        self.result.stopTestRun()
3342
 
 
3343
 
    def addSkip(self, test, reason):
3344
 
        self.result.addSkip(test, reason)
3345
 
 
3346
 
    def addSuccess(self, test):
3347
 
        self.result.addSuccess(test)
3348
 
 
3349
 
    def addError(self, test, err):
3350
 
        self.result.addError(test, err)
3351
 
 
3352
 
    def addFailure(self, test, err):
3353
 
        self.result.addFailure(test, err)
3354
 
ForwardingResult = testtools.ExtendedToOriginalDecorator
3355
 
 
3356
 
 
3357
 
class ProfileResult(ForwardingResult):
 
3682
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3358
3683
    """Generate profiling data for all activity between start and success.
3359
3684
    
3360
3685
    The profile data is appended to the test's _benchcalls attribute and can
3367
3692
    """
3368
3693
 
3369
3694
    def startTest(self, test):
3370
 
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3695
        self.profiler = breezy.lsprof.BzrProfiler()
 
3696
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3697
        # unavoidably fail.
 
3698
        breezy.lsprof.BzrProfiler.profiler_block = 0
3371
3699
        self.profiler.start()
3372
 
        ForwardingResult.startTest(self, test)
 
3700
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3373
3701
 
3374
3702
    def addSuccess(self, test):
3375
3703
        stats = self.profiler.stop()
3379
3707
            test._benchcalls = []
3380
3708
            calls = test._benchcalls
3381
3709
        calls.append(((test.id(), "", ""), stats))
3382
 
        ForwardingResult.addSuccess(self, test)
 
3710
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3383
3711
 
3384
3712
    def stopTest(self, test):
3385
 
        ForwardingResult.stopTest(self, test)
 
3713
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3386
3714
        self.profiler = None
3387
3715
 
3388
3716
 
3389
 
# Controlled by "bzr selftest -E=..." option
 
3717
# Controlled by "brz selftest -E=..." option
3390
3718
# Currently supported:
3391
3719
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
3392
3720
#                           preserves any flags supplied at the command line.
3394
3722
#                           rather than failing tests. And no longer raise
3395
3723
#                           LockContention when fctnl locks are not being used
3396
3724
#                           with proper exclusion rules.
 
3725
#   -Ethreads               Will display thread ident at creation/join time to
 
3726
#                           help track thread leaks
 
3727
#   -Euncollected_cases     Display the identity of any test cases that weren't
 
3728
#                           deallocated after being completed.
 
3729
#   -Econfig_stats          Will collect statistics using addDetail
3397
3730
selftest_debug_flags = set()
3398
3731
 
3399
3732
 
3419
3752
    # XXX: Very ugly way to do this...
3420
3753
    # Disable warning about old formats because we don't want it to disturb
3421
3754
    # any blackbox tests.
3422
 
    from bzrlib import repository
 
3755
    from breezy import repository
3423
3756
    repository._deprecation_warning_done = True
3424
3757
 
3425
3758
    global default_transport
3439
3772
        if starting_with:
3440
3773
            starting_with = [test_prefix_alias_registry.resolve_alias(start)
3441
3774
                             for start in starting_with]
 
3775
            # Always consider 'unittest' an interesting name so that failed
 
3776
            # suites wrapped as test cases appear in the output.
 
3777
            starting_with.append('unittest')
3442
3778
        if test_suite_factory is None:
3443
3779
            # Reduce loading time by loading modules based on the starting_with
3444
3780
            # patterns.
3482
3818
    test_list = []
3483
3819
    try:
3484
3820
        ftest = open(file_name, 'rt')
3485
 
    except IOError, e:
 
3821
    except IOError as e:
3486
3822
        if e.errno != errno.ENOENT:
3487
3823
            raise
3488
3824
        else:
3503
3839
 
3504
3840
    :return: (absents, duplicates) absents is a list containing the test found
3505
3841
        in id_list but not in test_suite, duplicates is a list containing the
3506
 
        test found multiple times in test_suite.
 
3842
        tests found multiple times in test_suite.
3507
3843
 
3508
3844
    When using a prefined test id list, it may occurs that some tests do not
3509
3845
    exist anymore or that some tests use the same id. This function warns the
3567
3903
 
3568
3904
    def refers_to(self, module_name):
3569
3905
        """Is there tests for the module or one of its sub modules."""
3570
 
        return self.modules.has_key(module_name)
 
3906
        return module_name in self.modules
3571
3907
 
3572
3908
    def includes(self, test_id):
3573
 
        return self.tests.has_key(test_id)
 
3909
        return test_id in self.tests
3574
3910
 
3575
3911
 
3576
3912
class TestPrefixAliasRegistry(registry.Registry):
3593
3929
                key, obj, help=help, info=info, override_existing=False)
3594
3930
        except KeyError:
3595
3931
            actual = self.get(key)
3596
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3597
 
                 % (key, actual, obj))
 
3932
            trace.note(
 
3933
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3934
                % (key, actual, obj))
3598
3935
 
3599
3936
    def resolve_alias(self, id_start):
3600
3937
        """Replace the alias by the prefix in the given string.
3615
3952
 
3616
3953
 
3617
3954
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
3618
 
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3619
 
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
 
3955
# appear prefixed ('breezy.' is "replaced" by 'breezy.').
 
3956
test_prefix_alias_registry.register('breezy', 'breezy')
3620
3957
 
3621
3958
# Obvious highest levels prefixes, feel free to add your own via a plugin
3622
 
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3623
 
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3624
 
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3625
 
test_prefix_alias_registry.register('bb', 'bzrlib.tests.blackbox')
3626
 
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
 
3959
test_prefix_alias_registry.register('bd', 'breezy.doc')
 
3960
test_prefix_alias_registry.register('bu', 'breezy.utils')
 
3961
test_prefix_alias_registry.register('bt', 'breezy.tests')
 
3962
test_prefix_alias_registry.register('bb', 'breezy.tests.blackbox')
 
3963
test_prefix_alias_registry.register('bp', 'breezy.plugins')
3627
3964
 
3628
3965
 
3629
3966
def _test_suite_testmod_names():
3630
3967
    """Return the standard list of test module names to test."""
3631
3968
    return [
3632
 
        'bzrlib.doc',
3633
 
        'bzrlib.tests.blackbox',
3634
 
        'bzrlib.tests.commands',
3635
 
        'bzrlib.tests.per_branch',
3636
 
        'bzrlib.tests.per_bzrdir',
3637
 
        'bzrlib.tests.per_bzrdir_colo',
3638
 
        'bzrlib.tests.per_foreign_vcs',
3639
 
        'bzrlib.tests.per_interrepository',
3640
 
        'bzrlib.tests.per_intertree',
3641
 
        'bzrlib.tests.per_inventory',
3642
 
        'bzrlib.tests.per_interbranch',
3643
 
        'bzrlib.tests.per_lock',
3644
 
        'bzrlib.tests.per_merger',
3645
 
        'bzrlib.tests.per_transport',
3646
 
        'bzrlib.tests.per_tree',
3647
 
        'bzrlib.tests.per_pack_repository',
3648
 
        'bzrlib.tests.per_repository',
3649
 
        'bzrlib.tests.per_repository_chk',
3650
 
        'bzrlib.tests.per_repository_reference',
3651
 
        'bzrlib.tests.per_uifactory',
3652
 
        'bzrlib.tests.per_versionedfile',
3653
 
        'bzrlib.tests.per_workingtree',
3654
 
        'bzrlib.tests.test__annotator',
3655
 
        'bzrlib.tests.test__bencode',
3656
 
        'bzrlib.tests.test__chk_map',
3657
 
        'bzrlib.tests.test__dirstate_helpers',
3658
 
        'bzrlib.tests.test__groupcompress',
3659
 
        'bzrlib.tests.test__known_graph',
3660
 
        'bzrlib.tests.test__rio',
3661
 
        'bzrlib.tests.test__simple_set',
3662
 
        'bzrlib.tests.test__static_tuple',
3663
 
        'bzrlib.tests.test__walkdirs_win32',
3664
 
        'bzrlib.tests.test_ancestry',
3665
 
        'bzrlib.tests.test_annotate',
3666
 
        'bzrlib.tests.test_api',
3667
 
        'bzrlib.tests.test_atomicfile',
3668
 
        'bzrlib.tests.test_bad_files',
3669
 
        'bzrlib.tests.test_bisect_multi',
3670
 
        'bzrlib.tests.test_branch',
3671
 
        'bzrlib.tests.test_branchbuilder',
3672
 
        'bzrlib.tests.test_btree_index',
3673
 
        'bzrlib.tests.test_bugtracker',
3674
 
        'bzrlib.tests.test_bundle',
3675
 
        'bzrlib.tests.test_bzrdir',
3676
 
        'bzrlib.tests.test__chunks_to_lines',
3677
 
        'bzrlib.tests.test_cache_utf8',
3678
 
        'bzrlib.tests.test_chk_map',
3679
 
        'bzrlib.tests.test_chk_serializer',
3680
 
        'bzrlib.tests.test_chunk_writer',
3681
 
        'bzrlib.tests.test_clean_tree',
3682
 
        'bzrlib.tests.test_cleanup',
3683
 
        'bzrlib.tests.test_cmdline',
3684
 
        'bzrlib.tests.test_commands',
3685
 
        'bzrlib.tests.test_commit',
3686
 
        'bzrlib.tests.test_commit_merge',
3687
 
        'bzrlib.tests.test_config',
3688
 
        'bzrlib.tests.test_conflicts',
3689
 
        'bzrlib.tests.test_counted_lock',
3690
 
        'bzrlib.tests.test_crash',
3691
 
        'bzrlib.tests.test_decorators',
3692
 
        'bzrlib.tests.test_delta',
3693
 
        'bzrlib.tests.test_debug',
3694
 
        'bzrlib.tests.test_deprecated_graph',
3695
 
        'bzrlib.tests.test_diff',
3696
 
        'bzrlib.tests.test_directory_service',
3697
 
        'bzrlib.tests.test_dirstate',
3698
 
        'bzrlib.tests.test_email_message',
3699
 
        'bzrlib.tests.test_eol_filters',
3700
 
        'bzrlib.tests.test_errors',
3701
 
        'bzrlib.tests.test_export',
3702
 
        'bzrlib.tests.test_extract',
3703
 
        'bzrlib.tests.test_fetch',
3704
 
        'bzrlib.tests.test_fifo_cache',
3705
 
        'bzrlib.tests.test_filters',
3706
 
        'bzrlib.tests.test_ftp_transport',
3707
 
        'bzrlib.tests.test_foreign',
3708
 
        'bzrlib.tests.test_generate_docs',
3709
 
        'bzrlib.tests.test_generate_ids',
3710
 
        'bzrlib.tests.test_globbing',
3711
 
        'bzrlib.tests.test_gpg',
3712
 
        'bzrlib.tests.test_graph',
3713
 
        'bzrlib.tests.test_groupcompress',
3714
 
        'bzrlib.tests.test_hashcache',
3715
 
        'bzrlib.tests.test_help',
3716
 
        'bzrlib.tests.test_hooks',
3717
 
        'bzrlib.tests.test_http',
3718
 
        'bzrlib.tests.test_http_response',
3719
 
        'bzrlib.tests.test_https_ca_bundle',
3720
 
        'bzrlib.tests.test_identitymap',
3721
 
        'bzrlib.tests.test_ignores',
3722
 
        'bzrlib.tests.test_index',
3723
 
        'bzrlib.tests.test_import_tariff',
3724
 
        'bzrlib.tests.test_info',
3725
 
        'bzrlib.tests.test_inv',
3726
 
        'bzrlib.tests.test_inventory_delta',
3727
 
        'bzrlib.tests.test_knit',
3728
 
        'bzrlib.tests.test_lazy_import',
3729
 
        'bzrlib.tests.test_lazy_regex',
3730
 
        'bzrlib.tests.test_lock',
3731
 
        'bzrlib.tests.test_lockable_files',
3732
 
        'bzrlib.tests.test_lockdir',
3733
 
        'bzrlib.tests.test_log',
3734
 
        'bzrlib.tests.test_lru_cache',
3735
 
        'bzrlib.tests.test_lsprof',
3736
 
        'bzrlib.tests.test_mail_client',
3737
 
        'bzrlib.tests.test_matchers',
3738
 
        'bzrlib.tests.test_memorytree',
3739
 
        'bzrlib.tests.test_merge',
3740
 
        'bzrlib.tests.test_merge3',
3741
 
        'bzrlib.tests.test_merge_core',
3742
 
        'bzrlib.tests.test_merge_directive',
3743
 
        'bzrlib.tests.test_missing',
3744
 
        'bzrlib.tests.test_msgeditor',
3745
 
        'bzrlib.tests.test_multiparent',
3746
 
        'bzrlib.tests.test_mutabletree',
3747
 
        'bzrlib.tests.test_nonascii',
3748
 
        'bzrlib.tests.test_options',
3749
 
        'bzrlib.tests.test_osutils',
3750
 
        'bzrlib.tests.test_osutils_encodings',
3751
 
        'bzrlib.tests.test_pack',
3752
 
        'bzrlib.tests.test_patch',
3753
 
        'bzrlib.tests.test_patches',
3754
 
        'bzrlib.tests.test_permissions',
3755
 
        'bzrlib.tests.test_plugins',
3756
 
        'bzrlib.tests.test_progress',
3757
 
        'bzrlib.tests.test_read_bundle',
3758
 
        'bzrlib.tests.test_reconcile',
3759
 
        'bzrlib.tests.test_reconfigure',
3760
 
        'bzrlib.tests.test_registry',
3761
 
        'bzrlib.tests.test_remote',
3762
 
        'bzrlib.tests.test_rename_map',
3763
 
        'bzrlib.tests.test_repository',
3764
 
        'bzrlib.tests.test_revert',
3765
 
        'bzrlib.tests.test_revision',
3766
 
        'bzrlib.tests.test_revisionspec',
3767
 
        'bzrlib.tests.test_revisiontree',
3768
 
        'bzrlib.tests.test_rio',
3769
 
        'bzrlib.tests.test_rules',
3770
 
        'bzrlib.tests.test_sampler',
3771
 
        'bzrlib.tests.test_script',
3772
 
        'bzrlib.tests.test_selftest',
3773
 
        'bzrlib.tests.test_serializer',
3774
 
        'bzrlib.tests.test_setup',
3775
 
        'bzrlib.tests.test_sftp_transport',
3776
 
        'bzrlib.tests.test_shelf',
3777
 
        'bzrlib.tests.test_shelf_ui',
3778
 
        'bzrlib.tests.test_smart',
3779
 
        'bzrlib.tests.test_smart_add',
3780
 
        'bzrlib.tests.test_smart_request',
3781
 
        'bzrlib.tests.test_smart_transport',
3782
 
        'bzrlib.tests.test_smtp_connection',
3783
 
        'bzrlib.tests.test_source',
3784
 
        'bzrlib.tests.test_ssh_transport',
3785
 
        'bzrlib.tests.test_status',
3786
 
        'bzrlib.tests.test_store',
3787
 
        'bzrlib.tests.test_strace',
3788
 
        'bzrlib.tests.test_subsume',
3789
 
        'bzrlib.tests.test_switch',
3790
 
        'bzrlib.tests.test_symbol_versioning',
3791
 
        'bzrlib.tests.test_tag',
3792
 
        'bzrlib.tests.test_testament',
3793
 
        'bzrlib.tests.test_textfile',
3794
 
        'bzrlib.tests.test_textmerge',
3795
 
        'bzrlib.tests.test_timestamp',
3796
 
        'bzrlib.tests.test_trace',
3797
 
        'bzrlib.tests.test_transactions',
3798
 
        'bzrlib.tests.test_transform',
3799
 
        'bzrlib.tests.test_transport',
3800
 
        'bzrlib.tests.test_transport_log',
3801
 
        'bzrlib.tests.test_tree',
3802
 
        'bzrlib.tests.test_treebuilder',
3803
 
        'bzrlib.tests.test_tsort',
3804
 
        'bzrlib.tests.test_tuned_gzip',
3805
 
        'bzrlib.tests.test_ui',
3806
 
        'bzrlib.tests.test_uncommit',
3807
 
        'bzrlib.tests.test_upgrade',
3808
 
        'bzrlib.tests.test_upgrade_stacked',
3809
 
        'bzrlib.tests.test_urlutils',
3810
 
        'bzrlib.tests.test_version',
3811
 
        'bzrlib.tests.test_version_info',
3812
 
        'bzrlib.tests.test_weave',
3813
 
        'bzrlib.tests.test_whitebox',
3814
 
        'bzrlib.tests.test_win32utils',
3815
 
        'bzrlib.tests.test_workingtree',
3816
 
        'bzrlib.tests.test_workingtree_4',
3817
 
        'bzrlib.tests.test_wsgi',
3818
 
        'bzrlib.tests.test_xml',
 
3969
        'breezy.git.tests.test_blackbox',
 
3970
        'breezy.git.tests.test_builder',
 
3971
        'breezy.git.tests.test_branch',
 
3972
        'breezy.git.tests.test_cache',
 
3973
        'breezy.git.tests.test_dir',
 
3974
        'breezy.git.tests.test_fetch',
 
3975
        'breezy.git.tests.test_git_remote_helper',
 
3976
        'breezy.git.tests.test_mapping',
 
3977
        'breezy.git.tests.test_memorytree',
 
3978
        'breezy.git.tests.test_object_store',
 
3979
        'breezy.git.tests.test_pristine_tar',
 
3980
        'breezy.git.tests.test_push',
 
3981
        'breezy.git.tests.test_remote',
 
3982
        'breezy.git.tests.test_repository',
 
3983
        'breezy.git.tests.test_refs',
 
3984
        'breezy.git.tests.test_revspec',
 
3985
        'breezy.git.tests.test_roundtrip',
 
3986
        'breezy.git.tests.test_server',
 
3987
        'breezy.git.tests.test_transportgit',
 
3988
        'breezy.git.tests.test_unpeel_map',
 
3989
        'breezy.git.tests.test_urls',
 
3990
        'breezy.git.tests.test_workingtree',
 
3991
        'breezy.tests.blackbox',
 
3992
        'breezy.tests.commands',
 
3993
        'breezy.tests.per_branch',
 
3994
        'breezy.tests.per_bzrdir',
 
3995
        'breezy.tests.per_controldir',
 
3996
        'breezy.tests.per_controldir_colo',
 
3997
        'breezy.tests.per_foreign_vcs',
 
3998
        'breezy.tests.per_interrepository',
 
3999
        'breezy.tests.per_intertree',
 
4000
        'breezy.tests.per_inventory',
 
4001
        'breezy.tests.per_interbranch',
 
4002
        'breezy.tests.per_lock',
 
4003
        'breezy.tests.per_merger',
 
4004
        'breezy.tests.per_transport',
 
4005
        'breezy.tests.per_tree',
 
4006
        'breezy.tests.per_pack_repository',
 
4007
        'breezy.tests.per_repository',
 
4008
        'breezy.tests.per_repository_chk',
 
4009
        'breezy.tests.per_repository_reference',
 
4010
        'breezy.tests.per_repository_vf',
 
4011
        'breezy.tests.per_uifactory',
 
4012
        'breezy.tests.per_versionedfile',
 
4013
        'breezy.tests.per_workingtree',
 
4014
        'breezy.tests.test__annotator',
 
4015
        'breezy.tests.test__bencode',
 
4016
        'breezy.tests.test__btree_serializer',
 
4017
        'breezy.tests.test__chk_map',
 
4018
        'breezy.tests.test__dirstate_helpers',
 
4019
        'breezy.tests.test__groupcompress',
 
4020
        'breezy.tests.test__known_graph',
 
4021
        'breezy.tests.test__rio',
 
4022
        'breezy.tests.test__simple_set',
 
4023
        'breezy.tests.test__static_tuple',
 
4024
        'breezy.tests.test__walkdirs_win32',
 
4025
        'breezy.tests.test_ancestry',
 
4026
        'breezy.tests.test_annotate',
 
4027
        'breezy.tests.test_atomicfile',
 
4028
        'breezy.tests.test_bad_files',
 
4029
        'breezy.tests.test_bisect',
 
4030
        'breezy.tests.test_bisect_multi',
 
4031
        'breezy.tests.test_branch',
 
4032
        'breezy.tests.test_branchbuilder',
 
4033
        'breezy.tests.test_btree_index',
 
4034
        'breezy.tests.test_bugtracker',
 
4035
        'breezy.tests.test_bundle',
 
4036
        'breezy.tests.test_bzrdir',
 
4037
        'breezy.tests.test__chunks_to_lines',
 
4038
        'breezy.tests.test_cache_utf8',
 
4039
        'breezy.tests.test_chk_map',
 
4040
        'breezy.tests.test_chk_serializer',
 
4041
        'breezy.tests.test_chunk_writer',
 
4042
        'breezy.tests.test_clean_tree',
 
4043
        'breezy.tests.test_cleanup',
 
4044
        'breezy.tests.test_cmdline',
 
4045
        'breezy.tests.test_commands',
 
4046
        'breezy.tests.test_commit',
 
4047
        'breezy.tests.test_commit_merge',
 
4048
        'breezy.tests.test_config',
 
4049
        'breezy.tests.test_conflicts',
 
4050
        'breezy.tests.test_controldir',
 
4051
        'breezy.tests.test_counted_lock',
 
4052
        'breezy.tests.test_crash',
 
4053
        'breezy.tests.test_decorators',
 
4054
        'breezy.tests.test_delta',
 
4055
        'breezy.tests.test_debug',
 
4056
        'breezy.tests.test_diff',
 
4057
        'breezy.tests.test_directory_service',
 
4058
        'breezy.tests.test_dirstate',
 
4059
        'breezy.tests.test_email_message',
 
4060
        'breezy.tests.test_eol_filters',
 
4061
        'breezy.tests.test_errors',
 
4062
        'breezy.tests.test_estimate_compressed_size',
 
4063
        'breezy.tests.test_export',
 
4064
        'breezy.tests.test_export_pot',
 
4065
        'breezy.tests.test_extract',
 
4066
        'breezy.tests.test_features',
 
4067
        'breezy.tests.test_fetch',
 
4068
        'breezy.tests.test_fetch_ghosts',
 
4069
        'breezy.tests.test_fixtures',
 
4070
        'breezy.tests.test_fifo_cache',
 
4071
        'breezy.tests.test_filters',
 
4072
        'breezy.tests.test_filter_tree',
 
4073
        'breezy.tests.test_foreign',
 
4074
        'breezy.tests.test_generate_docs',
 
4075
        'breezy.tests.test_generate_ids',
 
4076
        'breezy.tests.test_globbing',
 
4077
        'breezy.tests.test_gpg',
 
4078
        'breezy.tests.test_graph',
 
4079
        'breezy.tests.test_groupcompress',
 
4080
        'breezy.tests.test_hashcache',
 
4081
        'breezy.tests.test_help',
 
4082
        'breezy.tests.test_hooks',
 
4083
        'breezy.tests.test_http',
 
4084
        'breezy.tests.test_http_response',
 
4085
        'breezy.tests.test_https_ca_bundle',
 
4086
        'breezy.tests.test_https_urllib',
 
4087
        'breezy.tests.test_i18n',
 
4088
        'breezy.tests.test_identitymap',
 
4089
        'breezy.tests.test_ignores',
 
4090
        'breezy.tests.test_index',
 
4091
        'breezy.tests.test_import_tariff',
 
4092
        'breezy.tests.test_info',
 
4093
        'breezy.tests.test_inv',
 
4094
        'breezy.tests.test_inventory_delta',
 
4095
        'breezy.tests.test_knit',
 
4096
        'breezy.tests.test_lazy_import',
 
4097
        'breezy.tests.test_lazy_regex',
 
4098
        'breezy.tests.test_library_state',
 
4099
        'breezy.tests.test_lock',
 
4100
        'breezy.tests.test_lockable_files',
 
4101
        'breezy.tests.test_lockdir',
 
4102
        'breezy.tests.test_log',
 
4103
        'breezy.tests.test_lru_cache',
 
4104
        'breezy.tests.test_lsprof',
 
4105
        'breezy.tests.test_mail_client',
 
4106
        'breezy.tests.test_matchers',
 
4107
        'breezy.tests.test_memorytree',
 
4108
        'breezy.tests.test_merge',
 
4109
        'breezy.tests.test_merge3',
 
4110
        'breezy.tests.test_merge_core',
 
4111
        'breezy.tests.test_merge_directive',
 
4112
        'breezy.tests.test_mergetools',
 
4113
        'breezy.tests.test_missing',
 
4114
        'breezy.tests.test_msgeditor',
 
4115
        'breezy.tests.test_multiparent',
 
4116
        'breezy.tests.test_mutabletree',
 
4117
        'breezy.tests.test_nonascii',
 
4118
        'breezy.tests.test_options',
 
4119
        'breezy.tests.test_osutils',
 
4120
        'breezy.tests.test_osutils_encodings',
 
4121
        'breezy.tests.test_pack',
 
4122
        'breezy.tests.test_patch',
 
4123
        'breezy.tests.test_patches',
 
4124
        'breezy.tests.test_permissions',
 
4125
        'breezy.tests.test_plugins',
 
4126
        'breezy.tests.test_progress',
 
4127
        'breezy.tests.test_pyutils',
 
4128
        'breezy.tests.test_read_bundle',
 
4129
        'breezy.tests.test_reconcile',
 
4130
        'breezy.tests.test_reconfigure',
 
4131
        'breezy.tests.test_registry',
 
4132
        'breezy.tests.test_remote',
 
4133
        'breezy.tests.test_rename_map',
 
4134
        'breezy.tests.test_repository',
 
4135
        'breezy.tests.test_revert',
 
4136
        'breezy.tests.test_revision',
 
4137
        'breezy.tests.test_revisionspec',
 
4138
        'breezy.tests.test_revisiontree',
 
4139
        'breezy.tests.test_rio',
 
4140
        'breezy.tests.test_rules',
 
4141
        'breezy.tests.test_url_policy_open',
 
4142
        'breezy.tests.test_sampler',
 
4143
        'breezy.tests.test_scenarios',
 
4144
        'breezy.tests.test_script',
 
4145
        'breezy.tests.test_selftest',
 
4146
        'breezy.tests.test_serializer',
 
4147
        'breezy.tests.test_setup',
 
4148
        'breezy.tests.test_sftp_transport',
 
4149
        'breezy.tests.test_shelf',
 
4150
        'breezy.tests.test_shelf_ui',
 
4151
        'breezy.tests.test_smart',
 
4152
        'breezy.tests.test_smart_add',
 
4153
        'breezy.tests.test_smart_request',
 
4154
        'breezy.tests.test_smart_signals',
 
4155
        'breezy.tests.test_smart_transport',
 
4156
        'breezy.tests.test_smtp_connection',
 
4157
        'breezy.tests.test_source',
 
4158
        'breezy.tests.test_ssh_transport',
 
4159
        'breezy.tests.test_status',
 
4160
        'breezy.tests.test_strace',
 
4161
        'breezy.tests.test_subsume',
 
4162
        'breezy.tests.test_switch',
 
4163
        'breezy.tests.test_symbol_versioning',
 
4164
        'breezy.tests.test_tag',
 
4165
        'breezy.tests.test_test_server',
 
4166
        'breezy.tests.test_testament',
 
4167
        'breezy.tests.test_textfile',
 
4168
        'breezy.tests.test_textmerge',
 
4169
        'breezy.tests.test_cethread',
 
4170
        'breezy.tests.test_timestamp',
 
4171
        'breezy.tests.test_trace',
 
4172
        'breezy.tests.test_transactions',
 
4173
        'breezy.tests.test_transform',
 
4174
        'breezy.tests.test_transport',
 
4175
        'breezy.tests.test_transport_log',
 
4176
        'breezy.tests.test_tree',
 
4177
        'breezy.tests.test_treebuilder',
 
4178
        'breezy.tests.test_treeshape',
 
4179
        'breezy.tests.test_tsort',
 
4180
        'breezy.tests.test_tuned_gzip',
 
4181
        'breezy.tests.test_ui',
 
4182
        'breezy.tests.test_uncommit',
 
4183
        'breezy.tests.test_upgrade',
 
4184
        'breezy.tests.test_upgrade_stacked',
 
4185
        'breezy.tests.test_upstream_import',
 
4186
        'breezy.tests.test_urlutils',
 
4187
        'breezy.tests.test_utextwrap',
 
4188
        'breezy.tests.test_version',
 
4189
        'breezy.tests.test_version_info',
 
4190
        'breezy.tests.test_versionedfile',
 
4191
        'breezy.tests.test_vf_search',
 
4192
        'breezy.tests.test_views',
 
4193
        'breezy.tests.test_weave',
 
4194
        'breezy.tests.test_whitebox',
 
4195
        'breezy.tests.test_win32utils',
 
4196
        'breezy.tests.test_workingtree',
 
4197
        'breezy.tests.test_workingtree_4',
 
4198
        'breezy.tests.test_wsgi',
 
4199
        'breezy.tests.test_xml',
3819
4200
        ]
3820
4201
 
3821
4202
 
3825
4206
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
3826
4207
        return []
3827
4208
    return [
3828
 
        'bzrlib',
3829
 
        'bzrlib.branchbuilder',
3830
 
        'bzrlib.decorators',
3831
 
        'bzrlib.export',
3832
 
        'bzrlib.inventory',
3833
 
        'bzrlib.iterablefile',
3834
 
        'bzrlib.lockdir',
3835
 
        'bzrlib.merge3',
3836
 
        'bzrlib.option',
3837
 
        'bzrlib.symbol_versioning',
3838
 
        'bzrlib.tests',
3839
 
        'bzrlib.timestamp',
3840
 
        'bzrlib.version_info_formats.format_custom',
 
4209
        'breezy',
 
4210
        'breezy.branchbuilder',
 
4211
        'breezy.bzr.inventory',
 
4212
        'breezy.decorators',
 
4213
        'breezy.iterablefile',
 
4214
        'breezy.lockdir',
 
4215
        'breezy.merge3',
 
4216
        'breezy.option',
 
4217
        'breezy.pyutils',
 
4218
        'breezy.symbol_versioning',
 
4219
        'breezy.tests',
 
4220
        'breezy.tests.fixtures',
 
4221
        'breezy.timestamp',
 
4222
        'breezy.transport.http',
 
4223
        'breezy.version_info_formats.format_custom',
3841
4224
        ]
3842
4225
 
3843
4226
 
3844
4227
def test_suite(keep_only=None, starting_with=None):
3845
 
    """Build and return TestSuite for the whole of bzrlib.
 
4228
    """Build and return TestSuite for the whole of breezy.
3846
4229
 
3847
4230
    :param keep_only: A list of test ids limiting the suite returned.
3848
4231
 
3888
4271
    # modules building their suite with loadTestsFromModuleNames
3889
4272
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
3890
4273
 
3891
 
    for mod in _test_suite_modules_to_doctest():
3892
 
        if not interesting_module(mod):
3893
 
            # No tests to keep here, move along
3894
 
            continue
3895
 
        try:
3896
 
            # note that this really does mean "report only" -- doctest
3897
 
            # still runs the rest of the examples
3898
 
            doc_suite = doctest.DocTestSuite(mod,
3899
 
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3900
 
        except ValueError, e:
3901
 
            print '**failed to get doctest for: %s\n%s' % (mod, e)
3902
 
            raise
3903
 
        if len(doc_suite._tests) == 0:
3904
 
            raise errors.BzrError("no doctests found in %s" % (mod,))
3905
 
        suite.addTest(doc_suite)
 
4274
    if not PY3:
 
4275
        suite.addTest(loader.loadTestsFromModuleNames(['breezy.doc']))
 
4276
 
 
4277
        # It's pretty much impossible to write readable doctests that work on
 
4278
        # both Python 2 and Python 3 because of their overreliance on
 
4279
        # consistent repr() return values.
 
4280
        # For now, just run doctests on Python 2 so we now they haven't broken.
 
4281
        for mod in _test_suite_modules_to_doctest():
 
4282
            if not interesting_module(mod):
 
4283
                # No tests to keep here, move along
 
4284
                continue
 
4285
            try:
 
4286
                # note that this really does mean "report only" -- doctest
 
4287
                # still runs the rest of the examples
 
4288
                doc_suite = IsolatedDocTestSuite(
 
4289
                    mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4290
            except ValueError as e:
 
4291
                print('**failed to get doctest for: %s\n%s' % (mod, e))
 
4292
                raise
 
4293
            if len(doc_suite._tests) == 0:
 
4294
                raise errors.BzrError("no doctests found in %s" % (mod,))
 
4295
            suite.addTest(doc_suite)
3906
4296
 
3907
4297
    default_encoding = sys.getdefaultencoding()
3908
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4298
    for name, plugin in _mod_plugin.plugins().items():
3909
4299
        if not interesting_module(plugin.module.__name__):
3910
4300
            continue
3911
4301
        plugin_suite = plugin.test_suite()
3917
4307
        if plugin_suite is not None:
3918
4308
            suite.addTest(plugin_suite)
3919
4309
        if default_encoding != sys.getdefaultencoding():
3920
 
            bzrlib.trace.warning(
 
4310
            trace.warning(
3921
4311
                'Plugin "%s" tried to reset default encoding to: %s', name,
3922
4312
                sys.getdefaultencoding())
3923
4313
            reload(sys)
3938
4328
            # Some tests mentioned in the list are not in the test suite. The
3939
4329
            # list may be out of date, report to the tester.
3940
4330
            for id in not_found:
3941
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4331
                trace.warning('"%s" not found in the test suite', id)
3942
4332
        for id in duplicates:
3943
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4333
            trace.warning('"%s" is used as an id by several tests', id)
3944
4334
 
3945
4335
    return suite
3946
4336
 
3947
4337
 
3948
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4338
def multiply_scenarios(*scenarios):
 
4339
    """Multiply two or more iterables of scenarios.
 
4340
 
 
4341
    It is safe to pass scenario generators or iterators.
 
4342
 
 
4343
    :returns: A list of compound scenarios: the cross-product of all
 
4344
        scenarios, with the names concatenated and the parameters
 
4345
        merged together.
 
4346
    """
 
4347
    return functools.reduce(_multiply_two_scenarios, map(list, scenarios))
 
4348
 
 
4349
 
 
4350
def _multiply_two_scenarios(scenarios_left, scenarios_right):
3949
4351
    """Multiply two sets of scenarios.
3950
4352
 
3951
4353
    :returns: the cartesian product of the two sets of scenarios, that is
3954
4356
    """
3955
4357
    return [
3956
4358
        ('%s,%s' % (left_name, right_name),
3957
 
         dict(left_dict.items() + right_dict.items()))
 
4359
         dict(left_dict, **right_dict))
3958
4360
        for left_name, left_dict in scenarios_left
3959
4361
        for right_name, right_dict in scenarios_right]
3960
4362
 
3977
4379
    the scenario name at the end of its id(), and updating the test object's
3978
4380
    __dict__ with the scenario_param_dict.
3979
4381
 
3980
 
    >>> import bzrlib.tests.test_sampler
 
4382
    >>> import breezy.tests.test_sampler
3981
4383
    >>> r = multiply_tests(
3982
 
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
 
4384
    ...     breezy.tests.test_sampler.DemoTest('test_nothing'),
3983
4385
    ...     [('one', dict(param=1)),
3984
4386
    ...      ('two', dict(param=2))],
3985
 
    ...     TestSuite())
 
4387
    ...     TestUtil.TestSuite())
3986
4388
    >>> tests = list(iter_suite_tests(r))
3987
4389
    >>> len(tests)
3988
4390
    2
3989
4391
    >>> tests[0].id()
3990
 
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
 
4392
    'breezy.tests.test_sampler.DemoTest.test_nothing(one)'
3991
4393
    >>> tests[0].param
3992
4394
    1
3993
4395
    >>> tests[1].param
4015
4417
    """Copy test and apply scenario to it.
4016
4418
 
4017
4419
    :param test: A test to adapt.
4018
 
    :param scenario: A tuple describing the scenarion.
 
4420
    :param scenario: A tuple describing the scenario.
4019
4421
        The first element of the tuple is the new test id.
4020
4422
        The second element is a dict containing attributes to set on the
4021
4423
        test.
4035
4437
    :param new_id: The id to assign to it.
4036
4438
    :return: The new test.
4037
4439
    """
4038
 
    new_test = copy(test)
 
4440
    new_test = copy.copy(test)
4039
4441
    new_test.id = lambda: new_id
 
4442
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4443
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4444
    # read the test output for parameterized tests, because tracebacks will be
 
4445
    # associated with irrelevant tests.
 
4446
    try:
 
4447
        details = new_test._TestCase__details
 
4448
    except AttributeError:
 
4449
        # must be a different version of testtools than expected.  Do nothing.
 
4450
        pass
 
4451
    else:
 
4452
        # Reset the '__details' dict.
 
4453
        new_test._TestCase__details = {}
4040
4454
    return new_test
4041
4455
 
4042
4456
 
4047
4461
    This is meant to be used inside a modules 'load_tests()' function. It will
4048
4462
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
4049
4463
    against both implementations. Setting 'test.module' to the appropriate
4050
 
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
 
4464
    module. See breezy.tests.test__chk_map.load_tests as an example.
4051
4465
 
4052
4466
    :param standard_tests: A test suite to permute
4053
4467
    :param loader: A TestLoader
4054
4468
    :param py_module_name: The python path to a python module that can always
4055
4469
        be loaded, and will be considered the 'python' implementation. (eg
4056
 
        'bzrlib._chk_map_py')
 
4470
        'breezy._chk_map_py')
4057
4471
    :param ext_module_name: The python path to an extension module. If the
4058
4472
        module cannot be loaded, a single test will be added, which notes that
4059
4473
        the module is not available. If it can be loaded, all standard_tests
4063
4477
        the module is available.
4064
4478
    """
4065
4479
 
4066
 
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4480
    from .features import ModuleAvailableFeature
 
4481
    py_module = pyutils.get_named_object(py_module_name)
4067
4482
    scenarios = [
4068
4483
        ('python', {'module': py_module}),
4069
4484
    ]
4088
4503
    # except on win32, where rmtree(str) will fail
4089
4504
    # since it doesn't have the property of byte-stream paths
4090
4505
    # (they are either ascii or mbcs)
4091
 
    if sys.platform == 'win32':
 
4506
    if sys.platform == 'win32' and isinstance(dirname, bytes):
4092
4507
        # make sure we are using the unicode win32 api
4093
 
        dirname = unicode(dirname)
 
4508
        dirname = dirname.decode('mbcs')
4094
4509
    else:
4095
4510
        dirname = dirname.encode(sys.getfilesystemencoding())
4096
4511
    try:
4097
4512
        osutils.rmtree(dirname)
4098
 
    except OSError, e:
 
4513
    except OSError as e:
4099
4514
        # We don't want to fail here because some useful display will be lost
4100
4515
        # otherwise. Polluting the tmp dir is bad, but not giving all the
4101
4516
        # possible info to the test runner is even worse.
4102
4517
        if test_id != None:
4103
4518
            ui.ui_factory.clear_term()
4104
4519
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4520
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4521
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4522
                                    ).encode('ascii', 'replace')
4105
4523
        sys.stderr.write('Unable to remove testing dir %s\n%s'
4106
 
                         % (os.path.basename(dirname), e))
4107
 
 
4108
 
 
4109
 
class Feature(object):
4110
 
    """An operating system Feature."""
4111
 
 
4112
 
    def __init__(self):
4113
 
        self._available = None
4114
 
 
4115
 
    def available(self):
4116
 
        """Is the feature available?
4117
 
 
4118
 
        :return: True if the feature is available.
4119
 
        """
4120
 
        if self._available is None:
4121
 
            self._available = self._probe()
4122
 
        return self._available
4123
 
 
4124
 
    def _probe(self):
4125
 
        """Implement this method in concrete features.
4126
 
 
4127
 
        :return: True if the feature is available.
4128
 
        """
4129
 
        raise NotImplementedError
4130
 
 
4131
 
    def __str__(self):
4132
 
        if getattr(self, 'feature_name', None):
4133
 
            return self.feature_name()
4134
 
        return self.__class__.__name__
4135
 
 
4136
 
 
4137
 
class _SymlinkFeature(Feature):
4138
 
 
4139
 
    def _probe(self):
4140
 
        return osutils.has_symlinks()
4141
 
 
4142
 
    def feature_name(self):
4143
 
        return 'symlinks'
4144
 
 
4145
 
SymlinkFeature = _SymlinkFeature()
4146
 
 
4147
 
 
4148
 
class _HardlinkFeature(Feature):
4149
 
 
4150
 
    def _probe(self):
4151
 
        return osutils.has_hardlinks()
4152
 
 
4153
 
    def feature_name(self):
4154
 
        return 'hardlinks'
4155
 
 
4156
 
HardlinkFeature = _HardlinkFeature()
4157
 
 
4158
 
 
4159
 
class _OsFifoFeature(Feature):
4160
 
 
4161
 
    def _probe(self):
4162
 
        return getattr(os, 'mkfifo', None)
4163
 
 
4164
 
    def feature_name(self):
4165
 
        return 'filesystem fifos'
4166
 
 
4167
 
OsFifoFeature = _OsFifoFeature()
4168
 
 
4169
 
 
4170
 
class _UnicodeFilenameFeature(Feature):
4171
 
    """Does the filesystem support Unicode filenames?"""
4172
 
 
4173
 
    def _probe(self):
4174
 
        try:
4175
 
            # Check for character combinations unlikely to be covered by any
4176
 
            # single non-unicode encoding. We use the characters
4177
 
            # - greek small letter alpha (U+03B1) and
4178
 
            # - braille pattern dots-123456 (U+283F).
4179
 
            os.stat(u'\u03b1\u283f')
4180
 
        except UnicodeEncodeError:
4181
 
            return False
4182
 
        except (IOError, OSError):
4183
 
            # The filesystem allows the Unicode filename but the file doesn't
4184
 
            # exist.
4185
 
            return True
4186
 
        else:
4187
 
            # The filesystem allows the Unicode filename and the file exists,
4188
 
            # for some reason.
4189
 
            return True
4190
 
 
4191
 
UnicodeFilenameFeature = _UnicodeFilenameFeature()
4192
 
 
4193
 
 
4194
 
class _CompatabilityThunkFeature(Feature):
4195
 
    """This feature is just a thunk to another feature.
4196
 
 
4197
 
    It issues a deprecation warning if it is accessed, to let you know that you
4198
 
    should really use a different feature.
4199
 
    """
4200
 
 
4201
 
    def __init__(self, dep_version, module, name,
4202
 
                 replacement_name, replacement_module=None):
4203
 
        super(_CompatabilityThunkFeature, self).__init__()
4204
 
        self._module = module
4205
 
        if replacement_module is None:
4206
 
            replacement_module = module
4207
 
        self._replacement_module = replacement_module
4208
 
        self._name = name
4209
 
        self._replacement_name = replacement_name
4210
 
        self._dep_version = dep_version
4211
 
        self._feature = None
4212
 
 
4213
 
    def _ensure(self):
4214
 
        if self._feature is None:
4215
 
            depr_msg = self._dep_version % ('%s.%s'
4216
 
                                            % (self._module, self._name))
4217
 
            use_msg = ' Use %s.%s instead.' % (self._replacement_module,
4218
 
                                               self._replacement_name)
4219
 
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
4220
 
            # Import the new feature and use it as a replacement for the
4221
 
            # deprecated one.
4222
 
            mod = __import__(self._replacement_module, {}, {},
4223
 
                             [self._replacement_name])
4224
 
            self._feature = getattr(mod, self._replacement_name)
4225
 
 
4226
 
    def _probe(self):
4227
 
        self._ensure()
4228
 
        return self._feature._probe()
4229
 
 
4230
 
 
4231
 
class ModuleAvailableFeature(Feature):
4232
 
    """This is a feature than describes a module we want to be available.
4233
 
 
4234
 
    Declare the name of the module in __init__(), and then after probing, the
4235
 
    module will be available as 'self.module'.
4236
 
 
4237
 
    :ivar module: The module if it is available, else None.
4238
 
    """
4239
 
 
4240
 
    def __init__(self, module_name):
4241
 
        super(ModuleAvailableFeature, self).__init__()
4242
 
        self.module_name = module_name
4243
 
 
4244
 
    def _probe(self):
4245
 
        try:
4246
 
            self._module = __import__(self.module_name, {}, {}, [''])
4247
 
            return True
4248
 
        except ImportError:
4249
 
            return False
4250
 
 
4251
 
    @property
4252
 
    def module(self):
4253
 
        if self.available(): # Make sure the probe has been done
4254
 
            return self._module
4255
 
        return None
4256
 
 
4257
 
    def feature_name(self):
4258
 
        return self.module_name
4259
 
 
4260
 
 
4261
 
# This is kept here for compatibility, it is recommended to use
4262
 
# 'bzrlib.tests.feature.paramiko' instead
4263
 
ParamikoFeature = _CompatabilityThunkFeature(
4264
 
    deprecated_in((2,1,0)),
4265
 
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
 
4524
                         % (os.path.basename(dirname), printable_e))
4266
4525
 
4267
4526
 
4268
4527
def probe_unicode_in_user_encoding():
4289
4548
    Return None if all non-ascii characters is valid
4290
4549
    for given encoding.
4291
4550
    """
4292
 
    for i in xrange(128, 256):
4293
 
        char = chr(i)
 
4551
    for i in range(128, 256):
 
4552
        char = int2byte(i)
4294
4553
        try:
4295
4554
            char.decode(encoding)
4296
4555
        except UnicodeDecodeError:
4298
4557
    return None
4299
4558
 
4300
4559
 
4301
 
class _HTTPSServerFeature(Feature):
4302
 
    """Some tests want an https Server, check if one is available.
4303
 
 
4304
 
    Right now, the only way this is available is under python2.6 which provides
4305
 
    an ssl module.
4306
 
    """
4307
 
 
4308
 
    def _probe(self):
4309
 
        try:
4310
 
            import ssl
4311
 
            return True
4312
 
        except ImportError:
4313
 
            return False
4314
 
 
4315
 
    def feature_name(self):
4316
 
        return 'HTTPSServer'
4317
 
 
4318
 
 
4319
 
HTTPSServerFeature = _HTTPSServerFeature()
4320
 
 
4321
 
 
4322
 
class _UnicodeFilename(Feature):
4323
 
    """Does the filesystem support Unicode filenames?"""
4324
 
 
4325
 
    def _probe(self):
4326
 
        try:
4327
 
            os.stat(u'\u03b1')
4328
 
        except UnicodeEncodeError:
4329
 
            return False
4330
 
        except (IOError, OSError):
4331
 
            # The filesystem allows the Unicode filename but the file doesn't
4332
 
            # exist.
4333
 
            return True
4334
 
        else:
4335
 
            # The filesystem allows the Unicode filename and the file exists,
4336
 
            # for some reason.
4337
 
            return True
4338
 
 
4339
 
UnicodeFilename = _UnicodeFilename()
4340
 
 
4341
 
 
4342
 
class _UTF8Filesystem(Feature):
4343
 
    """Is the filesystem UTF-8?"""
4344
 
 
4345
 
    def _probe(self):
4346
 
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
4347
 
            return True
4348
 
        return False
4349
 
 
4350
 
UTF8Filesystem = _UTF8Filesystem()
4351
 
 
4352
 
 
4353
 
class _BreakinFeature(Feature):
4354
 
    """Does this platform support the breakin feature?"""
4355
 
 
4356
 
    def _probe(self):
4357
 
        from bzrlib import breakin
4358
 
        if breakin.determine_signal() is None:
4359
 
            return False
4360
 
        if sys.platform == 'win32':
4361
 
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
4362
 
            # We trigger SIGBREAK via a Console api so we need ctypes to
4363
 
            # access the function
4364
 
            try:
4365
 
                import ctypes
4366
 
            except OSError:
4367
 
                return False
4368
 
        return True
4369
 
 
4370
 
    def feature_name(self):
4371
 
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
4372
 
 
4373
 
 
4374
 
BreakinFeature = _BreakinFeature()
4375
 
 
4376
 
 
4377
 
class _CaseInsCasePresFilenameFeature(Feature):
4378
 
    """Is the file-system case insensitive, but case-preserving?"""
4379
 
 
4380
 
    def _probe(self):
4381
 
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
4382
 
        try:
4383
 
            # first check truly case-preserving for created files, then check
4384
 
            # case insensitive when opening existing files.
4385
 
            name = osutils.normpath(name)
4386
 
            base, rel = osutils.split(name)
4387
 
            found_rel = osutils.canonical_relpath(base, name)
4388
 
            return (found_rel == rel
4389
 
                    and os.path.isfile(name.upper())
4390
 
                    and os.path.isfile(name.lower()))
4391
 
        finally:
4392
 
            os.close(fileno)
4393
 
            os.remove(name)
4394
 
 
4395
 
    def feature_name(self):
4396
 
        return "case-insensitive case-preserving filesystem"
4397
 
 
4398
 
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
4399
 
 
4400
 
 
4401
 
class _CaseInsensitiveFilesystemFeature(Feature):
4402
 
    """Check if underlying filesystem is case-insensitive but *not* case
4403
 
    preserving.
4404
 
    """
4405
 
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
4406
 
    # more likely to be case preserving, so this case is rare.
4407
 
 
4408
 
    def _probe(self):
4409
 
        if CaseInsCasePresFilenameFeature.available():
4410
 
            return False
4411
 
 
4412
 
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
4413
 
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
4414
 
            TestCaseWithMemoryTransport.TEST_ROOT = root
4415
 
        else:
4416
 
            root = TestCaseWithMemoryTransport.TEST_ROOT
4417
 
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
4418
 
            dir=root)
4419
 
        name_a = osutils.pathjoin(tdir, 'a')
4420
 
        name_A = osutils.pathjoin(tdir, 'A')
4421
 
        os.mkdir(name_a)
4422
 
        result = osutils.isdir(name_A)
4423
 
        _rmtree_temp_dir(tdir)
4424
 
        return result
4425
 
 
4426
 
    def feature_name(self):
4427
 
        return 'case-insensitive filesystem'
4428
 
 
4429
 
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
4430
 
 
4431
 
 
4432
 
class _CaseSensitiveFilesystemFeature(Feature):
4433
 
 
4434
 
    def _probe(self):
4435
 
        if CaseInsCasePresFilenameFeature.available():
4436
 
            return False
4437
 
        elif CaseInsensitiveFilesystemFeature.available():
4438
 
            return False
4439
 
        else:
4440
 
            return True
4441
 
 
4442
 
    def feature_name(self):
4443
 
        return 'case-sensitive filesystem'
4444
 
 
4445
 
# new coding style is for feature instances to be lowercase
4446
 
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
4447
 
 
4448
 
 
4449
 
# Kept for compatibility, use bzrlib.tests.features.subunit instead
4450
 
SubUnitFeature = _CompatabilityThunkFeature(
4451
 
    deprecated_in((2,1,0)),
4452
 
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
4453
4560
# Only define SubUnitBzrRunner if subunit is available.
4454
4561
try:
4455
4562
    from subunit import TestProtocolClient
4456
4563
    from subunit.test_results import AutoTimingTestResultDecorator
4457
 
    class SubUnitBzrRunner(TextTestRunner):
 
4564
 
 
4565
    class SubUnitBzrProtocolClientv1(TestProtocolClient):
 
4566
 
 
4567
        def stopTest(self, test):
 
4568
            super(SubUnitBzrProtocolClientv1, self).stopTest(test)
 
4569
            _clear__type_equality_funcs(test)
 
4570
 
 
4571
        def addSuccess(self, test, details=None):
 
4572
            # The subunit client always includes the details in the subunit
 
4573
            # stream, but we don't want to include it in ours.
 
4574
            if details is not None and 'log' in details:
 
4575
                del details['log']
 
4576
            return super(SubUnitBzrProtocolClientv1, self).addSuccess(
 
4577
                test, details)
 
4578
 
 
4579
    class SubUnitBzrRunnerv1(TextTestRunner):
 
4580
 
4458
4581
        def run(self, test):
4459
4582
            result = AutoTimingTestResultDecorator(
4460
 
                TestProtocolClient(self.stream))
 
4583
                SubUnitBzrProtocolClientv1(self.stream))
4461
4584
            test.run(result)
4462
4585
            return result
4463
4586
except ImportError:
4464
4587
    pass
4465
4588
 
4466
 
class _PosixPermissionsFeature(Feature):
4467
 
 
4468
 
    def _probe(self):
4469
 
        def has_perms():
4470
 
            # create temporary file and check if specified perms are maintained.
4471
 
            import tempfile
4472
 
 
4473
 
            write_perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
4474
 
            f = tempfile.mkstemp(prefix='bzr_perms_chk_')
4475
 
            fd, name = f
4476
 
            os.close(fd)
4477
 
            os.chmod(name, write_perms)
4478
 
 
4479
 
            read_perms = os.stat(name).st_mode & 0777
4480
 
            os.unlink(name)
4481
 
            return (write_perms == read_perms)
4482
 
 
4483
 
        return (os.name == 'posix') and has_perms()
4484
 
 
4485
 
    def feature_name(self):
4486
 
        return 'POSIX permissions support'
4487
 
 
4488
 
posix_permissions_feature = _PosixPermissionsFeature()
 
4589
 
 
4590
try:
 
4591
    from subunit.run import SubunitTestRunner
 
4592
 
 
4593
    class SubUnitBzrRunnerv2(TextTestRunner, SubunitTestRunner):
 
4594
 
 
4595
        def __init__(self, stream=sys.stderr, descriptions=0, verbosity=1,
 
4596
                     bench_history=None, strict=False, result_decorators=None):
 
4597
            TextTestRunner.__init__(
 
4598
                    self, stream=stream,
 
4599
                    descriptions=descriptions, verbosity=verbosity,
 
4600
                    bench_history=bench_history, strict=strict,
 
4601
                    result_decorators=result_decorators)
 
4602
            SubunitTestRunner.__init__(self, verbosity=verbosity,
 
4603
                                       stream=stream)
 
4604
 
 
4605
        run = SubunitTestRunner.run
 
4606
except ImportError:
 
4607
    pass