/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/tests/__init__.py

  • Committer: Jelmer Vernooij
  • Date: 2017-07-20 00:00:04 UTC
  • mfrom: (6690.5.2 bundle-guess)
  • Revision ID: jelmer@jelmer.uk-20170720000004-wlknc5gthdk3tokn
Merge lp:~jelmer/brz/bundle-guess.

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