/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/tests/__init__.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-10 00:21:41 UTC
  • mto: This revision was merged to the branch mainline in revision 6675.
  • Revision ID: jelmer@jelmer.uk-20170610002141-m1z5k7fs8laesa65
Fix import.

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