/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-07-06 23:36:14 UTC
  • mto: (7027.3.2 python3-n)
  • mto: This revision was merged to the branch mainline in revision 7030.
  • Revision ID: jelmer@jelmer.uk-20180706233614-t4m8krag15t4z4lp
Update python3.passing.

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
    )
 
37
import itertools
37
38
import logging
38
39
import math
39
40
import os
40
 
from pprint import pformat
 
41
import platform
 
42
import pprint
41
43
import random
42
44
import re
43
45
import shlex
 
46
import site
44
47
import stat
45
 
from subprocess import Popen, PIPE, STDOUT
 
48
import subprocess
46
49
import sys
47
50
import tempfile
48
51
import threading
54
57
import testtools
55
58
# nb: check this before importing anything else from within it
56
59
_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"
 
60
if _testtools_version < (0, 9, 5):
 
61
    raise ImportError("need at least testtools 0.9.5: %s is %r"
59
62
        % (testtools.__file__, _testtools_version))
60
63
from testtools import content
61
64
 
62
 
from bzrlib import (
 
65
import breezy
 
66
from .. import (
63
67
    branchbuilder,
64
 
    bzrdir,
65
 
    chk_map,
 
68
    controldir,
 
69
    commands as _mod_commands,
66
70
    config,
 
71
    i18n,
67
72
    debug,
68
73
    errors,
69
74
    hooks,
70
75
    lock as _mod_lock,
 
76
    lockdir,
71
77
    memorytree,
72
78
    osutils,
73
 
    progress,
 
79
    plugin as _mod_plugin,
 
80
    pyutils,
74
81
    ui,
75
82
    urlutils,
76
83
    registry,
 
84
    symbol_versioning,
 
85
    trace,
 
86
    transport as _mod_transport,
77
87
    workingtree,
78
88
    )
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
 
89
from breezy.bzr import (
 
90
    chk_map,
 
91
    )
86
92
try:
87
 
    import bzrlib.lsprof
 
93
    import breezy.lsprof
88
94
except ImportError:
89
95
    # lsprof not available
90
96
    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,
 
97
from ..sixish import (
 
98
    PY3,
 
99
    string_types,
 
100
    text_type,
103
101
    )
104
 
import bzrlib.trace
105
 
from bzrlib.transport import (
106
 
    get_transport,
 
102
from ..bzr.smart import client, request
 
103
from ..transport import (
107
104
    memory,
108
105
    pathfilter,
109
106
    )
110
 
import bzrlib.transport
111
 
from bzrlib.trace import mutter, note
112
 
from bzrlib.tests import (
 
107
from ..tests import (
 
108
    fixtures,
113
109
    test_server,
114
110
    TestUtil,
 
111
    treeshape,
 
112
    ui_testing,
115
113
    )
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
 
114
from ..tests.features import _CompatabilityThunkFeature
126
115
 
127
116
# Mark this python module as being part of the implementation
128
117
# of unittest: this gives us better tracebacks where the last
140
129
SUBUNIT_SEEK_SET = 0
141
130
SUBUNIT_SEEK_CUR = 1
142
131
 
143
 
 
144
 
class ExtendedTestResult(unittest._TextTestResult):
 
132
# These are intentionally brought into this namespace. That way plugins, etc
 
133
# can just "from breezy.tests import TestCase, TestLoader, etc"
 
134
TestSuite = TestUtil.TestSuite
 
135
TestLoader = TestUtil.TestLoader
 
136
 
 
137
# Tests should run in a clean and clearly defined environment. The goal is to
 
138
# keep them isolated from the running environment as mush as possible. The test
 
139
# framework ensures the variables defined below are set (or deleted if the
 
140
# value is None) before a test is run and reset to their original value after
 
141
# the test is run. Generally if some code depends on an environment variable,
 
142
# the tests should start without this variable in the environment. There are a
 
143
# few exceptions but you shouldn't violate this rule lightly.
 
144
isolated_environ = {
 
145
    'BRZ_HOME': None,
 
146
    'HOME': None,
 
147
    'GNUPGHOME': None,
 
148
    'XDG_CONFIG_HOME': None,
 
149
    # brz now uses the Win32 API and doesn't rely on APPDATA, but the
 
150
    # tests do check our impls match APPDATA
 
151
    'BRZ_EDITOR': None, # test_msgeditor manipulates this variable
 
152
    'VISUAL': None,
 
153
    'EDITOR': None,
 
154
    'BRZ_EMAIL': None,
 
155
    'BZREMAIL': None, # may still be present in the environment
 
156
    'EMAIL': 'jrandom@example.com', # set EMAIL as brz does not guess
 
157
    'BRZ_PROGRESS_BAR': None,
 
158
    # This should trap leaks to ~/.brz.log. This occurs when tests use TestCase
 
159
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
 
160
    # TestCase should not use disk resources, BRZ_LOG is one.
 
161
    'BRZ_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
162
    'BRZ_PLUGIN_PATH': '-site',
 
163
    'BRZ_DISABLE_PLUGINS': None,
 
164
    'BRZ_PLUGINS_AT': None,
 
165
    'BRZ_CONCURRENCY': None,
 
166
    # Make sure that any text ui tests are consistent regardless of
 
167
    # the environment the test case is run in; you may want tests that
 
168
    # test other combinations.  'dumb' is a reasonable guess for tests
 
169
    # going to a pipe or a BytesIO.
 
170
    'TERM': 'dumb',
 
171
    'LINES': '25',
 
172
    'COLUMNS': '80',
 
173
    'BRZ_COLUMNS': '80',
 
174
    # Disable SSH Agent
 
175
    'SSH_AUTH_SOCK': None,
 
176
    # Proxies
 
177
    'http_proxy': None,
 
178
    'HTTP_PROXY': None,
 
179
    'https_proxy': None,
 
180
    'HTTPS_PROXY': None,
 
181
    'no_proxy': None,
 
182
    'NO_PROXY': None,
 
183
    'all_proxy': None,
 
184
    'ALL_PROXY': None,
 
185
    'BZR_REMOTE_PATH': None,
 
186
    # Generally speaking, we don't want apport reporting on crashes in
 
187
    # the test envirnoment unless we're specifically testing apport,
 
188
    # so that it doesn't leak into the real system environment.  We
 
189
    # use an env var so it propagates to subprocesses.
 
190
    'APPORT_DISABLE': '1',
 
191
    }
 
192
 
 
193
 
 
194
def override_os_environ(test, env=None):
 
195
    """Modify os.environ keeping a copy.
 
196
 
 
197
    :param test: A test instance
 
198
 
 
199
    :param env: A dict containing variable definitions to be installed
 
200
    """
 
201
    if env is None:
 
202
        env = isolated_environ
 
203
    test._original_os_environ = dict(**os.environ)
 
204
    for var in env:
 
205
        osutils.set_or_unset_env(var, env[var])
 
206
        if var not in test._original_os_environ:
 
207
            # The var is new, add it with a value of None, so
 
208
            # restore_os_environ will delete it
 
209
            test._original_os_environ[var] = None
 
210
 
 
211
 
 
212
def restore_os_environ(test):
 
213
    """Restore os.environ to its original state.
 
214
 
 
215
    :param test: A test instance previously passed to override_os_environ.
 
216
    """
 
217
    for var, value in test._original_os_environ.items():
 
218
        # Restore the original value (or delete it if the value has been set to
 
219
        # None in override_os_environ).
 
220
        osutils.set_or_unset_env(var, value)
 
221
 
 
222
 
 
223
def _clear__type_equality_funcs(test):
 
224
    """Cleanup bound methods stored on TestCase instances
 
225
 
 
226
    Clear the dict breaking a few (mostly) harmless cycles in the affected
 
227
    unittests released with Python 2.6 and initial Python 2.7 versions.
 
228
 
 
229
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
 
230
    shipped in Oneiric, an object with no clear method was used, hence the
 
231
    extra complications, see bug 809048 for details.
 
232
    """
 
233
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
234
    if type_equality_funcs is not None:
 
235
        tef_clear = getattr(type_equality_funcs, "clear", None)
 
236
        if tef_clear is None:
 
237
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
 
238
            if tef_instance_dict is not None:
 
239
                tef_clear = tef_instance_dict.clear
 
240
        if tef_clear is not None:
 
241
            tef_clear()
 
242
 
 
243
 
 
244
class ExtendedTestResult(testtools.TextTestResult):
145
245
    """Accepts, reports and accumulates the results of running tests.
146
246
 
147
247
    Compared to the unittest version this class adds support for
150
250
    different types of display.
151
251
 
152
252
    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
 
253
    addFailure or addError methods.  These in turn may redirect to a more
154
254
    specific case for the special test results supported by our extended
155
255
    tests.
156
256
 
168
268
        :param bench_history: Optionally, a writable file object to accumulate
169
269
            benchmark results.
170
270
        """
171
 
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
271
        testtools.TextTestResult.__init__(self, stream)
172
272
        if bench_history is not None:
173
 
            from bzrlib.version import _get_bzr_source_tree
 
273
            from breezy.version import _get_bzr_source_tree
174
274
            src_tree = _get_bzr_source_tree()
175
275
            if src_tree:
176
276
                try:
178
278
                except IndexError:
179
279
                    # XXX: if this is a brand new tree, do the same as if there
180
280
                    # is no branch.
181
 
                    revision_id = ''
 
281
                    revision_id = b''
182
282
            else:
183
283
                # XXX: If there's no branch, what should we do?
184
 
                revision_id = ''
 
284
                revision_id = b''
185
285
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
186
286
        self._bench_history = bench_history
187
287
        self.ui = ui.ui_factory
195
295
        self.count = 0
196
296
        self._overall_start_time = time.time()
197
297
        self._strict = strict
 
298
        self._first_thread_leaker_id = None
 
299
        self._tests_leaking_threads_count = 0
 
300
        self._traceback_from_test = None
198
301
 
199
302
    def stopTestRun(self):
200
303
        run = self.testsRun
201
304
        actionTaken = "Ran"
202
305
        stopTime = time.time()
203
306
        timeTaken = stopTime - self.startTime
204
 
        self.printErrors()
205
 
        self.stream.writeln(self.separator2)
206
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
307
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
 
308
        #                the parent class method is similar have to duplicate
 
309
        self._show_list('ERROR', self.errors)
 
310
        self._show_list('FAIL', self.failures)
 
311
        self.stream.write(self.sep2)
 
312
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
207
313
                            run, run != 1 and "s" or "", timeTaken))
208
 
        self.stream.writeln()
209
314
        if not self.wasSuccessful():
210
315
            self.stream.write("FAILED (")
211
316
            failed, errored = map(len, (self.failures, self.errors))
218
323
                if failed or errored: self.stream.write(", ")
219
324
                self.stream.write("known_failure_count=%d" %
220
325
                    self.known_failure_count)
221
 
            self.stream.writeln(")")
 
326
            self.stream.write(")\n")
222
327
        else:
223
328
            if self.known_failure_count:
224
 
                self.stream.writeln("OK (known_failures=%d)" %
 
329
                self.stream.write("OK (known_failures=%d)\n" %
225
330
                    self.known_failure_count)
226
331
            else:
227
 
                self.stream.writeln("OK")
 
332
                self.stream.write("OK\n")
228
333
        if self.skip_count > 0:
229
334
            skipped = self.skip_count
230
 
            self.stream.writeln('%d test%s skipped' %
 
335
            self.stream.write('%d test%s skipped\n' %
231
336
                                (skipped, skipped != 1 and "s" or ""))
232
337
        if self.unsupported:
233
338
            for feature, count in sorted(self.unsupported.items()):
234
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
339
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
235
340
                    (feature, count))
236
341
        if self._strict:
237
342
            ok = self.wasStrictlySuccessful()
238
343
        else:
239
344
            ok = self.wasSuccessful()
240
 
        if TestCase._first_thread_leaker_id:
 
345
        if self._first_thread_leaker_id:
241
346
            self.stream.write(
242
347
                '%s is leaking threads among %d leaking tests.\n' % (
243
 
                TestCase._first_thread_leaker_id,
244
 
                TestCase._leaking_threads_tests))
 
348
                self._first_thread_leaker_id,
 
349
                self._tests_leaking_threads_count))
245
350
            # We don't report the main thread as an active one.
246
351
            self.stream.write(
247
352
                '%d non-main threads were left active in the end.\n'
248
 
                % (TestCase._active_threads - 1))
 
353
                % (len(self._active_threads) - 1))
249
354
 
250
355
    def getDescription(self, test):
251
356
        return test.id()
256
361
            return float(''.join(details['benchtime'].iter_bytes()))
257
362
        return getattr(testCase, "_benchtime", None)
258
363
 
 
364
    def _delta_to_float(self, a_timedelta, precision):
 
365
        # This calls ceiling to ensure that the most pessimistic view of time
 
366
        # taken is shown (rather than leaving it to the Python %f operator
 
367
        # to decide whether to round/floor/ceiling. This was added when we
 
368
        # had pyp3 test failures that suggest a floor was happening.
 
369
        shift = 10 ** precision
 
370
        return math.ceil((a_timedelta.days * 86400.0 + a_timedelta.seconds +
 
371
            a_timedelta.microseconds / 1000000.0) * shift) / shift
 
372
 
259
373
    def _elapsedTestTimeString(self):
260
374
        """Return a time string for the overall time the current test has taken."""
261
 
        return self._formatTime(time.time() - self._start_time)
 
375
        return self._formatTime(self._delta_to_float(
 
376
            self._now() - self._start_datetime, 3))
262
377
 
263
378
    def _testTimeString(self, testCase):
264
379
        benchmark_time = self._extractBenchmarkTime(testCase)
275
390
 
276
391
    def _shortened_test_description(self, test):
277
392
        what = test.id()
278
 
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
393
        what = re.sub(r'^breezy\.tests\.', '', what)
279
394
        return what
280
395
 
 
396
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
397
    #                multiple times in a row, because the handler is added for
 
398
    #                each test but the container list is shared between cases.
 
399
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
400
    def _record_traceback_from_test(self, exc_info):
 
401
        """Store the traceback from passed exc_info tuple till"""
 
402
        self._traceback_from_test = exc_info[2]
 
403
 
281
404
    def startTest(self, test):
282
 
        unittest.TestResult.startTest(self, test)
 
405
        super(ExtendedTestResult, self).startTest(test)
283
406
        if self.count == 0:
284
407
            self.startTests()
 
408
        self.count += 1
285
409
        self.report_test_start(test)
286
410
        test.number = self.count
287
411
        self._recordTestStartTime()
 
412
        # Make testtools cases give us the real traceback on failure
 
413
        addOnException = getattr(test, "addOnException", None)
 
414
        if addOnException is not None:
 
415
            addOnException(self._record_traceback_from_test)
 
416
        # Only check for thread leaks on breezy derived test cases
 
417
        if isinstance(test, TestCase):
 
418
            test.addCleanup(self._check_leaked_threads, test)
 
419
 
 
420
    def stopTest(self, test):
 
421
        super(ExtendedTestResult, self).stopTest(test)
 
422
        # Manually break cycles, means touching various private things but hey
 
423
        getDetails = getattr(test, "getDetails", None)
 
424
        if getDetails is not None:
 
425
            getDetails().clear()
 
426
        _clear__type_equality_funcs(test)
 
427
        self._traceback_from_test = None
288
428
 
289
429
    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')
 
430
        self.report_tests_starting()
 
431
        self._active_threads = threading.enumerate()
 
432
 
 
433
    def _check_leaked_threads(self, test):
 
434
        """See if any threads have leaked since last call
 
435
 
 
436
        A sample of live threads is stored in the _active_threads attribute,
 
437
        when this method runs it compares the current live threads and any not
 
438
        in the previous sample are treated as having leaked.
 
439
        """
 
440
        now_active_threads = set(threading.enumerate())
 
441
        threads_leaked = now_active_threads.difference(self._active_threads)
 
442
        if threads_leaked:
 
443
            self._report_thread_leak(test, threads_leaked, now_active_threads)
 
444
            self._tests_leaking_threads_count += 1
 
445
            if self._first_thread_leaker_id is None:
 
446
                self._first_thread_leaker_id = test.id()
 
447
            self._active_threads = now_active_threads
307
448
 
308
449
    def _recordTestStartTime(self):
309
450
        """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()
 
451
        self._start_datetime = self._now()
318
452
 
319
453
    def addError(self, test, err):
320
454
        """Tell result that test finished with an error.
322
456
        Called from the TestCase run() method when the test
323
457
        fails with an unexpected error.
324
458
        """
325
 
        self._post_mortem()
326
 
        unittest.TestResult.addError(self, test, err)
 
459
        self._post_mortem(self._traceback_from_test)
 
460
        super(ExtendedTestResult, self).addError(test, err)
327
461
        self.error_count += 1
328
462
        self.report_error(test, err)
329
463
        if self.stop_early:
330
464
            self.stop()
331
 
        self._cleanupLogFile(test)
332
465
 
333
466
    def addFailure(self, test, err):
334
467
        """Tell result that test failed.
336
469
        Called from the TestCase run() method when the test
337
470
        fails because e.g. an assert() method failed.
338
471
        """
339
 
        self._post_mortem()
340
 
        unittest.TestResult.addFailure(self, test, err)
 
472
        self._post_mortem(self._traceback_from_test)
 
473
        super(ExtendedTestResult, self).addFailure(test, err)
341
474
        self.failure_count += 1
342
475
        self.report_failure(test, err)
343
476
        if self.stop_early:
344
477
            self.stop()
345
 
        self._cleanupLogFile(test)
346
478
 
347
479
    def addSuccess(self, test, details=None):
348
480
        """Tell result that test completed successfully.
356
488
                    self._formatTime(benchmark_time),
357
489
                    test.id()))
358
490
        self.report_success(test)
359
 
        self._cleanupLogFile(test)
360
 
        unittest.TestResult.addSuccess(self, test)
 
491
        super(ExtendedTestResult, self).addSuccess(test)
361
492
        test._log_contents = ''
362
493
 
363
494
    def addExpectedFailure(self, test, err):
364
495
        self.known_failure_count += 1
365
496
        self.report_known_failure(test, err)
366
497
 
 
498
    def addUnexpectedSuccess(self, test, details=None):
 
499
        """Tell result the test unexpectedly passed, counting as a failure
 
500
 
 
501
        When the minimum version of testtools required becomes 0.9.8 this
 
502
        can be updated to use the new handling there.
 
503
        """
 
504
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
505
        self.failure_count += 1
 
506
        self.report_unexpected_success(test,
 
507
            "".join(details["reason"].iter_text()))
 
508
        if self.stop_early:
 
509
            self.stop()
 
510
 
367
511
    def addNotSupported(self, test, feature):
368
512
        """The test will not be run because of a missing feature.
369
513
        """
386
530
        self.not_applicable_count += 1
387
531
        self.report_not_applicable(test, reason)
388
532
 
389
 
    def _post_mortem(self):
 
533
    def _count_stored_tests(self):
 
534
        """Count of tests instances kept alive due to not succeeding"""
 
535
        return self.error_count + self.failure_count + self.known_failure_count
 
536
 
 
537
    def _post_mortem(self, tb=None):
390
538
        """Start a PDB post mortem session."""
391
 
        if os.environ.get('BZR_TEST_PDB', None):
392
 
            import pdb;pdb.post_mortem()
 
539
        if os.environ.get('BRZ_TEST_PDB', None):
 
540
            import pdb
 
541
            pdb.post_mortem(tb)
393
542
 
394
543
    def progress(self, offset, whence):
395
544
        """The test is adjusting the count of tests to run."""
400
549
        else:
401
550
            raise errors.BzrError("Unknown whence %r" % whence)
402
551
 
403
 
    def report_cleaning_up(self):
404
 
        pass
 
552
    def report_tests_starting(self):
 
553
        """Display information before the test run begins"""
 
554
        if getattr(sys, 'frozen', None) is None:
 
555
            bzr_path = osutils.realpath(sys.argv[0])
 
556
        else:
 
557
            bzr_path = sys.executable
 
558
        self.stream.write(
 
559
            'brz selftest: %s\n' % (bzr_path,))
 
560
        self.stream.write(
 
561
            '   %s\n' % (
 
562
                    breezy.__path__[0],))
 
563
        self.stream.write(
 
564
            '   bzr-%s python-%s %s\n' % (
 
565
                    breezy.version_string,
 
566
                    breezy._format_version_tuple(sys.version_info),
 
567
                    platform.platform(aliased=1),
 
568
                    ))
 
569
        self.stream.write('\n')
 
570
 
 
571
    def report_test_start(self, test):
 
572
        """Display information on the test just about to be run"""
 
573
 
 
574
    def _report_thread_leak(self, test, leaked_threads, active_threads):
 
575
        """Display information on a test that leaked one or more threads"""
 
576
        # GZ 2010-09-09: A leak summary reported separately from the general
 
577
        #                thread debugging would be nice. Tests under subunit
 
578
        #                need something not using stream, perhaps adding a
 
579
        #                testtools details object would be fitting.
 
580
        if 'threads' in selftest_debug_flags:
 
581
            self.stream.write('%s is leaking, active is now %d\n' %
 
582
                (test.id(), len(active_threads)))
405
583
 
406
584
    def startTestRun(self):
407
585
        self.startTime = time.time()
420
598
 
421
599
    def __init__(self, stream, descriptions, verbosity,
422
600
                 bench_history=None,
423
 
                 pb=None,
424
601
                 strict=None,
425
602
                 ):
426
603
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
427
604
            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
605
        self.pb = self.ui.nested_progress_bar()
433
606
        self.pb.show_pct = False
434
607
        self.pb.show_spinner = False
444
617
        self.pb.finished()
445
618
        super(TextTestResult, self).stopTestRun()
446
619
 
447
 
    def startTestRun(self):
448
 
        super(TextTestResult, self).startTestRun()
 
620
    def report_tests_starting(self):
 
621
        super(TextTestResult, self).report_tests_starting()
449
622
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
450
623
 
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
624
    def _progress_prefix_text(self):
457
625
        # the longer this text, the less space we have to show the test
458
626
        # name...
480
648
        return a
481
649
 
482
650
    def report_test_start(self, test):
483
 
        self.count += 1
484
651
        self.pb.update(
485
652
                self._progress_prefix_text()
486
653
                + ' '
504
671
    def report_known_failure(self, test, err):
505
672
        pass
506
673
 
 
674
    def report_unexpected_success(self, test, reason):
 
675
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
 
676
            self._test_description(test),
 
677
            "Unexpected success. Should have failed",
 
678
            reason,
 
679
            ))
 
680
 
507
681
    def report_skip(self, test, reason):
508
682
        pass
509
683
 
513
687
    def report_unsupported(self, test, feature):
514
688
        """test cannot be run because feature is missing."""
515
689
 
516
 
    def report_cleaning_up(self):
517
 
        self.pb.update('Cleaning up')
518
 
 
519
690
 
520
691
class VerboseTestResult(ExtendedTestResult):
521
692
    """Produce long output, with one line per test run plus times"""
528
699
            result = a_string
529
700
        return result.ljust(final_width)
530
701
 
531
 
    def startTestRun(self):
532
 
        super(VerboseTestResult, self).startTestRun()
 
702
    def report_tests_starting(self):
533
703
        self.stream.write('running %d tests...\n' % self.num_tests)
 
704
        super(VerboseTestResult, self).report_tests_starting()
534
705
 
535
706
    def report_test_start(self, test):
536
 
        self.count += 1
537
707
        name = self._shortened_test_description(test)
538
708
        width = osutils.terminal_width()
539
709
        if width is not None:
551
721
        return '%s%s' % (indent, err[1])
552
722
 
553
723
    def report_error(self, test, err):
554
 
        self.stream.writeln('ERROR %s\n%s'
 
724
        self.stream.write('ERROR %s\n%s\n'
555
725
                % (self._testTimeString(test),
556
726
                   self._error_summary(err)))
557
727
 
558
728
    def report_failure(self, test, err):
559
 
        self.stream.writeln(' FAIL %s\n%s'
 
729
        self.stream.write(' FAIL %s\n%s\n'
560
730
                % (self._testTimeString(test),
561
731
                   self._error_summary(err)))
562
732
 
563
733
    def report_known_failure(self, test, err):
564
 
        self.stream.writeln('XFAIL %s\n%s'
 
734
        self.stream.write('XFAIL %s\n%s\n'
565
735
                % (self._testTimeString(test),
566
736
                   self._error_summary(err)))
567
737
 
 
738
    def report_unexpected_success(self, test, reason):
 
739
        self.stream.write(' FAIL %s\n%s: %s\n'
 
740
                % (self._testTimeString(test),
 
741
                   "Unexpected success. Should have failed",
 
742
                   reason))
 
743
 
568
744
    def report_success(self, test):
569
 
        self.stream.writeln('   OK %s' % self._testTimeString(test))
 
745
        self.stream.write('   OK %s\n' % self._testTimeString(test))
570
746
        for bench_called, stats in getattr(test, '_benchcalls', []):
571
 
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
747
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
572
748
            stats.pprint(file=self.stream)
573
749
        # flush the stream so that we get smooth output. This verbose mode is
574
750
        # used to show the output in PQM.
575
751
        self.stream.flush()
576
752
 
577
753
    def report_skip(self, test, reason):
578
 
        self.stream.writeln(' SKIP %s\n%s'
 
754
        self.stream.write(' SKIP %s\n%s\n'
579
755
                % (self._testTimeString(test), reason))
580
756
 
581
757
    def report_not_applicable(self, test, reason):
582
 
        self.stream.writeln('  N/A %s\n    %s'
 
758
        self.stream.write('  N/A %s\n    %s\n'
583
759
                % (self._testTimeString(test), reason))
584
760
 
585
761
    def report_unsupported(self, test, feature):
586
762
        """test cannot be run because feature is missing."""
587
 
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
 
763
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
588
764
                %(self._testTimeString(test), feature))
589
765
 
590
766
 
612
788
        # to encode using ascii.
613
789
        new_encoding = osutils.get_terminal_encoding()
614
790
        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)
 
791
        encode = codec.encode
 
792
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
793
        #                so should swap to the plain codecs.StreamWriter
 
794
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
795
            "backslashreplace")
621
796
        stream.encoding = new_encoding
622
 
        self.stream = unittest._WritelnDecorator(stream)
 
797
        self.stream = stream
623
798
        self.descriptions = descriptions
624
799
        self.verbosity = verbosity
625
800
        self._bench_history = bench_history
707
882
    """
708
883
 
709
884
 
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
 
 
 
885
class StringIOWrapper(ui_testing.BytesIOWithEncoding):
 
886
 
 
887
    @symbol_versioning.deprecated_method(
 
888
        symbol_versioning.deprecated_in((3, 0)))
720
889
    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.
 
890
        super(StringIOWrapper, self).__init__(s)
 
891
 
 
892
 
 
893
TestUIFactory = ui_testing.TestUIFactory
 
894
 
 
895
 
 
896
def isolated_doctest_setUp(test):
 
897
    override_os_environ(test)
 
898
    osutils.set_or_unset_env('BRZ_HOME', '/nonexistent')
 
899
    test._orig_ui_factory = ui.ui_factory
 
900
    ui.ui_factory = ui.SilentUIFactory()
 
901
 
 
902
 
 
903
def isolated_doctest_tearDown(test):
 
904
    restore_os_environ(test)
 
905
    ui.ui_factory = test._orig_ui_factory
 
906
 
 
907
 
 
908
def IsolatedDocTestSuite(*args, **kwargs):
 
909
    """Overrides doctest.DocTestSuite to handle isolation.
 
910
 
 
911
    The method is really a factory and users are expected to use it as such.
745
912
    """
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()
 
913
 
 
914
    kwargs['setUp'] = isolated_doctest_setUp
 
915
    kwargs['tearDown'] = isolated_doctest_tearDown
 
916
    return doctest.DocTestSuite(*args, **kwargs)
774
917
 
775
918
 
776
919
class TestCase(testtools.TestCase):
777
 
    """Base class for bzr unit tests.
 
920
    """Base class for brz unit tests.
778
921
 
779
922
    Tests that need access to disk resources should subclass
780
923
    TestCaseInTempDir not TestCase.
786
929
    is read into memory and removed from disk.
787
930
 
788
931
    There are also convenience functions to invoke bzr's command-line
789
 
    routine, and to build and check bzr trees.
 
932
    routine, and to build and check brz trees.
790
933
 
791
934
    In addition to the usual method of overriding tearDown(), this class also
792
 
    allows subclasses to register functions into the _cleanups list, which is
 
935
    allows subclasses to register cleanup functions via addCleanup, which are
793
936
    run in order as the object is torn down.  It's less likely this will be
794
937
    accidentally overlooked.
795
938
    """
796
939
 
797
 
    _active_threads = None
798
 
    _leaking_threads_tests = 0
799
 
    _first_thread_leaker_id = None
800
 
    _log_file_name = None
 
940
    _log_file = None
801
941
    # record lsprof data when performing benchmark calls.
802
942
    _gather_lsprof_in_benchmarks = False
803
943
 
804
944
    def __init__(self, methodName='testMethod'):
805
945
        super(TestCase, self).__init__(methodName)
806
 
        self._cleanups = []
807
946
        self._directory_isolation = True
808
947
        self.exception_handlers.insert(0,
809
948
            (UnavailableFeature, self._do_unsupported_or_skip))
812
951
 
813
952
    def setUp(self):
814
953
        super(TestCase, self).setUp()
 
954
 
 
955
        # At this point we're still accessing the config files in $BRZ_HOME (as
 
956
        # set by the user running selftest).
 
957
        timeout = config.GlobalStack().get('selftest.timeout')
 
958
        if timeout:
 
959
            timeout_fixture = fixtures.TimeoutFixture(timeout)
 
960
            timeout_fixture.setUp()
 
961
            self.addCleanup(timeout_fixture.cleanUp)
 
962
 
815
963
        for feature in getattr(self, '_test_needs_features', []):
816
964
            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
965
        self._cleanEnvironment()
 
966
 
 
967
        self.overrideAttr(breezy.get_global_state(), 'cmdline_overrides',
 
968
                          config.CommandLineStore())
 
969
 
822
970
        self._silenceUI()
823
971
        self._startLogFile()
824
972
        self._benchcalls = []
827
975
        self._track_transports()
828
976
        self._track_locks()
829
977
        self._clear_debug_flags()
830
 
        TestCase._active_threads = threading.activeCount()
831
 
        self.addCleanup(self._check_leaked_threads)
 
978
        # Isolate global verbosity level, to make sure it's reproducible
 
979
        # between tests.  We should get rid of this altogether: bug 656694. --
 
980
        # mbp 20101008
 
981
        self.overrideAttr(breezy.trace, '_verbosity_level', 0)
 
982
        self._log_files = set()
 
983
        # Each key in the ``_counters`` dict holds a value for a different
 
984
        # counter. When the test ends, addDetail() should be used to output the
 
985
        # counter values. This happens in install_counter_hook().
 
986
        self._counters = {}
 
987
        if 'config_stats' in selftest_debug_flags:
 
988
            self._install_config_stats_hooks()
 
989
        # Do not use i18n for tests (unless the test reverses this)
 
990
        i18n.disable_i18n()
832
991
 
833
992
    def debug(self):
834
993
        # debug a frame up.
835
994
        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()
 
995
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
996
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
997
                ).set_trace(sys._getframe().f_back)
 
998
 
 
999
    def discardDetail(self, name):
 
1000
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1001
 
 
1002
        eg. brz always adds the 'log' detail at startup, but we don't want to
 
1003
        include it for skipped, xfail, etc tests.
 
1004
 
 
1005
        It is safe to call this for a detail that doesn't exist, in case this
 
1006
        gets called multiple times.
 
1007
        """
 
1008
        # We cheat. details is stored in __details which means we shouldn't
 
1009
        # touch it. but getDetails() returns the dict directly, so we can
 
1010
        # mutate it.
 
1011
        details = self.getDetails()
 
1012
        if name in details:
 
1013
            del details[name]
 
1014
 
 
1015
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1016
        """Install a counting hook.
 
1017
 
 
1018
        Any hook can be counted as long as it doesn't need to return a value.
 
1019
 
 
1020
        :param hooks: Where the hook should be installed.
 
1021
 
 
1022
        :param name: The hook name that will be counted.
 
1023
 
 
1024
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1025
            to ``name``.
 
1026
        """
 
1027
        _counters = self._counters # Avoid closing over self
 
1028
        if counter_name is None:
 
1029
            counter_name = name
 
1030
        if counter_name in _counters:
 
1031
            raise AssertionError('%s is already used as a counter name'
 
1032
                                  % (counter_name,))
 
1033
        _counters[counter_name] = 0
 
1034
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1035
            lambda: [b'%d' % (_counters[counter_name],)]))
 
1036
        def increment_counter(*args, **kwargs):
 
1037
            _counters[counter_name] += 1
 
1038
        label = 'count %s calls' % (counter_name,)
 
1039
        hooks.install_named_hook(name, increment_counter, label)
 
1040
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1041
 
 
1042
    def _install_config_stats_hooks(self):
 
1043
        """Install config hooks to count hook calls.
 
1044
 
 
1045
        """
 
1046
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1047
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1048
                                       'config.%s' % (hook_name,))
 
1049
 
 
1050
        # The OldConfigHooks are private and need special handling to protect
 
1051
        # against recursive tests (tests that run other tests), so we just do
 
1052
        # manually what registering them into _builtin_known_hooks will provide
 
1053
        # us.
 
1054
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1055
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1056
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1057
                                      'old_config.%s' % (hook_name,))
852
1058
 
853
1059
    def _clear_debug_flags(self):
854
1060
        """Prevent externally set debug flags affecting tests.
865
1071
 
866
1072
    def _clear_hooks(self):
867
1073
        # prevent hooks affecting tests
 
1074
        known_hooks = hooks.known_hooks
868
1075
        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)
 
1076
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1077
            current_hooks = getattr(parent, name)
872
1078
            self._preserved_hooks[parent] = (name, current_hooks)
 
1079
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1080
        hooks._lazy_hooks = {}
873
1081
        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)
 
1082
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1083
            factory = known_hooks.get(key)
876
1084
            setattr(parent, name, factory())
877
1085
        # this hook should always be installed
878
1086
        request._install_hook()
907
1115
        # break some locks on purpose and should be taken into account by
908
1116
        # considering that breaking a lock is just a dirty way of releasing it.
909
1117
        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))
 
1118
            message = (
 
1119
                'Different number of acquired and '
 
1120
                'released or broken locks.\n'
 
1121
                'acquired=%s\n'
 
1122
                'released=%s\n'
 
1123
                'broken=%s\n' %
 
1124
                (acquired_locks, released_locks, broken_locks))
913
1125
            if not self._lock_check_thorough:
914
1126
                # Rather than fail, just warn
915
 
                print "Broken test %s: %s" % (self, message)
 
1127
                print("Broken test %s: %s" % (self, message))
916
1128
                return
917
1129
            self.fail(message)
918
1130
 
943
1155
 
944
1156
    def permit_dir(self, name):
945
1157
        """Permit a directory to be used by this test. See permit_url."""
946
 
        name_transport = get_transport(name)
 
1158
        name_transport = _mod_transport.get_transport_from_path(name)
947
1159
        self.permit_url(name)
948
1160
        self.permit_url(name_transport.base)
949
1161
 
950
1162
    def permit_url(self, url):
951
1163
        """Declare that url is an ok url to use in this test.
952
 
        
 
1164
 
953
1165
        Do this for memory transports, temporary test directory etc.
954
 
        
 
1166
 
955
1167
        Do not do this for the current working directory, /tmp, or any other
956
1168
        preexisting non isolated url.
957
1169
        """
960
1172
        self._bzr_selftest_roots.append(url)
961
1173
 
962
1174
    def permit_source_tree_branch_repo(self):
963
 
        """Permit the source tree bzr is running from to be opened.
 
1175
        """Permit the source tree brz is running from to be opened.
964
1176
 
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
 
1177
        Some code such as breezy.version attempts to read from the brz branch
 
1178
        that brz is executing from (if any). This method permits that directory
967
1179
        to be used in the test suite.
968
1180
        """
969
1181
        path = self.get_source_path()
972
1184
            try:
973
1185
                workingtree.WorkingTree.open(path)
974
1186
            except (errors.NotBranchError, errors.NoWorkingTree):
975
 
                return
 
1187
                raise TestSkipped('Needs a working tree of brz sources')
976
1188
        finally:
977
1189
            self.enable_directory_isolation()
978
1190
 
1010
1222
 
1011
1223
    def record_directory_isolation(self):
1012
1224
        """Gather accessed directories to permit later access.
1013
 
        
1014
 
        This is used for tests that access the branch bzr is running from.
 
1225
 
 
1226
        This is used for tests that access the branch brz is running from.
1015
1227
        """
1016
1228
        self._directory_isolation = "record"
1017
1229
 
1028
1240
        self.addCleanup(transport_server.stop_server)
1029
1241
        # Obtain a real transport because if the server supplies a password, it
1030
1242
        # will be hidden from the base on the client side.
1031
 
        t = get_transport(transport_server.get_url())
 
1243
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1032
1244
        # Some transport servers effectively chroot the backing transport;
1033
1245
        # others like SFTPServer don't - users of the transport can walk up the
1034
1246
        # transport to read the entire backing transport. This wouldn't matter
1062
1274
        # TestCase has no safe place it can write to.
1063
1275
        self._bzr_selftest_roots = []
1064
1276
        # 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
 
1277
        # hook into brz dir opening. This leaves a small window of error for
1066
1278
        # transport tests, but they are well known, and we can improve on this
1067
1279
        # step.
1068
 
        bzrdir.BzrDir.hooks.install_named_hook("pre_open",
1069
 
            self._preopen_isolate_transport, "Check bzr directories are safe.")
 
1280
        controldir.ControlDir.hooks.install_named_hook("pre_open",
 
1281
            self._preopen_isolate_transport, "Check brz directories are safe.")
1070
1282
 
1071
1283
    def _ndiff_strings(self, a, b):
1072
1284
        """Return ndiff between two strings containing lines.
1087
1299
        try:
1088
1300
            if a == b:
1089
1301
                return
1090
 
        except UnicodeError, e:
 
1302
        except UnicodeError as e:
1091
1303
            # If we can't compare without getting a UnicodeError, then
1092
1304
            # obviously they are different
1093
 
            mutter('UnicodeError: %s', e)
 
1305
            trace.mutter('UnicodeError: %s', e)
1094
1306
        if message:
1095
1307
            message += '\n'
1096
1308
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1097
1309
            % (message,
1098
 
               pformat(a), pformat(b)))
 
1310
               pprint.pformat(a), pprint.pformat(b)))
1099
1311
 
 
1312
    # FIXME: This is deprecated in unittest2 but plugins may still use it so we
 
1313
    # need a deprecation period for them -- vila 2016-02-01
1100
1314
    assertEquals = assertEqual
1101
1315
 
1102
1316
    def assertEqualDiff(self, a, b, message=None):
1105
1319
        This is intended for use with multi-line strings where it can
1106
1320
        be hard to find the differences by eye.
1107
1321
        """
1108
 
        # TODO: perhaps override assertEquals to call this for strings?
 
1322
        # TODO: perhaps override assertEqual to call this for strings?
1109
1323
        if a == b:
1110
1324
            return
1111
1325
        if message is None:
1135
1349
                         'st_mtime did not match')
1136
1350
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1137
1351
                         'st_ctime did not match')
1138
 
        if sys.platform != 'win32':
 
1352
        if sys.platform == 'win32':
1139
1353
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1140
1354
            # 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
 
1355
            # odd. We just force it to always be 0 to avoid any problems.
 
1356
            self.assertEqual(0, expected.st_dev)
 
1357
            self.assertEqual(0, actual.st_dev)
 
1358
            self.assertEqual(0, expected.st_ino)
 
1359
            self.assertEqual(0, actual.st_ino)
 
1360
        else:
1143
1361
            self.assertEqual(expected.st_dev, actual.st_dev,
1144
1362
                             'st_dev did not match')
1145
1363
            self.assertEqual(expected.st_ino, actual.st_ino,
1154
1372
                length, len(obj_with_len), obj_with_len))
1155
1373
 
1156
1374
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1157
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1375
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1158
1376
        """
1159
 
        from bzrlib import trace
1160
1377
        captured = []
1161
1378
        orig_log_exception_quietly = trace.log_exception_quietly
1162
1379
        try:
1163
1380
            def capture():
1164
1381
                orig_log_exception_quietly()
1165
 
                captured.append(sys.exc_info())
 
1382
                captured.append(sys.exc_info()[1])
1166
1383
            trace.log_exception_quietly = capture
1167
1384
            func(*args, **kwargs)
1168
1385
        finally:
1169
1386
            trace.log_exception_quietly = orig_log_exception_quietly
1170
1387
        self.assertLength(1, captured)
1171
 
        err = captured[0][1]
 
1388
        err = captured[0]
1172
1389
        self.assertIsInstance(err, exception_class)
1173
1390
        return err
1174
1391
 
1211
1428
        if haystack.find(needle) == -1:
1212
1429
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1213
1430
 
 
1431
    def assertNotContainsString(self, haystack, needle):
 
1432
        if haystack.find(needle) != -1:
 
1433
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1434
 
1214
1435
    def assertSubset(self, sublist, superlist):
1215
1436
        """Assert that every entry in sublist is present in superlist."""
1216
1437
        missing = set(sublist) - set(superlist)
1227
1448
        """
1228
1449
        try:
1229
1450
            list(func(*args, **kwargs))
1230
 
        except excClass, e:
 
1451
        except excClass as e:
1231
1452
            return e
1232
1453
        else:
1233
 
            if getattr(excClass,'__name__', None) is not None:
 
1454
            if getattr(excClass, '__name__', None) is not None:
1234
1455
                excName = excClass.__name__
1235
1456
            else:
1236
1457
                excName = str(excClass)
1237
 
            raise self.failureException, "%s not raised" % excName
 
1458
            raise self.failureException("%s not raised" % excName)
1238
1459
 
1239
1460
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
1240
1461
        """Assert that a callable raises a particular exception.
1248
1469
        """
1249
1470
        try:
1250
1471
            callableObj(*args, **kwargs)
1251
 
        except excClass, e:
 
1472
        except excClass as e:
1252
1473
            return e
1253
1474
        else:
1254
 
            if getattr(excClass,'__name__', None) is not None:
 
1475
            if getattr(excClass, '__name__', None) is not None:
1255
1476
                excName = excClass.__name__
1256
1477
            else:
1257
1478
                # probably a tuple
1258
1479
                excName = str(excClass)
1259
 
            raise self.failureException, "%s not raised" % excName
 
1480
            raise self.failureException("%s not raised" % excName)
1260
1481
 
1261
1482
    def assertIs(self, left, right, message=None):
1262
1483
        if not (left is right):
1305
1526
 
1306
1527
    def assertFileEqual(self, content, path):
1307
1528
        """Fail if path does not contain 'content'."""
1308
 
        self.failUnlessExists(path)
1309
 
        f = file(path, 'rb')
1310
 
        try:
 
1529
        self.assertPathExists(path)
 
1530
        
 
1531
        with open(path, 'r' + ('b' if isinstance(content, bytes) else '')) as f:
1311
1532
            s = f.read()
1312
 
        finally:
1313
 
            f.close()
1314
1533
        self.assertEqualDiff(content, s)
1315
1534
 
1316
1535
    def assertDocstring(self, expected_docstring, obj):
1321
1540
        else:
1322
1541
            self.assertEqual(expected_docstring, obj.__doc__)
1323
1542
 
1324
 
    def failUnlessExists(self, path):
 
1543
    def assertPathExists(self, path):
1325
1544
        """Fail unless path or paths, which may be abs or relative, exist."""
1326
 
        if not isinstance(path, basestring):
 
1545
        # TODO(jelmer): Clean this up for pad.lv/1696545
 
1546
        if not isinstance(path, (bytes, str, text_type)):
1327
1547
            for p in path:
1328
 
                self.failUnlessExists(p)
 
1548
                self.assertPathExists(p)
1329
1549
        else:
1330
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1550
            self.assertTrue(osutils.lexists(path),
 
1551
                path + " does not exist")
1331
1552
 
1332
 
    def failIfExists(self, path):
 
1553
    def assertPathDoesNotExist(self, path):
1333
1554
        """Fail if path or paths, which may be abs or relative, exist."""
1334
 
        if not isinstance(path, basestring):
 
1555
        if not isinstance(path, (str, text_type)):
1335
1556
            for p in path:
1336
 
                self.failIfExists(p)
 
1557
                self.assertPathDoesNotExist(p)
1337
1558
        else:
1338
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1559
            self.assertFalse(osutils.lexists(path),
 
1560
                path + " exists")
1339
1561
 
1340
1562
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1341
1563
        """A helper for callDeprecated and applyDeprecated.
1367
1589
        not other callers that go direct to the warning module.
1368
1590
 
1369
1591
        To test that a deprecated method raises an error, do something like
1370
 
        this::
 
1592
        this (remember that both assertRaises and applyDeprecated delays *args
 
1593
        and **kwargs passing)::
1371
1594
 
1372
1595
            self.assertRaises(errors.ReservedId,
1373
1596
                self.applyDeprecated,
1451
1674
        return result
1452
1675
 
1453
1676
    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
 
1677
        """Setup a in-memory target for bzr and testcase log messages"""
 
1678
        pseudo_log_file = BytesIO()
 
1679
        def _get_log_contents_for_weird_testtools_api():
 
1680
            return [pseudo_log_file.getvalue().decode(
 
1681
                "utf-8", "replace").encode("utf-8")]
 
1682
        self.addDetail("log", content.Content(content.ContentType("text",
 
1683
            "plain", {"charset": "utf8"}),
 
1684
            _get_log_contents_for_weird_testtools_api))
 
1685
        self._log_file = pseudo_log_file
 
1686
        self._log_memento = trace.push_log_file(self._log_file)
1462
1687
        self.addCleanup(self._finishLogFile)
1463
1688
 
1464
1689
    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:
 
1690
        """Flush and dereference the in-memory log for this testcase"""
 
1691
        if trace._trace_file:
1470
1692
            # 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)
 
1693
            trace._trace_file.flush()
 
1694
        trace.pop_log_file(self._log_memento)
 
1695
        # The logging module now tracks references for cleanup so discard ours
 
1696
        del self._log_memento
1475
1697
 
1476
1698
    def thisFailsStrictLockCheck(self):
1477
1699
        """It is known that this test would fail with -Dstrict_locks.
1486
1708
        """
1487
1709
        debug.debug_flags.discard('strict_locks')
1488
1710
 
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
1711
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1498
1712
        """Overrides an object attribute restoring it after the test.
1499
1713
 
 
1714
        :note: This should be used with discretion; you should think about
 
1715
        whether it's better to make the code testable without monkey-patching.
 
1716
 
1500
1717
        :param obj: The object that will be mutated.
1501
1718
 
1502
1719
        :param attr_name: The attribute name we want to preserve/override in
1506
1723
 
1507
1724
        :returns: The actual attr value.
1508
1725
        """
1509
 
        value = getattr(obj, attr_name)
1510
1726
        # The actual value is captured by the call below
1511
 
        self.addCleanup(setattr, obj, attr_name, value)
 
1727
        value = getattr(obj, attr_name, _unitialized_attr)
 
1728
        if value is _unitialized_attr:
 
1729
            # When the test completes, the attribute should not exist, but if
 
1730
            # we aren't setting a value, we don't need to do anything.
 
1731
            if new is not _unitialized_attr:
 
1732
                self.addCleanup(delattr, obj, attr_name)
 
1733
        else:
 
1734
            self.addCleanup(setattr, obj, attr_name, value)
1512
1735
        if new is not _unitialized_attr:
1513
1736
            setattr(obj, attr_name, new)
1514
1737
        return value
1515
1738
 
 
1739
    def overrideEnv(self, name, new):
 
1740
        """Set an environment variable, and reset it after the test.
 
1741
 
 
1742
        :param name: The environment variable name.
 
1743
 
 
1744
        :param new: The value to set the variable to. If None, the 
 
1745
            variable is deleted from the environment.
 
1746
 
 
1747
        :returns: The actual variable value.
 
1748
        """
 
1749
        value = osutils.set_or_unset_env(name, new)
 
1750
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1751
        return value
 
1752
 
 
1753
    def recordCalls(self, obj, attr_name):
 
1754
        """Monkeypatch in a wrapper that will record calls.
 
1755
 
 
1756
        The monkeypatch is automatically removed when the test concludes.
 
1757
 
 
1758
        :param obj: The namespace holding the reference to be replaced;
 
1759
            typically a module, class, or object.
 
1760
        :param attr_name: A string for the name of the attribute to 
 
1761
            patch.
 
1762
        :returns: A list that will be extended with one item every time the
 
1763
            function is called, with a tuple of (args, kwargs).
 
1764
        """
 
1765
        calls = []
 
1766
 
 
1767
        def decorator(*args, **kwargs):
 
1768
            calls.append((args, kwargs))
 
1769
            return orig(*args, **kwargs)
 
1770
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1771
        return calls
 
1772
 
1516
1773
    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)
 
1774
        for name, value in isolated_environ.items():
 
1775
            self.overrideEnv(name, value)
1577
1776
 
1578
1777
    def _restoreHooks(self):
1579
1778
        for klass, (name, hooks) in self._preserved_hooks.items():
1580
1779
            setattr(klass, name, hooks)
 
1780
        self._preserved_hooks.clear()
 
1781
        breezy.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1782
        self._preserved_lazy_hooks.clear()
1581
1783
 
1582
1784
    def knownFailure(self, reason):
1583
 
        """This test has failed for some known reason."""
1584
 
        raise KnownFailure(reason)
 
1785
        """Declare that this test fails for a known reason
 
1786
 
 
1787
        Tests that are known to fail should generally be using expectedFailure
 
1788
        with an appropriate reverse assertion if a change could cause the test
 
1789
        to start passing. Conversely if the test has no immediate prospect of
 
1790
        succeeding then using skip is more suitable.
 
1791
 
 
1792
        When this method is called while an exception is being handled, that
 
1793
        traceback will be used, otherwise a new exception will be thrown to
 
1794
        provide one but won't be reported.
 
1795
        """
 
1796
        self._add_reason(reason)
 
1797
        try:
 
1798
            exc_info = sys.exc_info()
 
1799
            if exc_info != (None, None, None):
 
1800
                self._report_traceback(exc_info)
 
1801
            else:
 
1802
                try:
 
1803
                    raise self.failureException(reason)
 
1804
                except self.failureException:
 
1805
                    exc_info = sys.exc_info()
 
1806
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1807
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1808
        finally:
 
1809
            del exc_info
 
1810
 
 
1811
    def _suppress_log(self):
 
1812
        """Remove the log info from details."""
 
1813
        self.discardDetail('log')
1585
1814
 
1586
1815
    def _do_skip(self, result, reason):
 
1816
        self._suppress_log()
1587
1817
        addSkip = getattr(result, 'addSkip', None)
1588
1818
        if not callable(addSkip):
1589
1819
            result.addSuccess(result)
1590
1820
        else:
1591
 
            addSkip(self, reason)
 
1821
            addSkip(self, str(reason))
1592
1822
 
1593
1823
    @staticmethod
1594
1824
    def _do_known_failure(self, result, e):
 
1825
        self._suppress_log()
1595
1826
        err = sys.exc_info()
1596
1827
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1597
1828
        if addExpectedFailure is not None:
1605
1836
            reason = 'No reason given'
1606
1837
        else:
1607
1838
            reason = e.args[0]
 
1839
        self._suppress_log ()
1608
1840
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1609
1841
        if addNotApplicable is not None:
1610
1842
            result.addNotApplicable(self, reason)
1612
1844
            self._do_skip(result, reason)
1613
1845
 
1614
1846
    @staticmethod
 
1847
    def _report_skip(self, result, err):
 
1848
        """Override the default _report_skip.
 
1849
 
 
1850
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1851
        already been formatted into the 'reason' string, and we can't pull it
 
1852
        out again.
 
1853
        """
 
1854
        self._suppress_log()
 
1855
        super(TestCase, self)._report_skip(self, result, err)
 
1856
 
 
1857
    @staticmethod
 
1858
    def _report_expected_failure(self, result, err):
 
1859
        """Strip the log.
 
1860
 
 
1861
        See _report_skip for motivation.
 
1862
        """
 
1863
        self._suppress_log()
 
1864
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1865
 
 
1866
    @staticmethod
1615
1867
    def _do_unsupported_or_skip(self, result, e):
1616
1868
        reason = e.args[0]
 
1869
        self._suppress_log()
1617
1870
        addNotSupported = getattr(result, 'addNotSupported', None)
1618
1871
        if addNotSupported is not None:
1619
1872
            result.addNotSupported(self, reason)
1623
1876
    def time(self, callable, *args, **kwargs):
1624
1877
        """Run callable and accrue the time it takes to the benchmark time.
1625
1878
 
1626
 
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
 
1879
        If lsprofiling is enabled (i.e. by --lsprof-time to brz selftest) then
1627
1880
        this will cause lsprofile statistics to be gathered and stored in
1628
1881
        self._benchcalls.
1629
1882
        """
1630
1883
        if self._benchtime is None:
1631
 
            self.addDetail('benchtime', content.Content(content.ContentType(
1632
 
                "text", "plain"), lambda:[str(self._benchtime)]))
 
1884
            self.addDetail('benchtime', content.Content(content.UTF8_TEXT,
 
1885
                lambda:[str(self._benchtime).encode('utf-8')]))
1633
1886
            self._benchtime = 0
1634
1887
        start = time.time()
1635
1888
        try:
1637
1890
                return callable(*args, **kwargs)
1638
1891
            else:
1639
1892
                # record this benchmark
1640
 
                ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
 
1893
                ret, stats = breezy.lsprof.profile(callable, *args, **kwargs)
1641
1894
                stats.sort()
1642
1895
                self._benchcalls.append(((callable, args, kwargs), stats))
1643
1896
                return ret
1645
1898
            self._benchtime += time.time() - start
1646
1899
 
1647
1900
    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."
 
1901
        trace.mutter(*args)
1728
1902
 
1729
1903
    def get_log(self):
1730
 
        """Get a unicode string containing the log from bzrlib.trace.
 
1904
        """Get a unicode string containing the log from breezy.trace.
1731
1905
 
1732
1906
        Undecodable characters are replaced.
1733
1907
        """
1744
1918
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1745
1919
            working_dir):
1746
1920
        """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)))
 
1921
        if isinstance(args, string_types):
 
1922
            args = shlex.split(args)
1751
1923
        return self._run_bzr_core(args, retcode=retcode,
1752
1924
                encoding=encoding, stdin=stdin, working_dir=working_dir,
1753
1925
                )
1759
1931
        chk_map.clear_cache()
1760
1932
        if encoding is None:
1761
1933
            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)
 
1934
 
 
1935
        self.log('run brz: %r', args)
 
1936
 
 
1937
        stdout = ui_testing.BytesIOWithEncoding()
 
1938
        stderr = ui_testing.BytesIOWithEncoding()
 
1939
        stdout.encoding = stderr.encoding = encoding
 
1940
 
1768
1941
        # FIXME: don't call into logging here
1769
 
        handler = logging.StreamHandler(stderr)
1770
 
        handler.setLevel(logging.INFO)
 
1942
        handler = trace.EncodedStreamHandler(
 
1943
            stderr, errors="replace", level=logging.INFO)
1771
1944
        logger = logging.getLogger('')
1772
1945
        logger.addHandler(handler)
 
1946
 
 
1947
        self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
 
1948
        self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
 
1949
 
1773
1950
        old_ui_factory = ui.ui_factory
1774
 
        ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
 
1951
        ui.ui_factory = ui_testing.TestUIFactory(
 
1952
            stdin=stdin,
 
1953
            stdout=self._last_cmd_stdout,
 
1954
            stderr=self._last_cmd_stderr)
1775
1955
 
1776
1956
        cwd = None
1777
1957
        if working_dir is not None:
1779
1959
            os.chdir(working_dir)
1780
1960
 
1781
1961
        try:
1782
 
            try:
1783
 
                result = self.apply_redirected(ui.ui_factory.stdin,
 
1962
            with ui.ui_factory:
 
1963
                result = self.apply_redirected(
 
1964
                    ui.ui_factory.stdin,
1784
1965
                    stdout, stderr,
1785
 
                    bzrlib.commands.run_bzr_catch_user_errors,
 
1966
                    _mod_commands.run_bzr_catch_user_errors,
1786
1967
                    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
1968
        finally:
1799
1969
            logger.removeHandler(handler)
1800
1970
            ui.ui_factory = old_ui_factory
1808
1978
        if err:
1809
1979
            self.log('errors:\n%r', err)
1810
1980
        if retcode is not None:
1811
 
            self.assertEquals(retcode, result,
 
1981
            self.assertEqual(retcode, result,
1812
1982
                              message='Unexpected return code')
1813
1983
        return result, out, err
1814
1984
 
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.
 
1985
    def run_bzr(self, args, retcode=0, stdin=None, encoding=None,
 
1986
                working_dir=None, error_regexes=[]):
 
1987
        """Invoke brz, as if it were run from the command line.
1818
1988
 
1819
 
        The argument list should not include the bzr program name - the
1820
 
        first argument is normally the bzr command.  Arguments may be
 
1989
        The argument list should not include the brz program name - the
 
1990
        first argument is normally the brz command.  Arguments may be
1821
1991
        passed in three ways:
1822
1992
 
1823
1993
        1- A list of strings, eg ["commit", "a"].  This is recommended
1827
1997
        2- A single string, eg "add a".  This is the most convenient
1828
1998
        for hardcoded commands.
1829
1999
 
1830
 
        This runs bzr through the interface that catches and reports
 
2000
        This runs brz through the interface that catches and reports
1831
2001
        errors, and with logging set to something approximating the
1832
2002
        default, so that error reporting can be checked.
1833
2003
 
1834
2004
        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
 
2005
        overall behavior of the brz application (rather than a unit test
1836
2006
        or a functional test of the library.)
1837
2007
 
1838
2008
        This sends the stdout/stderr results into the test's log,
1858
2028
        return out, err
1859
2029
 
1860
2030
    def run_bzr_error(self, error_regexes, *args, **kwargs):
1861
 
        """Run bzr, and check that stderr contains the supplied regexes
 
2031
        """Run brz, and check that stderr contains the supplied regexes
1862
2032
 
1863
2033
        :param error_regexes: Sequence of regular expressions which
1864
2034
            must each be found in the error output. The relative ordering
1865
2035
            is not enforced.
1866
 
        :param args: command-line arguments for bzr
1867
 
        :param kwargs: Keyword arguments which are interpreted by run_bzr
 
2036
        :param args: command-line arguments for brz
 
2037
        :param kwargs: Keyword arguments which are interpreted by run_brz
1868
2038
            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.
 
2039
            since in most cases this is run when you expect brz to fail.
1870
2040
 
1871
2041
        :return: (out, err) The actual output of running the command (in case
1872
2042
            you want to do more inspection)
1874
2044
        Examples of use::
1875
2045
 
1876
2046
            # Make sure that commit is failing because there is nothing to do
1877
 
            self.run_bzr_error(['no changes to commit'],
 
2047
            self.run_bzr_error([b'no changes to commit'],
1878
2048
                               ['commit', '-m', 'my commit comment'])
1879
2049
            # Make sure --strict is handling an unknown file, rather than
1880
2050
            # giving us the 'nothing to do' error
1881
2051
            self.build_tree(['unknown'])
1882
 
            self.run_bzr_error(['Commit refused because there are unknown files'],
 
2052
            self.run_bzr_error([b'Commit refused because there are unknown files'],
1883
2053
                               ['commit', --strict', '-m', 'my commit comment'])
1884
2054
        """
1885
2055
        kwargs.setdefault('retcode', 3)
1888
2058
        return out, err
1889
2059
 
1890
2060
    def run_bzr_subprocess(self, *args, **kwargs):
1891
 
        """Run bzr in a subprocess for testing.
 
2061
        """Run brz in a subprocess for testing.
1892
2062
 
1893
 
        This starts a new Python interpreter and runs bzr in there.
 
2063
        This starts a new Python interpreter and runs brz in there.
1894
2064
        This should only be used for tests that have a justifiable need for
1895
2065
        this isolation: e.g. they are testing startup time, or signal
1896
2066
        handling, or early startup code, etc.  Subprocess code can't be
1914
2084
        if len(args) == 1:
1915
2085
            if isinstance(args[0], list):
1916
2086
                args = args[0]
1917
 
            elif isinstance(args[0], basestring):
 
2087
            elif isinstance(args[0], (str, text_type)):
1918
2088
                args = list(shlex.split(args[0]))
1919
2089
        else:
1920
2090
            raise ValueError("passing varargs to run_bzr_subprocess")
1930
2100
    def start_bzr_subprocess(self, process_args, env_changes=None,
1931
2101
                             skip_if_plan_to_signal=False,
1932
2102
                             working_dir=None,
1933
 
                             allow_plugins=False):
1934
 
        """Start bzr in a subprocess for testing.
 
2103
                             allow_plugins=False, stderr=subprocess.PIPE):
 
2104
        """Start brz in a subprocess for testing.
1935
2105
 
1936
 
        This starts a new Python interpreter and runs bzr in there.
 
2106
        This starts a new Python interpreter and runs brz in there.
1937
2107
        This should only be used for tests that have a justifiable need for
1938
2108
        this isolation: e.g. they are testing startup time, or signal
1939
2109
        handling, or early startup code, etc.  Subprocess code can't be
1940
2110
        profiled or debugged so easily.
1941
2111
 
1942
 
        :param process_args: a list of arguments to pass to the bzr executable,
 
2112
        :param process_args: a list of arguments to pass to the brz executable,
1943
2113
            for example ``['--version']``.
1944
2114
        :param env_changes: A dictionary which lists changes to environment
1945
2115
            variables. A value of None will unset the env variable.
1946
2116
            The values must be strings. The change will only occur in the
1947
2117
            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.
 
2118
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2119
            doesn't support signalling subprocesses.
 
2120
        :param allow_plugins: If False (default) pass --no-plugins to brz.
 
2121
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2122
            are those valid for the stderr argument of `subprocess.Popen`.
 
2123
            Default value is ``subprocess.PIPE``.
1951
2124
 
1952
2125
        :returns: Popen object for the started process.
1953
2126
        """
1954
2127
        if skip_if_plan_to_signal:
1955
 
            if not getattr(os, 'kill', None):
1956
 
                raise TestSkipped("os.kill not available.")
 
2128
            if os.name != "posix":
 
2129
                raise TestSkipped("Sending signals not supported")
1957
2130
 
1958
2131
        if env_changes is None:
1959
2132
            env_changes = {}
 
2133
        # Because $HOME is set to a tempdir for the context of a test, modules
 
2134
        # installed in the user dir will not be found unless $PYTHONUSERBASE
 
2135
        # gets set to the computed directory of this parent process.
 
2136
        if site.USER_BASE is not None:
 
2137
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
1960
2138
        old_env = {}
1961
2139
 
1962
2140
        def cleanup_environment():
1963
 
            for env_var, value in env_changes.iteritems():
 
2141
            for env_var, value in env_changes.items():
1964
2142
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
1965
2143
 
1966
2144
        def restore_environment():
1967
 
            for env_var, value in old_env.iteritems():
 
2145
            for env_var, value in old_env.items():
1968
2146
                osutils.set_or_unset_env(env_var, value)
1969
2147
 
1970
 
        bzr_path = self.get_bzr_path()
 
2148
        bzr_path = self.get_brz_path()
1971
2149
 
1972
2150
        cwd = None
1973
2151
        if working_dir is not None:
1979
2157
            # so we will avoid using it on all platforms, just to
1980
2158
            # make sure the code path is used, and we don't break on win32
1981
2159
            cleanup_environment()
 
2160
            # Include the subprocess's log file in the test details, in case
 
2161
            # the test fails due to an error in the subprocess.
 
2162
            self._add_subprocess_log(trace._get_brz_log_filename())
1982
2163
            command = [sys.executable]
1983
2164
            # frozen executables don't need the path to bzr
1984
2165
            if getattr(sys, "frozen", None) is None:
1986
2167
            if not allow_plugins:
1987
2168
                command.append('--no-plugins')
1988
2169
            command.extend(process_args)
1989
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
2170
            process = self._popen(command, stdin=subprocess.PIPE,
 
2171
                                  stdout=subprocess.PIPE,
 
2172
                                  stderr=stderr, bufsize=0)
1990
2173
        finally:
1991
2174
            restore_environment()
1992
2175
            if cwd is not None:
1994
2177
 
1995
2178
        return process
1996
2179
 
 
2180
    def _add_subprocess_log(self, log_file_path):
 
2181
        if len(self._log_files) == 0:
 
2182
            # Register an addCleanup func.  We do this on the first call to
 
2183
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2184
            # addCleanup is registered after any cleanups for tempdirs that
 
2185
            # subclasses might create, which will probably remove the log file
 
2186
            # we want to read.
 
2187
            self.addCleanup(self._subprocess_log_cleanup)
 
2188
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2189
        # twice.
 
2190
        self._log_files.add(log_file_path)
 
2191
 
 
2192
    def _subprocess_log_cleanup(self):
 
2193
        for count, log_file_path in enumerate(self._log_files):
 
2194
            # We use buffer_now=True to avoid holding the file open beyond
 
2195
            # the life of this function, which might interfere with e.g.
 
2196
            # cleaning tempdirs on Windows.
 
2197
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2198
            #detail_content = content.content_from_file(
 
2199
            #    log_file_path, buffer_now=True)
 
2200
            with open(log_file_path, 'rb') as log_file:
 
2201
                log_file_bytes = log_file.read()
 
2202
            detail_content = content.Content(content.ContentType("text",
 
2203
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2204
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2205
                detail_content)
 
2206
 
1997
2207
    def _popen(self, *args, **kwargs):
1998
2208
        """Place a call to Popen.
1999
2209
 
2000
2210
        Allows tests to override this method to intercept the calls made to
2001
2211
        Popen for introspection.
2002
2212
        """
2003
 
        return Popen(*args, **kwargs)
 
2213
        return subprocess.Popen(*args, **kwargs)
2004
2214
 
2005
2215
    def get_source_path(self):
2006
 
        """Return the path of the directory containing bzrlib."""
2007
 
        return os.path.dirname(os.path.dirname(bzrlib.__file__))
 
2216
        """Return the path of the directory containing breezy."""
 
2217
        return os.path.dirname(os.path.dirname(breezy.__file__))
2008
2218
 
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):
 
2219
    def get_brz_path(self):
 
2220
        """Return the path of the 'brz' executable for this test suite."""
 
2221
        brz_path = os.path.join(self.get_source_path(), "brz")
 
2222
        if not os.path.isfile(brz_path):
2013
2223
            # We are probably installed. Assume sys.argv is the right file
2014
 
            bzr_path = sys.argv[0]
2015
 
        return bzr_path
 
2224
            brz_path = sys.argv[0]
 
2225
        return brz_path
2016
2226
 
2017
2227
    def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
2018
2228
                              universal_newlines=False, process_args=None):
2036
2246
        if retcode is not None and retcode != process.returncode:
2037
2247
            if process_args is None:
2038
2248
                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'
 
2249
            trace.mutter('Output of brz %r:\n%s', process_args, out)
 
2250
            trace.mutter('Error for brz %r:\n%s', process_args, err)
 
2251
            self.fail('Command brz %r failed with retcode %d != %d'
2042
2252
                      % (process_args, retcode, process.returncode))
2043
2253
        return [out, err]
2044
2254
 
2045
 
    def check_inventory_shape(self, inv, shape):
2046
 
        """Compare an inventory to a list of expected names.
 
2255
    def check_tree_shape(self, tree, shape):
 
2256
        """Compare a tree to a list of expected names.
2047
2257
 
2048
2258
        Fail if they are not precisely equal.
2049
2259
        """
2050
2260
        extras = []
2051
2261
        shape = list(shape)             # copy
2052
 
        for path, ie in inv.entries():
 
2262
        for path, ie in tree.iter_entries_by_dir():
2053
2263
            name = path.replace('\\', '/')
2054
2264
            if ie.kind == 'directory':
2055
2265
                name = name + '/'
2056
 
            if name in shape:
 
2266
            if name == "/":
 
2267
                pass # ignore root entry
 
2268
            elif name in shape:
2057
2269
                shape.remove(name)
2058
2270
            else:
2059
2271
                extras.append(name)
2070
2282
        if not callable(a_callable):
2071
2283
            raise ValueError("a_callable must be callable.")
2072
2284
        if stdin is None:
2073
 
            stdin = StringIO("")
 
2285
            stdin = BytesIO(b"")
2074
2286
        if stdout is None:
2075
2287
            if getattr(self, "_log_file", None) is not None:
2076
2288
                stdout = self._log_file
2077
2289
            else:
2078
 
                stdout = StringIO()
 
2290
                if sys.version_info[0] == 2:
 
2291
                    stdout = BytesIO()
 
2292
                else:
 
2293
                    stdout = StringIO()
2079
2294
        if stderr is None:
2080
2295
            if getattr(self, "_log_file", None is not None):
2081
2296
                stderr = self._log_file
2082
2297
            else:
2083
 
                stderr = StringIO()
 
2298
                if sys.version_info[0] == 2:
 
2299
                    stderr = BytesIO()
 
2300
                else:
 
2301
                    stderr = StringIO()
2084
2302
        real_stdin = sys.stdin
2085
2303
        real_stdout = sys.stdout
2086
2304
        real_stderr = sys.stderr
2100
2318
 
2101
2319
        Tests that expect to provoke LockContention errors should call this.
2102
2320
        """
2103
 
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2321
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2104
2322
 
2105
2323
    def make_utf8_encoded_stringio(self, encoding_type=None):
2106
 
        """Return a StringIOWrapper instance, that will encode Unicode
2107
 
        input to UTF-8.
2108
 
        """
 
2324
        """Return a wrapped BytesIO, that will encode text input to UTF-8."""
2109
2325
        if encoding_type is None:
2110
2326
            encoding_type = 'strict'
2111
 
        sio = StringIO()
 
2327
        bio = BytesIO()
2112
2328
        output_encoding = 'utf-8'
2113
 
        sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
 
2329
        sio = codecs.getwriter(output_encoding)(bio, errors=encoding_type)
2114
2330
        sio.encoding = output_encoding
2115
2331
        return sio
2116
2332
 
2117
2333
    def disable_verb(self, verb):
2118
2334
        """Disable a smart server verb for one test."""
2119
 
        from bzrlib.smart import request
 
2335
        from breezy.bzr.smart import request
2120
2336
        request_handlers = request.request_handlers
2121
2337
        orig_method = request_handlers.get(verb)
 
2338
        orig_info = request_handlers.get_info(verb)
2122
2339
        request_handlers.remove(verb)
2123
 
        self.addCleanup(request_handlers.register, verb, orig_method)
 
2340
        self.addCleanup(request_handlers.register, verb, orig_method,
 
2341
            info=orig_info)
 
2342
 
 
2343
    def __hash__(self):
 
2344
        return id(self)
2124
2345
 
2125
2346
 
2126
2347
class CapturedCall(object):
2149
2370
class TestCaseWithMemoryTransport(TestCase):
2150
2371
    """Common test class for tests that do not need disk resources.
2151
2372
 
2152
 
    Tests that need disk resources should derive from TestCaseWithTransport.
2153
 
 
2154
 
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2155
 
 
2156
 
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
2373
    Tests that need disk resources should derive from TestCaseInTempDir
 
2374
    orTestCaseWithTransport.
 
2375
 
 
2376
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all brz tests.
 
2377
 
 
2378
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2157
2379
    a directory which does not exist. This serves to help ensure test isolation
2158
 
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
2159
 
    must exist. However, TestCaseWithMemoryTransport does not offer local
2160
 
    file defaults for the transport in tests, nor does it obey the command line
 
2380
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2381
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2382
    defaults for the transport in tests, nor does it obey the command line
2161
2383
    override, so tests that accidentally write to the common directory should
2162
2384
    be rare.
2163
2385
 
2164
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
2165
 
    a .bzr directory that stops us ascending higher into the filesystem.
 
2386
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2387
        ``.bzr`` directory that stops us ascending higher into the filesystem.
2166
2388
    """
2167
2389
 
2168
2390
    TEST_ROOT = None
2178
2400
        self.transport_readonly_server = None
2179
2401
        self.__vfs_server = None
2180
2402
 
 
2403
    def setUp(self):
 
2404
        super(TestCaseWithMemoryTransport, self).setUp()
 
2405
 
 
2406
        def _add_disconnect_cleanup(transport):
 
2407
            """Schedule disconnection of given transport at test cleanup
 
2408
 
 
2409
            This needs to happen for all connected transports or leaks occur.
 
2410
 
 
2411
            Note reconnections may mean we call disconnect multiple times per
 
2412
            transport which is suboptimal but seems harmless.
 
2413
            """
 
2414
            self.addCleanup(transport.disconnect)
 
2415
 
 
2416
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
 
2417
            _add_disconnect_cleanup, None)
 
2418
 
 
2419
        self._make_test_root()
 
2420
        self.addCleanup(os.chdir, osutils.getcwd())
 
2421
        self.makeAndChdirToTestDir()
 
2422
        self.overrideEnvironmentForTesting()
 
2423
        self.__readonly_server = None
 
2424
        self.__server = None
 
2425
        self.reduceLockdirTimeout()
 
2426
        # Each test may use its own config files even if the local config files
 
2427
        # don't actually exist. They'll rightly fail if they try to create them
 
2428
        # though.
 
2429
        self.overrideAttr(config, '_shared_stores', {})
 
2430
 
2181
2431
    def get_transport(self, relpath=None):
2182
2432
        """Return a writeable transport.
2183
2433
 
2186
2436
 
2187
2437
        :param relpath: a path relative to the base url.
2188
2438
        """
2189
 
        t = get_transport(self.get_url(relpath))
 
2439
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2190
2440
        self.assertFalse(t.is_readonly())
2191
2441
        return t
2192
2442
 
2198
2448
 
2199
2449
        :param relpath: a path relative to the base url.
2200
2450
        """
2201
 
        t = get_transport(self.get_readonly_url(relpath))
 
2451
        t = _mod_transport.get_transport_from_url(
 
2452
            self.get_readonly_url(relpath))
2202
2453
        self.assertTrue(t.is_readonly())
2203
2454
        return t
2204
2455
 
2325
2576
        real branch.
2326
2577
        """
2327
2578
        root = TestCaseWithMemoryTransport.TEST_ROOT
2328
 
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2579
        try:
 
2580
            # Make sure we get a readable and accessible home for .brz.log
 
2581
            # and/or config files, and not fallback to weird defaults (see
 
2582
            # http://pad.lv/825027).
 
2583
            self.assertIs(None, os.environ.get('BRZ_HOME', None))
 
2584
            os.environ['BRZ_HOME'] = root
 
2585
            wt = controldir.ControlDir.create_standalone_workingtree(root)
 
2586
            del os.environ['BRZ_HOME']
 
2587
        except Exception as e:
 
2588
            self.fail("Fail to initialize the safety net: %r\n" % (e,))
 
2589
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2590
        # we don't need to re-open the wt to check it hasn't changed.
 
2591
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2592
            wt.control_transport.get_bytes('dirstate'))
2329
2593
 
2330
2594
    def _check_safety_net(self):
2331
2595
        """Check that the safety .bzr directory have not been touched.
2334
2598
        propagating. This method ensures than a test did not leaked.
2335
2599
        """
2336
2600
        root = TestCaseWithMemoryTransport.TEST_ROOT
2337
 
        self.permit_url(get_transport(root).base)
2338
 
        wt = workingtree.WorkingTree.open(root)
2339
 
        last_rev = wt.last_revision()
2340
 
        if last_rev != 'null:':
 
2601
        t = _mod_transport.get_transport_from_path(root)
 
2602
        self.permit_url(t.base)
 
2603
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2604
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2341
2605
            # The current test have modified the /bzr directory, we need to
2342
2606
            # recreate a new one or all the followng tests will fail.
2343
2607
            # If you need to inspect its content uncomment the following line
2375
2639
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2376
2640
        self.permit_dir(self.test_dir)
2377
2641
 
2378
 
    def make_branch(self, relpath, format=None):
 
2642
    def make_branch(self, relpath, format=None, name=None):
2379
2643
        """Create a branch on the transport at relpath."""
2380
2644
        repo = self.make_repository(relpath, format=format)
2381
 
        return repo.bzrdir.create_branch()
2382
 
 
2383
 
    def make_bzrdir(self, relpath, format=None):
 
2645
        return repo.controldir.create_branch(append_revisions_only=False, name=name)
 
2646
 
 
2647
    def get_default_format(self):
 
2648
        return 'default'
 
2649
 
 
2650
    def resolve_format(self, format):
 
2651
        """Resolve an object to a ControlDir format object.
 
2652
 
 
2653
        The initial format object can either already be
 
2654
        a ControlDirFormat, None (for the default format),
 
2655
        or a string with the name of the control dir format.
 
2656
 
 
2657
        :param format: Object to resolve
 
2658
        :return A ControlDirFormat instance
 
2659
        """
 
2660
        if format is None:
 
2661
            format = self.get_default_format()
 
2662
        if isinstance(format, str):
 
2663
            format = controldir.format_registry.make_controldir(format)
 
2664
        return format
 
2665
 
 
2666
    def make_controldir(self, relpath, format=None):
2384
2667
        try:
2385
2668
            # might be a relative or absolute path
2386
2669
            maybe_a_url = self.get_url(relpath)
2387
2670
            segments = maybe_a_url.rsplit('/', 1)
2388
 
            t = get_transport(maybe_a_url)
 
2671
            t = _mod_transport.get_transport(maybe_a_url)
2389
2672
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2390
2673
                t.ensure_base()
2391
 
            if format is None:
2392
 
                format = 'default'
2393
 
            if isinstance(format, basestring):
2394
 
                format = bzrdir.format_registry.make_bzrdir(format)
 
2674
            format = self.resolve_format(format)
2395
2675
            return format.initialize_on_transport(t)
2396
2676
        except errors.UninitializableFormat:
2397
2677
            raise TestSkipped("Format %s is not initializable." % format)
2398
2678
 
2399
 
    def make_repository(self, relpath, shared=False, format=None):
 
2679
    def make_repository(self, relpath, shared=None, format=None):
2400
2680
        """Create a repository on our default transport at relpath.
2401
2681
 
2402
2682
        Note that relpath must be a relative path, not a full url.
2405
2685
        # real format, which is incorrect.  Actually we should make sure that
2406
2686
        # RemoteBzrDir returns a RemoteRepository.
2407
2687
        # maybe  mbp 20070410
2408
 
        made_control = self.make_bzrdir(relpath, format=format)
 
2688
        made_control = self.make_controldir(relpath, format=format)
2409
2689
        return made_control.create_repository(shared=shared)
2410
2690
 
2411
 
    def make_smart_server(self, path):
 
2691
    def make_smart_server(self, path, backing_server=None):
 
2692
        if backing_server is None:
 
2693
            backing_server = self.get_server()
2412
2694
        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)
 
2695
        self.start_server(smart_server, backing_server)
 
2696
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
 
2697
                                                   ).clone(path)
2415
2698
        return remote_transport
2416
2699
 
2417
2700
    def make_branch_and_memory_tree(self, relpath, format=None):
2418
2701
        """Create a branch on the default transport and a MemoryTree for it."""
2419
2702
        b = self.make_branch(relpath, format=format)
2420
 
        return memorytree.MemoryTree.create_on_branch(b)
 
2703
        return b.create_memorytree()
2421
2704
 
2422
2705
    def make_branch_builder(self, relpath, format=None):
2423
2706
        branch = self.make_branch(relpath, format=format)
2425
2708
 
2426
2709
    def overrideEnvironmentForTesting(self):
2427
2710
        test_home_dir = self.test_home_dir
2428
 
        if isinstance(test_home_dir, unicode):
 
2711
        if not PY3 and isinstance(test_home_dir, text_type):
2429
2712
            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()
 
2713
        self.overrideEnv('HOME', test_home_dir)
 
2714
        self.overrideEnv('BRZ_HOME', test_home_dir)
 
2715
        self.overrideEnv('GNUPGHOME', os.path.join(test_home_dir, '.gnupg'))
2442
2716
 
2443
2717
    def setup_smart_server_with_call_log(self):
2444
2718
        """Sets up a smart server as the transport server with a call log."""
2445
2719
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2720
        self.hpss_connections = []
2446
2721
        self.hpss_calls = []
2447
2722
        import traceback
2448
2723
        # Skip the current stack down to the caller of
2451
2726
        def capture_hpss_call(params):
2452
2727
            self.hpss_calls.append(
2453
2728
                CapturedCall(params, prefix_length))
 
2729
        def capture_connect(transport):
 
2730
            self.hpss_connections.append(transport)
2454
2731
        client._SmartClient.hooks.install_named_hook(
2455
2732
            'call', capture_hpss_call, None)
 
2733
        _mod_transport.Transport.hooks.install_named_hook(
 
2734
            'post_connect', capture_connect, None)
2456
2735
 
2457
2736
    def reset_smart_call_log(self):
2458
2737
        self.hpss_calls = []
 
2738
        self.hpss_connections = []
2459
2739
 
2460
2740
 
2461
2741
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2480
2760
 
2481
2761
    OVERRIDE_PYTHON = 'python'
2482
2762
 
 
2763
    def setUp(self):
 
2764
        super(TestCaseInTempDir, self).setUp()
 
2765
        # Remove the protection set in isolated_environ, we have a proper
 
2766
        # access to disk resources now.
 
2767
        self.overrideEnv('BRZ_LOG', None)
 
2768
 
2483
2769
    def check_file_contents(self, filename, expect):
2484
2770
        self.log("check contents of file %s" % filename)
2485
 
        contents = file(filename, 'r').read()
 
2771
        with open(filename, 'rb') as f:
 
2772
            contents = f.read()
2486
2773
        if contents != expect:
2487
2774
            self.log("expected: %r" % expect)
2488
2775
            self.log("actually: %r" % contents)
2521
2808
        # stacking policy to honour; create a bzr dir with an unshared
2522
2809
        # repository (but not a branch - our code would be trying to escape
2523
2810
        # then!) to stop them, and permit it to be read.
2524
 
        # control = bzrdir.BzrDir.create(self.test_base_dir)
 
2811
        # control = controldir.ControlDir.create(self.test_base_dir)
2525
2812
        # control.create_repository()
2526
2813
        self.test_home_dir = self.test_base_dir + '/home'
2527
2814
        os.mkdir(self.test_home_dir)
2529
2816
        os.mkdir(self.test_dir)
2530
2817
        os.chdir(self.test_dir)
2531
2818
        # put name of test inside
2532
 
        f = file(self.test_base_dir + '/name', 'w')
2533
 
        try:
 
2819
        with open(self.test_base_dir + '/name', 'w') as f:
2534
2820
            f.write(self.id())
2535
 
        finally:
2536
 
            f.close()
2537
2821
 
2538
2822
    def deleteTestDir(self):
2539
2823
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2562
2846
                "a list or a tuple. Got %r instead" % (shape,))
2563
2847
        # It's OK to just create them using forward slashes on windows.
2564
2848
        if transport is None or transport.is_readonly():
2565
 
            transport = get_transport(".")
 
2849
            transport = _mod_transport.get_transport_from_path(".")
2566
2850
        for name in shape:
2567
 
            self.assertIsInstance(name, basestring)
 
2851
            self.assertIsInstance(name, (str, text_type))
2568
2852
            if name[-1] == '/':
2569
2853
                transport.mkdir(urlutils.escape(name[:-1]))
2570
2854
            else:
2571
2855
                if line_endings == 'binary':
2572
 
                    end = '\n'
 
2856
                    end = b'\n'
2573
2857
                elif line_endings == 'native':
2574
 
                    end = os.linesep
 
2858
                    end = os.linesep.encode('ascii')
2575
2859
                else:
2576
2860
                    raise errors.BzrError(
2577
2861
                        'Invalid line ending request %r' % line_endings)
2578
 
                content = "contents of %s%s" % (name.encode('utf-8'), end)
 
2862
                content = b"contents of %s%s" % (name.encode('utf-8'), end)
2579
2863
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2580
2864
 
2581
 
    def build_tree_contents(self, shape):
2582
 
        build_tree_contents(shape)
 
2865
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2583
2866
 
2584
2867
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2585
2868
        """Assert whether path or paths are in the WorkingTree"""
2586
2869
        if tree is None:
2587
2870
            tree = workingtree.WorkingTree.open(root_path)
2588
 
        if not isinstance(path, basestring):
 
2871
        if not isinstance(path, (str, text_type)):
2589
2872
            for p in path:
2590
2873
                self.assertInWorkingTree(p, tree=tree)
2591
2874
        else:
2592
 
            self.assertIsNot(tree.path2id(path), None,
 
2875
            self.assertTrue(tree.is_versioned(path),
2593
2876
                path+' not in working tree.')
2594
2877
 
2595
2878
    def assertNotInWorkingTree(self, path, root_path='.', tree=None):
2596
2879
        """Assert whether path or paths are not in the WorkingTree"""
2597
2880
        if tree is None:
2598
2881
            tree = workingtree.WorkingTree.open(root_path)
2599
 
        if not isinstance(path, basestring):
 
2882
        if not isinstance(path, (str, text_type)):
2600
2883
            for p in path:
2601
 
                self.assertNotInWorkingTree(p,tree=tree)
 
2884
                self.assertNotInWorkingTree(p, tree=tree)
2602
2885
        else:
2603
 
            self.assertIs(tree.path2id(path), None, path+' in working tree.')
 
2886
            self.assertFalse(tree.is_versioned(path), path+' in working tree.')
2604
2887
 
2605
2888
 
2606
2889
class TestCaseWithTransport(TestCaseInTempDir):
2617
2900
    readwrite one must both define get_url() as resolving to os.getcwd().
2618
2901
    """
2619
2902
 
 
2903
    def setUp(self):
 
2904
        super(TestCaseWithTransport, self).setUp()
 
2905
        self.__vfs_server = None
 
2906
 
2620
2907
    def get_vfs_only_server(self):
2621
2908
        """See TestCaseWithMemoryTransport.
2622
2909
 
2654
2941
        # this obviously requires a format that supports branch references
2655
2942
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2656
2943
        # RBC 20060208
 
2944
        format = self.resolve_format(format=format)
 
2945
        if not format.supports_workingtrees:
 
2946
            b = self.make_branch(relpath+'.branch', format=format)
 
2947
            return b.create_checkout(relpath, lightweight=True)
2657
2948
        b = self.make_branch(relpath, format=format)
2658
2949
        try:
2659
 
            return b.bzrdir.create_workingtree()
 
2950
            return b.controldir.create_workingtree()
2660
2951
        except errors.NotLocalUrl:
2661
2952
            # We can only make working trees locally at the moment.  If the
2662
2953
            # transport can't support them, then we keep the non-disk-backed
2664
2955
            if self.vfs_transport_factory is test_server.LocalURLServer:
2665
2956
                # the branch is colocated on disk, we cannot create a checkout.
2666
2957
                # hopefully callers will expect this.
2667
 
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
 
2958
                local_controldir = controldir.ControlDir.open(
 
2959
                    self.get_vfs_only_url(relpath))
2668
2960
                wt = local_controldir.create_workingtree()
2669
2961
                if wt.branch._format != b._format:
2670
2962
                    wt._branch = b
2700
2992
        self.assertFalse(differences.has_changed(),
2701
2993
            "Trees %r and %r are different: %r" % (left, right, differences))
2702
2994
 
2703
 
    def setUp(self):
2704
 
        super(TestCaseWithTransport, self).setUp()
2705
 
        self.__vfs_server = None
2706
 
 
2707
2995
    def disable_missing_extensions_warning(self):
2708
2996
        """Some tests expect a precise stderr content.
2709
2997
 
2710
2998
        There is no point in forcing them to duplicate the extension related
2711
2999
        warning.
2712
3000
        """
2713
 
        config.GlobalConfig().set_user_option('ignore_missing_extensions', True)
 
3001
        config.GlobalConfig().set_user_option(
 
3002
            'suppress_warnings', 'missing_extensions')
2714
3003
 
2715
3004
 
2716
3005
class ChrootedTestCase(TestCaseWithTransport):
2726
3015
    """
2727
3016
 
2728
3017
    def setUp(self):
 
3018
        from breezy.tests import http_server
2729
3019
        super(ChrootedTestCase, self).setUp()
2730
3020
        if not self.vfs_transport_factory == memory.MemoryServer:
2731
 
            self.transport_readonly_server = HttpServer
 
3021
            self.transport_readonly_server = http_server.HttpServer
2732
3022
 
2733
3023
 
2734
3024
def condition_id_re(pattern):
2737
3027
    :param pattern: A regular expression string.
2738
3028
    :return: A callable that returns True if the re matches.
2739
3029
    """
2740
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2741
 
        'test filter')
 
3030
    filter_re = re.compile(pattern, 0)
2742
3031
    def condition(test):
2743
3032
        test_id = test.id()
2744
3033
        return filter_re.search(test_id)
2934
3223
              stream=None,
2935
3224
              result_decorators=None,
2936
3225
              ):
2937
 
    """Run a test suite for bzr selftest.
 
3226
    """Run a test suite for brz selftest.
2938
3227
 
2939
3228
    :param runner_class: The class of runner to use. Must support the
2940
3229
        constructor arguments passed by run_suite which are more than standard
2958
3247
                            result_decorators=result_decorators,
2959
3248
                            )
2960
3249
    runner.stop_on_failure=stop_on_failure
 
3250
    if isinstance(suite, unittest.TestSuite):
 
3251
        # Empty out _tests list of passed suite and populate new TestSuite
 
3252
        suite._tests[:], suite = [], TestSuite(suite)
2961
3253
    # built in decorator factories:
2962
3254
    decorators = [
2963
3255
        random_order(random_seed, runner),
2981
3273
        # to take effect, though that is of marginal benefit.
2982
3274
        if verbosity >= 2:
2983
3275
            stream.write("Listing tests only ...\n")
2984
 
        for t in iter_suite_tests(suite):
2985
 
            stream.write("%s\n" % (t.id()))
 
3276
        if getattr(runner, 'list', None) is not None:
 
3277
            runner.list(suite)
 
3278
        else:
 
3279
            for t in iter_suite_tests(suite):
 
3280
                stream.write("%s\n" % (t.id()))
2986
3281
        return True
2987
3282
    result = runner.run(suite)
2988
3283
    if strict:
2996
3291
 
2997
3292
 
2998
3293
def fork_decorator(suite):
 
3294
    if getattr(os, "fork", None) is None:
 
3295
        raise errors.BzrCommandError("platform does not support fork,"
 
3296
            " try --parallel=subprocess instead.")
2999
3297
    concurrency = osutils.local_concurrency()
3000
3298
    if concurrency == 1:
3001
3299
        return suite
3032
3330
 
3033
3331
def random_order(random_seed, runner):
3034
3332
    """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.
 
3333
 
 
3334
    :param random_seed: now, a string which casts to an integer, or an integer.
3037
3335
    :param runner: A test runner with a stream attribute to report on.
3038
3336
    """
3039
3337
    if random_seed is None:
3056
3354
    return suite
3057
3355
 
3058
3356
 
3059
 
class TestDecorator(TestSuite):
 
3357
class TestDecorator(TestUtil.TestSuite):
3060
3358
    """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().
 
3359
 
 
3360
    Contains rather than flattening suite passed on construction
3065
3361
    """
3066
3362
 
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
 
3363
    def __init__(self, suite=None):
 
3364
        super(TestDecorator, self).__init__()
 
3365
        if suite is not None:
 
3366
            self.addTest(suite)
 
3367
 
 
3368
    # Don't need subclass run method with suite emptying
 
3369
    run = unittest.TestSuite.run
3089
3370
 
3090
3371
 
3091
3372
class CountingDecorator(TestDecorator):
3102
3383
    """A decorator which excludes test matching an exclude pattern."""
3103
3384
 
3104
3385
    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)
 
3386
        super(ExcludeDecorator, self).__init__(
 
3387
            exclude_tests_by_re(suite, exclude_pattern))
3117
3388
 
3118
3389
 
3119
3390
class FilterTestsDecorator(TestDecorator):
3120
3391
    """A decorator which filters tests to those matching a pattern."""
3121
3392
 
3122
3393
    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)
 
3394
        super(FilterTestsDecorator, self).__init__(
 
3395
            filter_suite_by_re(suite, pattern))
3135
3396
 
3136
3397
 
3137
3398
class RandomDecorator(TestDecorator):
3138
3399
    """A decorator which randomises the order of its tests."""
3139
3400
 
3140
3401
    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()))
 
3402
        random_seed = self.actual_seed(random_seed)
 
3403
        stream.write("Randomizing test order using seed %s\n\n" %
 
3404
            (random_seed,))
3152
3405
        # 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)
 
3406
        random.seed(random_seed)
 
3407
        super(RandomDecorator, self).__init__(randomize_suite(suite))
3158
3408
 
3159
 
    def actual_seed(self):
3160
 
        if self.random_seed == "now":
3161
 
            # We convert the seed to a long to make it reuseable across
 
3409
    @staticmethod
 
3410
    def actual_seed(seed):
 
3411
        if seed == "now":
 
3412
            # We convert the seed to an integer to make it reuseable across
3162
3413
            # invocations (because the user can reenter it).
3163
 
            self.random_seed = long(time.time())
 
3414
            return int(time.time())
3164
3415
        else:
3165
 
            # Convert the seed to a long if we can
 
3416
            # Convert the seed to an integer if we can
3166
3417
            try:
3167
 
                self.random_seed = long(self.random_seed)
3168
 
            except:
 
3418
                return int(seed)
 
3419
            except (TypeError, ValueError):
3169
3420
                pass
3170
 
        return self.random_seed
 
3421
        return seed
3171
3422
 
3172
3423
 
3173
3424
class TestFirstDecorator(TestDecorator):
3174
3425
    """A decorator which moves named tests to the front."""
3175
3426
 
3176
3427
    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)
 
3428
        super(TestFirstDecorator, self).__init__()
 
3429
        self.addTests(split_suite_by_re(suite, pattern))
3189
3430
 
3190
3431
 
3191
3432
def partition_tests(suite, count):
3192
3433
    """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
 
3434
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3435
    # splits up blocks of related tests that might run faster if they shared
 
3436
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3437
    # just one partition.  So the slowest partition shouldn't be much slower
 
3438
    # than the fastest.
 
3439
    partitions = [list() for i in range(count)]
 
3440
    tests = iter_suite_tests(suite)
 
3441
    for partition, test in zip(itertools.cycle(partitions), tests):
 
3442
        partition.append(test)
 
3443
    return partitions
3202
3444
 
3203
3445
 
3204
3446
def workaround_zealous_crypto_random():
3222
3464
    """
3223
3465
    concurrency = osutils.local_concurrency()
3224
3466
    result = []
3225
 
    from subunit import TestProtocolClient, ProtocolTestCase
 
3467
    from subunit import ProtocolTestCase
3226
3468
    from subunit.test_results import AutoTimingTestResultDecorator
3227
3469
    class TestInOtherProcess(ProtocolTestCase):
3228
3470
        # Should be in subunit, I think. RBC.
3234
3476
            try:
3235
3477
                ProtocolTestCase.run(self, result)
3236
3478
            finally:
3237
 
                os.waitpid(self.pid, 0)
 
3479
                pid, status = os.waitpid(self.pid, 0)
 
3480
            # GZ 2011-10-18: If status is nonzero, should report to the result
 
3481
            #                that something went wrong.
3238
3482
 
3239
3483
    test_blocks = partition_tests(suite, concurrency)
 
3484
    # Clear the tests from the original suite so it doesn't keep them alive
 
3485
    suite._tests[:] = []
3240
3486
    for process_tests in test_blocks:
3241
 
        process_suite = TestSuite()
3242
 
        process_suite.addTests(process_tests)
 
3487
        process_suite = TestUtil.TestSuite(process_tests)
 
3488
        # Also clear each split list so new suite has only reference
 
3489
        process_tests[:] = []
3243
3490
        c2pread, c2pwrite = os.pipe()
3244
3491
        pid = os.fork()
3245
3492
        if pid == 0:
3246
 
            workaround_zealous_crypto_random()
3247
3493
            try:
 
3494
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3495
                workaround_zealous_crypto_random()
 
3496
                try:
 
3497
                    import coverage
 
3498
                except ImportError:
 
3499
                    pass
 
3500
                else:
 
3501
                    coverage.process_startup()
3248
3502
                os.close(c2pread)
3249
3503
                # Leave stderr and stdout open so we can see test noise
3250
3504
                # Close stdin so that the child goes away if it decides to
3251
3505
                # read from stdin (otherwise its a roulette to see what
3252
3506
                # child actually gets keystrokes for pdb etc).
3253
3507
                sys.stdin.close()
3254
 
                sys.stdin = None
3255
 
                stream = os.fdopen(c2pwrite, 'wb', 1)
3256
3508
                subunit_result = AutoTimingTestResultDecorator(
3257
 
                    TestProtocolClient(stream))
 
3509
                    SubUnitBzrProtocolClientv1(stream))
3258
3510
                process_suite.run(subunit_result)
3259
 
            finally:
3260
 
                os._exit(0)
 
3511
            except:
 
3512
                # Try and report traceback on stream, but exit with error even
 
3513
                # if stream couldn't be created or something else goes wrong.
 
3514
                # The traceback is formatted to a string and written in one go
 
3515
                # to avoid interleaving lines from multiple failing children.
 
3516
                try:
 
3517
                    stream.write(traceback.format_exc())
 
3518
                finally:
 
3519
                    os._exit(1)
 
3520
            os._exit(0)
3261
3521
        else:
3262
3522
            os.close(c2pwrite)
3263
3523
            stream = os.fdopen(c2pread, 'rb', 1)
3292
3552
    test_blocks = partition_tests(suite, concurrency)
3293
3553
    for process_tests in test_blocks:
3294
3554
        # ugly; currently reimplement rather than reuses TestCase methods.
3295
 
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
3555
        bzr_path = os.path.dirname(os.path.dirname(breezy.__file__))+'/bzr'
3296
3556
        if not os.path.isfile(bzr_path):
3297
3557
            # We are probably installed. Assume sys.argv is the right file
3298
3558
            bzr_path = sys.argv[0]
3310
3570
                '--subunit']
3311
3571
            if '--no-plugins' in sys.argv:
3312
3572
                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)
 
3573
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3574
            # noise on stderr it can interrupt the subunit protocol.
 
3575
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3576
                                      stdout=subprocess.PIPE,
 
3577
                                      stderr=subprocess.PIPE,
 
3578
                                      bufsize=1)
3317
3579
            test = TestInSubprocess(process, test_list_file_name)
3318
3580
            result.append(test)
3319
3581
        except:
3322
3584
    return result
3323
3585
 
3324
3586
 
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):
 
3587
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3358
3588
    """Generate profiling data for all activity between start and success.
3359
3589
    
3360
3590
    The profile data is appended to the test's _benchcalls attribute and can
3367
3597
    """
3368
3598
 
3369
3599
    def startTest(self, test):
3370
 
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3600
        self.profiler = breezy.lsprof.BzrProfiler()
 
3601
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3602
        # unavoidably fail.
 
3603
        breezy.lsprof.BzrProfiler.profiler_block = 0
3371
3604
        self.profiler.start()
3372
 
        ForwardingResult.startTest(self, test)
 
3605
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3373
3606
 
3374
3607
    def addSuccess(self, test):
3375
3608
        stats = self.profiler.stop()
3379
3612
            test._benchcalls = []
3380
3613
            calls = test._benchcalls
3381
3614
        calls.append(((test.id(), "", ""), stats))
3382
 
        ForwardingResult.addSuccess(self, test)
 
3615
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3383
3616
 
3384
3617
    def stopTest(self, test):
3385
 
        ForwardingResult.stopTest(self, test)
 
3618
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3386
3619
        self.profiler = None
3387
3620
 
3388
3621
 
3389
 
# Controlled by "bzr selftest -E=..." option
 
3622
# Controlled by "brz selftest -E=..." option
3390
3623
# Currently supported:
3391
3624
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
3392
3625
#                           preserves any flags supplied at the command line.
3394
3627
#                           rather than failing tests. And no longer raise
3395
3628
#                           LockContention when fctnl locks are not being used
3396
3629
#                           with proper exclusion rules.
 
3630
#   -Ethreads               Will display thread ident at creation/join time to
 
3631
#                           help track thread leaks
 
3632
#   -Euncollected_cases     Display the identity of any test cases that weren't
 
3633
#                           deallocated after being completed.
 
3634
#   -Econfig_stats          Will collect statistics using addDetail
3397
3635
selftest_debug_flags = set()
3398
3636
 
3399
3637
 
3419
3657
    # XXX: Very ugly way to do this...
3420
3658
    # Disable warning about old formats because we don't want it to disturb
3421
3659
    # any blackbox tests.
3422
 
    from bzrlib import repository
 
3660
    from breezy import repository
3423
3661
    repository._deprecation_warning_done = True
3424
3662
 
3425
3663
    global default_transport
3439
3677
        if starting_with:
3440
3678
            starting_with = [test_prefix_alias_registry.resolve_alias(start)
3441
3679
                             for start in starting_with]
 
3680
            # Always consider 'unittest' an interesting name so that failed
 
3681
            # suites wrapped as test cases appear in the output.
 
3682
            starting_with.append('unittest')
3442
3683
        if test_suite_factory is None:
3443
3684
            # Reduce loading time by loading modules based on the starting_with
3444
3685
            # patterns.
3482
3723
    test_list = []
3483
3724
    try:
3484
3725
        ftest = open(file_name, 'rt')
3485
 
    except IOError, e:
 
3726
    except IOError as e:
3486
3727
        if e.errno != errno.ENOENT:
3487
3728
            raise
3488
3729
        else:
3503
3744
 
3504
3745
    :return: (absents, duplicates) absents is a list containing the test found
3505
3746
        in id_list but not in test_suite, duplicates is a list containing the
3506
 
        test found multiple times in test_suite.
 
3747
        tests found multiple times in test_suite.
3507
3748
 
3508
3749
    When using a prefined test id list, it may occurs that some tests do not
3509
3750
    exist anymore or that some tests use the same id. This function warns the
3567
3808
 
3568
3809
    def refers_to(self, module_name):
3569
3810
        """Is there tests for the module or one of its sub modules."""
3570
 
        return self.modules.has_key(module_name)
 
3811
        return module_name in self.modules
3571
3812
 
3572
3813
    def includes(self, test_id):
3573
 
        return self.tests.has_key(test_id)
 
3814
        return test_id in self.tests
3574
3815
 
3575
3816
 
3576
3817
class TestPrefixAliasRegistry(registry.Registry):
3593
3834
                key, obj, help=help, info=info, override_existing=False)
3594
3835
        except KeyError:
3595
3836
            actual = self.get(key)
3596
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3597
 
                 % (key, actual, obj))
 
3837
            trace.note(
 
3838
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3839
                % (key, actual, obj))
3598
3840
 
3599
3841
    def resolve_alias(self, id_start):
3600
3842
        """Replace the alias by the prefix in the given string.
3615
3857
 
3616
3858
 
3617
3859
# 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')
 
3860
# appear prefixed ('breezy.' is "replaced" by 'breezy.').
 
3861
test_prefix_alias_registry.register('breezy', 'breezy')
3620
3862
 
3621
3863
# 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')
 
3864
test_prefix_alias_registry.register('bd', 'breezy.doc')
 
3865
test_prefix_alias_registry.register('bu', 'breezy.utils')
 
3866
test_prefix_alias_registry.register('bt', 'breezy.tests')
 
3867
test_prefix_alias_registry.register('bb', 'breezy.tests.blackbox')
 
3868
test_prefix_alias_registry.register('bp', 'breezy.plugins')
3627
3869
 
3628
3870
 
3629
3871
def _test_suite_testmod_names():
3630
3872
    """Return the standard list of test module names to test."""
3631
3873
    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',
 
3874
        'breezy.doc',
 
3875
        'breezy.tests.blackbox',
 
3876
        'breezy.tests.commands',
 
3877
        'breezy.tests.per_branch',
 
3878
        'breezy.tests.per_bzrdir',
 
3879
        'breezy.tests.per_controldir',
 
3880
        'breezy.tests.per_controldir_colo',
 
3881
        'breezy.tests.per_foreign_vcs',
 
3882
        'breezy.tests.per_interrepository',
 
3883
        'breezy.tests.per_intertree',
 
3884
        'breezy.tests.per_inventory',
 
3885
        'breezy.tests.per_interbranch',
 
3886
        'breezy.tests.per_lock',
 
3887
        'breezy.tests.per_merger',
 
3888
        'breezy.tests.per_transport',
 
3889
        'breezy.tests.per_tree',
 
3890
        'breezy.tests.per_pack_repository',
 
3891
        'breezy.tests.per_repository',
 
3892
        'breezy.tests.per_repository_chk',
 
3893
        'breezy.tests.per_repository_reference',
 
3894
        'breezy.tests.per_repository_vf',
 
3895
        'breezy.tests.per_uifactory',
 
3896
        'breezy.tests.per_versionedfile',
 
3897
        'breezy.tests.per_workingtree',
 
3898
        'breezy.tests.test__annotator',
 
3899
        'breezy.tests.test__bencode',
 
3900
        'breezy.tests.test__btree_serializer',
 
3901
        'breezy.tests.test__chk_map',
 
3902
        'breezy.tests.test__dirstate_helpers',
 
3903
        'breezy.tests.test__groupcompress',
 
3904
        'breezy.tests.test__known_graph',
 
3905
        'breezy.tests.test__rio',
 
3906
        'breezy.tests.test__simple_set',
 
3907
        'breezy.tests.test__static_tuple',
 
3908
        'breezy.tests.test__walkdirs_win32',
 
3909
        'breezy.tests.test_ancestry',
 
3910
        'breezy.tests.test_annotate',
 
3911
        'breezy.tests.test_atomicfile',
 
3912
        'breezy.tests.test_bad_files',
 
3913
        'breezy.tests.test_bisect',
 
3914
        'breezy.tests.test_bisect_multi',
 
3915
        'breezy.tests.test_branch',
 
3916
        'breezy.tests.test_branchbuilder',
 
3917
        'breezy.tests.test_btree_index',
 
3918
        'breezy.tests.test_bugtracker',
 
3919
        'breezy.tests.test_bundle',
 
3920
        'breezy.tests.test_bzrdir',
 
3921
        'breezy.tests.test__chunks_to_lines',
 
3922
        'breezy.tests.test_cache_utf8',
 
3923
        'breezy.tests.test_chk_map',
 
3924
        'breezy.tests.test_chk_serializer',
 
3925
        'breezy.tests.test_chunk_writer',
 
3926
        'breezy.tests.test_clean_tree',
 
3927
        'breezy.tests.test_cleanup',
 
3928
        'breezy.tests.test_cmdline',
 
3929
        'breezy.tests.test_commands',
 
3930
        'breezy.tests.test_commit',
 
3931
        'breezy.tests.test_commit_merge',
 
3932
        'breezy.tests.test_config',
 
3933
        'breezy.tests.test_conflicts',
 
3934
        'breezy.tests.test_controldir',
 
3935
        'breezy.tests.test_counted_lock',
 
3936
        'breezy.tests.test_crash',
 
3937
        'breezy.tests.test_decorators',
 
3938
        'breezy.tests.test_delta',
 
3939
        'breezy.tests.test_debug',
 
3940
        'breezy.tests.test_diff',
 
3941
        'breezy.tests.test_directory_service',
 
3942
        'breezy.tests.test_dirstate',
 
3943
        'breezy.tests.test_email_message',
 
3944
        'breezy.tests.test_eol_filters',
 
3945
        'breezy.tests.test_errors',
 
3946
        'breezy.tests.test_estimate_compressed_size',
 
3947
        'breezy.tests.test_export',
 
3948
        'breezy.tests.test_export_pot',
 
3949
        'breezy.tests.test_extract',
 
3950
        'breezy.tests.test_features',
 
3951
        'breezy.tests.test_fetch',
 
3952
        'breezy.tests.test_fetch_ghosts',
 
3953
        'breezy.tests.test_fixtures',
 
3954
        'breezy.tests.test_fifo_cache',
 
3955
        'breezy.tests.test_filters',
 
3956
        'breezy.tests.test_filter_tree',
 
3957
        'breezy.tests.test_foreign',
 
3958
        'breezy.tests.test_generate_docs',
 
3959
        'breezy.tests.test_generate_ids',
 
3960
        'breezy.tests.test_globbing',
 
3961
        'breezy.tests.test_gpg',
 
3962
        'breezy.tests.test_graph',
 
3963
        'breezy.tests.test_groupcompress',
 
3964
        'breezy.tests.test_hashcache',
 
3965
        'breezy.tests.test_help',
 
3966
        'breezy.tests.test_hooks',
 
3967
        'breezy.tests.test_http',
 
3968
        'breezy.tests.test_http_response',
 
3969
        'breezy.tests.test_https_ca_bundle',
 
3970
        'breezy.tests.test_https_urllib',
 
3971
        'breezy.tests.test_i18n',
 
3972
        'breezy.tests.test_identitymap',
 
3973
        'breezy.tests.test_ignores',
 
3974
        'breezy.tests.test_index',
 
3975
        'breezy.tests.test_import_tariff',
 
3976
        'breezy.tests.test_info',
 
3977
        'breezy.tests.test_inv',
 
3978
        'breezy.tests.test_inventory_delta',
 
3979
        'breezy.tests.test_knit',
 
3980
        'breezy.tests.test_lazy_import',
 
3981
        'breezy.tests.test_lazy_regex',
 
3982
        'breezy.tests.test_library_state',
 
3983
        'breezy.tests.test_lock',
 
3984
        'breezy.tests.test_lockable_files',
 
3985
        'breezy.tests.test_lockdir',
 
3986
        'breezy.tests.test_log',
 
3987
        'breezy.tests.test_lru_cache',
 
3988
        'breezy.tests.test_lsprof',
 
3989
        'breezy.tests.test_mail_client',
 
3990
        'breezy.tests.test_matchers',
 
3991
        'breezy.tests.test_memorytree',
 
3992
        'breezy.tests.test_merge',
 
3993
        'breezy.tests.test_merge3',
 
3994
        'breezy.tests.test_merge_core',
 
3995
        'breezy.tests.test_merge_directive',
 
3996
        'breezy.tests.test_mergetools',
 
3997
        'breezy.tests.test_missing',
 
3998
        'breezy.tests.test_msgeditor',
 
3999
        'breezy.tests.test_multiparent',
 
4000
        'breezy.tests.test_mutabletree',
 
4001
        'breezy.tests.test_nonascii',
 
4002
        'breezy.tests.test_options',
 
4003
        'breezy.tests.test_osutils',
 
4004
        'breezy.tests.test_osutils_encodings',
 
4005
        'breezy.tests.test_pack',
 
4006
        'breezy.tests.test_patch',
 
4007
        'breezy.tests.test_patches',
 
4008
        'breezy.tests.test_permissions',
 
4009
        'breezy.tests.test_plugins',
 
4010
        'breezy.tests.test_progress',
 
4011
        'breezy.tests.test_pyutils',
 
4012
        'breezy.tests.test_read_bundle',
 
4013
        'breezy.tests.test_reconcile',
 
4014
        'breezy.tests.test_reconfigure',
 
4015
        'breezy.tests.test_registry',
 
4016
        'breezy.tests.test_remote',
 
4017
        'breezy.tests.test_rename_map',
 
4018
        'breezy.tests.test_repository',
 
4019
        'breezy.tests.test_revert',
 
4020
        'breezy.tests.test_revision',
 
4021
        'breezy.tests.test_revisionspec',
 
4022
        'breezy.tests.test_revisiontree',
 
4023
        'breezy.tests.test_rio',
 
4024
        'breezy.tests.test_rules',
 
4025
        'breezy.tests.test_url_policy_open',
 
4026
        'breezy.tests.test_sampler',
 
4027
        'breezy.tests.test_scenarios',
 
4028
        'breezy.tests.test_script',
 
4029
        'breezy.tests.test_selftest',
 
4030
        'breezy.tests.test_serializer',
 
4031
        'breezy.tests.test_setup',
 
4032
        'breezy.tests.test_sftp_transport',
 
4033
        'breezy.tests.test_shelf',
 
4034
        'breezy.tests.test_shelf_ui',
 
4035
        'breezy.tests.test_smart',
 
4036
        'breezy.tests.test_smart_add',
 
4037
        'breezy.tests.test_smart_request',
 
4038
        'breezy.tests.test_smart_signals',
 
4039
        'breezy.tests.test_smart_transport',
 
4040
        'breezy.tests.test_smtp_connection',
 
4041
        'breezy.tests.test_source',
 
4042
        'breezy.tests.test_ssh_transport',
 
4043
        'breezy.tests.test_status',
 
4044
        'breezy.tests.test_strace',
 
4045
        'breezy.tests.test_subsume',
 
4046
        'breezy.tests.test_switch',
 
4047
        'breezy.tests.test_symbol_versioning',
 
4048
        'breezy.tests.test_tag',
 
4049
        'breezy.tests.test_test_server',
 
4050
        'breezy.tests.test_testament',
 
4051
        'breezy.tests.test_textfile',
 
4052
        'breezy.tests.test_textmerge',
 
4053
        'breezy.tests.test_cethread',
 
4054
        'breezy.tests.test_timestamp',
 
4055
        'breezy.tests.test_trace',
 
4056
        'breezy.tests.test_transactions',
 
4057
        'breezy.tests.test_transform',
 
4058
        'breezy.tests.test_transport',
 
4059
        'breezy.tests.test_transport_log',
 
4060
        'breezy.tests.test_tree',
 
4061
        'breezy.tests.test_treebuilder',
 
4062
        'breezy.tests.test_treeshape',
 
4063
        'breezy.tests.test_tsort',
 
4064
        'breezy.tests.test_tuned_gzip',
 
4065
        'breezy.tests.test_ui',
 
4066
        'breezy.tests.test_uncommit',
 
4067
        'breezy.tests.test_upgrade',
 
4068
        'breezy.tests.test_upgrade_stacked',
 
4069
        'breezy.tests.test_upstream_import',
 
4070
        'breezy.tests.test_urlutils',
 
4071
        'breezy.tests.test_utextwrap',
 
4072
        'breezy.tests.test_version',
 
4073
        'breezy.tests.test_version_info',
 
4074
        'breezy.tests.test_versionedfile',
 
4075
        'breezy.tests.test_vf_search',
 
4076
        'breezy.tests.test_views',
 
4077
        'breezy.tests.test_weave',
 
4078
        'breezy.tests.test_whitebox',
 
4079
        'breezy.tests.test_win32utils',
 
4080
        'breezy.tests.test_workingtree',
 
4081
        'breezy.tests.test_workingtree_4',
 
4082
        'breezy.tests.test_wsgi',
 
4083
        'breezy.tests.test_xml',
3819
4084
        ]
3820
4085
 
3821
4086
 
3825
4090
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
3826
4091
        return []
3827
4092
    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',
 
4093
        'breezy',
 
4094
        'breezy.branchbuilder',
 
4095
        'breezy.bzr.inventory',
 
4096
        'breezy.decorators',
 
4097
        'breezy.iterablefile',
 
4098
        'breezy.lockdir',
 
4099
        'breezy.merge3',
 
4100
        'breezy.option',
 
4101
        'breezy.pyutils',
 
4102
        'breezy.symbol_versioning',
 
4103
        'breezy.tests',
 
4104
        'breezy.tests.fixtures',
 
4105
        'breezy.timestamp',
 
4106
        'breezy.transport.http',
 
4107
        'breezy.version_info_formats.format_custom',
3841
4108
        ]
3842
4109
 
3843
4110
 
3844
4111
def test_suite(keep_only=None, starting_with=None):
3845
 
    """Build and return TestSuite for the whole of bzrlib.
 
4112
    """Build and return TestSuite for the whole of breezy.
3846
4113
 
3847
4114
    :param keep_only: A list of test ids limiting the suite returned.
3848
4115
 
3895
4162
        try:
3896
4163
            # note that this really does mean "report only" -- doctest
3897
4164
            # 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)
 
4165
            doc_suite = IsolatedDocTestSuite(
 
4166
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4167
        except ValueError as e:
 
4168
            print('**failed to get doctest for: %s\n%s' % (mod, e))
3902
4169
            raise
3903
4170
        if len(doc_suite._tests) == 0:
3904
4171
            raise errors.BzrError("no doctests found in %s" % (mod,))
3905
4172
        suite.addTest(doc_suite)
3906
4173
 
3907
4174
    default_encoding = sys.getdefaultencoding()
3908
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4175
    for name, plugin in _mod_plugin.plugins().items():
3909
4176
        if not interesting_module(plugin.module.__name__):
3910
4177
            continue
3911
4178
        plugin_suite = plugin.test_suite()
3917
4184
        if plugin_suite is not None:
3918
4185
            suite.addTest(plugin_suite)
3919
4186
        if default_encoding != sys.getdefaultencoding():
3920
 
            bzrlib.trace.warning(
 
4187
            trace.warning(
3921
4188
                'Plugin "%s" tried to reset default encoding to: %s', name,
3922
4189
                sys.getdefaultencoding())
3923
4190
            reload(sys)
3938
4205
            # Some tests mentioned in the list are not in the test suite. The
3939
4206
            # list may be out of date, report to the tester.
3940
4207
            for id in not_found:
3941
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4208
                trace.warning('"%s" not found in the test suite', id)
3942
4209
        for id in duplicates:
3943
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4210
            trace.warning('"%s" is used as an id by several tests', id)
3944
4211
 
3945
4212
    return suite
3946
4213
 
3947
4214
 
3948
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4215
def multiply_scenarios(*scenarios):
 
4216
    """Multiply two or more iterables of scenarios.
 
4217
 
 
4218
    It is safe to pass scenario generators or iterators.
 
4219
 
 
4220
    :returns: A list of compound scenarios: the cross-product of all
 
4221
        scenarios, with the names concatenated and the parameters
 
4222
        merged together.
 
4223
    """
 
4224
    return functools.reduce(_multiply_two_scenarios, map(list, scenarios))
 
4225
 
 
4226
 
 
4227
def _multiply_two_scenarios(scenarios_left, scenarios_right):
3949
4228
    """Multiply two sets of scenarios.
3950
4229
 
3951
4230
    :returns: the cartesian product of the two sets of scenarios, that is
3954
4233
    """
3955
4234
    return [
3956
4235
        ('%s,%s' % (left_name, right_name),
3957
 
         dict(left_dict.items() + right_dict.items()))
 
4236
         dict(left_dict, **right_dict))
3958
4237
        for left_name, left_dict in scenarios_left
3959
4238
        for right_name, right_dict in scenarios_right]
3960
4239
 
3977
4256
    the scenario name at the end of its id(), and updating the test object's
3978
4257
    __dict__ with the scenario_param_dict.
3979
4258
 
3980
 
    >>> import bzrlib.tests.test_sampler
 
4259
    >>> import breezy.tests.test_sampler
3981
4260
    >>> r = multiply_tests(
3982
 
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
 
4261
    ...     breezy.tests.test_sampler.DemoTest('test_nothing'),
3983
4262
    ...     [('one', dict(param=1)),
3984
4263
    ...      ('two', dict(param=2))],
3985
 
    ...     TestSuite())
 
4264
    ...     TestUtil.TestSuite())
3986
4265
    >>> tests = list(iter_suite_tests(r))
3987
4266
    >>> len(tests)
3988
4267
    2
3989
4268
    >>> tests[0].id()
3990
 
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
 
4269
    'breezy.tests.test_sampler.DemoTest.test_nothing(one)'
3991
4270
    >>> tests[0].param
3992
4271
    1
3993
4272
    >>> tests[1].param
4015
4294
    """Copy test and apply scenario to it.
4016
4295
 
4017
4296
    :param test: A test to adapt.
4018
 
    :param scenario: A tuple describing the scenarion.
 
4297
    :param scenario: A tuple describing the scenario.
4019
4298
        The first element of the tuple is the new test id.
4020
4299
        The second element is a dict containing attributes to set on the
4021
4300
        test.
4035
4314
    :param new_id: The id to assign to it.
4036
4315
    :return: The new test.
4037
4316
    """
4038
 
    new_test = copy(test)
 
4317
    new_test = copy.copy(test)
4039
4318
    new_test.id = lambda: new_id
 
4319
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4320
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4321
    # read the test output for parameterized tests, because tracebacks will be
 
4322
    # associated with irrelevant tests.
 
4323
    try:
 
4324
        details = new_test._TestCase__details
 
4325
    except AttributeError:
 
4326
        # must be a different version of testtools than expected.  Do nothing.
 
4327
        pass
 
4328
    else:
 
4329
        # Reset the '__details' dict.
 
4330
        new_test._TestCase__details = {}
4040
4331
    return new_test
4041
4332
 
4042
4333
 
4047
4338
    This is meant to be used inside a modules 'load_tests()' function. It will
4048
4339
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
4049
4340
    against both implementations. Setting 'test.module' to the appropriate
4050
 
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
 
4341
    module. See breezy.tests.test__chk_map.load_tests as an example.
4051
4342
 
4052
4343
    :param standard_tests: A test suite to permute
4053
4344
    :param loader: A TestLoader
4054
4345
    :param py_module_name: The python path to a python module that can always
4055
4346
        be loaded, and will be considered the 'python' implementation. (eg
4056
 
        'bzrlib._chk_map_py')
 
4347
        'breezy._chk_map_py')
4057
4348
    :param ext_module_name: The python path to an extension module. If the
4058
4349
        module cannot be loaded, a single test will be added, which notes that
4059
4350
        the module is not available. If it can be loaded, all standard_tests
4063
4354
        the module is available.
4064
4355
    """
4065
4356
 
4066
 
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4357
    from .features import ModuleAvailableFeature
 
4358
    py_module = pyutils.get_named_object(py_module_name)
4067
4359
    scenarios = [
4068
4360
        ('python', {'module': py_module}),
4069
4361
    ]
4088
4380
    # except on win32, where rmtree(str) will fail
4089
4381
    # since it doesn't have the property of byte-stream paths
4090
4382
    # (they are either ascii or mbcs)
4091
 
    if sys.platform == 'win32':
 
4383
    if sys.platform == 'win32' and isinstance(dirname, bytes):
4092
4384
        # make sure we are using the unicode win32 api
4093
 
        dirname = unicode(dirname)
 
4385
        dirname = dirname.decode('mbcs')
4094
4386
    else:
4095
4387
        dirname = dirname.encode(sys.getfilesystemencoding())
4096
4388
    try:
4097
4389
        osutils.rmtree(dirname)
4098
 
    except OSError, e:
 
4390
    except OSError as e:
4099
4391
        # We don't want to fail here because some useful display will be lost
4100
4392
        # otherwise. Polluting the tmp dir is bad, but not giving all the
4101
4393
        # possible info to the test runner is even worse.
4102
4394
        if test_id != None:
4103
4395
            ui.ui_factory.clear_term()
4104
4396
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4397
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4398
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4399
                                    ).encode('ascii', 'replace')
4105
4400
        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')
 
4401
                         % (os.path.basename(dirname), printable_e))
4266
4402
 
4267
4403
 
4268
4404
def probe_unicode_in_user_encoding():
4289
4425
    Return None if all non-ascii characters is valid
4290
4426
    for given encoding.
4291
4427
    """
4292
 
    for i in xrange(128, 256):
 
4428
    for i in range(128, 256):
4293
4429
        char = chr(i)
4294
4430
        try:
4295
4431
            char.decode(encoding)
4298
4434
    return None
4299
4435
 
4300
4436
 
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
4437
# Only define SubUnitBzrRunner if subunit is available.
4454
4438
try:
4455
4439
    from subunit import TestProtocolClient
4456
4440
    from subunit.test_results import AutoTimingTestResultDecorator
4457
 
    class SubUnitBzrRunner(TextTestRunner):
 
4441
 
 
4442
    class SubUnitBzrProtocolClientv1(TestProtocolClient):
 
4443
 
 
4444
        def stopTest(self, test):
 
4445
            super(SubUnitBzrProtocolClientv1, self).stopTest(test)
 
4446
            _clear__type_equality_funcs(test)
 
4447
 
 
4448
        def addSuccess(self, test, details=None):
 
4449
            # The subunit client always includes the details in the subunit
 
4450
            # stream, but we don't want to include it in ours.
 
4451
            if details is not None and 'log' in details:
 
4452
                del details['log']
 
4453
            return super(SubUnitBzrProtocolClientv1, self).addSuccess(
 
4454
                test, details)
 
4455
 
 
4456
    class SubUnitBzrRunnerv1(TextTestRunner):
 
4457
 
4458
4458
        def run(self, test):
4459
4459
            result = AutoTimingTestResultDecorator(
4460
 
                TestProtocolClient(self.stream))
 
4460
                SubUnitBzrProtocolClientv1(self.stream))
4461
4461
            test.run(result)
4462
4462
            return result
4463
4463
except ImportError:
4464
4464
    pass
4465
4465
 
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()
 
4466
 
 
4467
try:
 
4468
    from subunit.run import SubunitTestRunner
 
4469
 
 
4470
    class SubUnitBzrRunnerv2(TextTestRunner, SubunitTestRunner):
 
4471
 
 
4472
        def __init__(self, stream=sys.stderr, descriptions=0, verbosity=1,
 
4473
                     bench_history=None, strict=False, result_decorators=None):
 
4474
            TextTestRunner.__init__(
 
4475
                    self, stream=stream,
 
4476
                    descriptions=descriptions, verbosity=verbosity,
 
4477
                    bench_history=bench_history, strict=strict,
 
4478
                    result_decorators=result_decorators)
 
4479
            SubunitTestRunner.__init__(self, verbosity=verbosity,
 
4480
                                       stream=stream)
 
4481
 
 
4482
        run = SubunitTestRunner.run
 
4483
except ImportError:
 
4484
    pass