~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

(jelmer) Use the absolute_import feature everywhere in bzrlib,
 and add a source test to make sure it's used everywhere. (Jelmer Vernooij)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2011 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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
"""Testing framework extensions"""
17
18
 
18
 
# TODO: Perhaps there should be an API to find out if bzr running under the
19
 
# test suite -- some plugins might want to avoid making intrusive changes if
20
 
# this is the case.  However, we want behaviour under to test to diverge as
21
 
# little as possible, so this should be used rarely if it's added at all.
22
 
# (Suggestion from j-a-meinel, 2005-11-24)
 
19
from __future__ import absolute_import
23
20
 
24
21
# NOTE: Some classes in here use camelCaseNaming() rather than
25
22
# underscore_naming().  That's for consistency with unittest; it's not the
28
25
 
29
26
import atexit
30
27
import codecs
31
 
from copy import copy
 
28
import copy
32
29
from cStringIO import StringIO
33
30
import difflib
34
31
import doctest
35
32
import errno
 
33
import itertools
36
34
import logging
37
 
import math
38
35
import os
39
 
from pprint import pformat
 
36
import platform
 
37
import pprint
40
38
import random
41
39
import re
42
40
import shlex
 
41
import site
43
42
import stat
44
 
from subprocess import Popen, PIPE, STDOUT
 
43
import subprocess
45
44
import sys
46
45
import tempfile
47
46
import threading
48
47
import time
 
48
import traceback
49
49
import unittest
50
50
import warnings
51
51
 
 
52
import testtools
 
53
# nb: check this before importing anything else from within it
 
54
_testtools_version = getattr(testtools, '__version__', ())
 
55
if _testtools_version < (0, 9, 5):
 
56
    raise ImportError("need at least testtools 0.9.5: %s is %r"
 
57
        % (testtools.__file__, _testtools_version))
 
58
from testtools import content
52
59
 
 
60
import bzrlib
53
61
from bzrlib import (
54
62
    branchbuilder,
55
63
    bzrdir,
56
64
    chk_map,
 
65
    commands as _mod_commands,
57
66
    config,
 
67
    i18n,
58
68
    debug,
59
69
    errors,
60
70
    hooks,
61
71
    lock as _mod_lock,
 
72
    lockdir,
62
73
    memorytree,
63
74
    osutils,
64
 
    progress,
 
75
    plugin as _mod_plugin,
 
76
    pyutils,
65
77
    ui,
66
78
    urlutils,
67
79
    registry,
 
80
    symbol_versioning,
 
81
    trace,
 
82
    transport as _mod_transport,
68
83
    workingtree,
69
84
    )
70
 
import bzrlib.branch
71
 
import bzrlib.commands
72
 
import bzrlib.timestamp
73
 
import bzrlib.export
74
 
import bzrlib.inventory
75
 
import bzrlib.iterablefile
76
 
import bzrlib.lockdir
77
85
try:
78
86
    import bzrlib.lsprof
79
87
except ImportError:
80
88
    # lsprof not available
81
89
    pass
82
 
from bzrlib.merge import merge_inner
83
 
import bzrlib.merge3
84
 
import bzrlib.plugin
85
 
from bzrlib.smart import client, request, server
86
 
import bzrlib.store
87
 
from bzrlib import symbol_versioning
 
90
from bzrlib.smart import client, request
 
91
from bzrlib.transport import (
 
92
    memory,
 
93
    pathfilter,
 
94
    )
88
95
from bzrlib.symbol_versioning import (
89
 
    DEPRECATED_PARAMETER,
90
96
    deprecated_function,
91
 
    deprecated_method,
92
 
    deprecated_passed,
93
 
    )
94
 
import bzrlib.trace
95
 
from bzrlib.transport import get_transport, pathfilter
96
 
import bzrlib.transport
97
 
from bzrlib.transport.local import LocalURLServer
98
 
from bzrlib.transport.memory import MemoryServer
99
 
from bzrlib.transport.readonly import ReadonlyServer
100
 
from bzrlib.trace import mutter, note
101
 
from bzrlib.tests import TestUtil
102
 
from bzrlib.tests.http_server import HttpServer
103
 
from bzrlib.tests.TestUtil import (
104
 
                          TestSuite,
105
 
                          TestLoader,
106
 
                          )
107
 
from bzrlib.tests.treeshape import build_tree_contents
 
97
    deprecated_in,
 
98
    )
 
99
from bzrlib.tests import (
 
100
    fixtures,
 
101
    test_server,
 
102
    TestUtil,
 
103
    treeshape,
 
104
    )
108
105
from bzrlib.ui import NullProgressView
109
106
from bzrlib.ui.text import TextUIFactory
110
 
import bzrlib.version_info_formats.format_custom
111
 
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
 
107
from bzrlib.tests.features import _CompatabilityThunkFeature
112
108
 
113
109
# Mark this python module as being part of the implementation
114
110
# of unittest: this gives us better tracebacks where the last
115
111
# shown frame is the test code, not our assertXYZ.
116
112
__unittest = 1
117
113
 
118
 
default_transport = LocalURLServer
 
114
default_transport = test_server.LocalURLServer
 
115
 
 
116
 
 
117
_unitialized_attr = object()
 
118
"""A sentinel needed to act as a default value in a method signature."""
 
119
 
119
120
 
120
121
# Subunit result codes, defined here to prevent a hard dependency on subunit.
121
122
SUBUNIT_SEEK_SET = 0
122
123
SUBUNIT_SEEK_CUR = 1
123
124
 
124
 
 
125
 
class ExtendedTestResult(unittest._TextTestResult):
 
125
# These are intentionally brought into this namespace. That way plugins, etc
 
126
# can just "from bzrlib.tests import TestCase, TestLoader, etc"
 
127
TestSuite = TestUtil.TestSuite
 
128
TestLoader = TestUtil.TestLoader
 
129
 
 
130
# Tests should run in a clean and clearly defined environment. The goal is to
 
131
# keep them isolated from the running environment as mush as possible. The test
 
132
# framework ensures the variables defined below are set (or deleted if the
 
133
# value is None) before a test is run and reset to their original value after
 
134
# the test is run. Generally if some code depends on an environment variable,
 
135
# the tests should start without this variable in the environment. There are a
 
136
# few exceptions but you shouldn't violate this rule lightly.
 
137
isolated_environ = {
 
138
    'BZR_HOME': None,
 
139
    'HOME': None,
 
140
    # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
 
141
    # tests do check our impls match APPDATA
 
142
    'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
143
    'VISUAL': None,
 
144
    'EDITOR': None,
 
145
    'BZR_EMAIL': None,
 
146
    'BZREMAIL': None, # may still be present in the environment
 
147
    'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
 
148
    'BZR_PROGRESS_BAR': None,
 
149
    # This should trap leaks to ~/.bzr.log. This occurs when tests use TestCase
 
150
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
 
151
    # TestCase should not use disk resources, BZR_LOG is one.
 
152
    'BZR_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
153
    'BZR_PLUGIN_PATH': None,
 
154
    'BZR_DISABLE_PLUGINS': None,
 
155
    'BZR_PLUGINS_AT': None,
 
156
    'BZR_CONCURRENCY': None,
 
157
    # Make sure that any text ui tests are consistent regardless of
 
158
    # the environment the test case is run in; you may want tests that
 
159
    # test other combinations.  'dumb' is a reasonable guess for tests
 
160
    # going to a pipe or a StringIO.
 
161
    'TERM': 'dumb',
 
162
    'LINES': '25',
 
163
    'COLUMNS': '80',
 
164
    'BZR_COLUMNS': '80',
 
165
    # Disable SSH Agent
 
166
    'SSH_AUTH_SOCK': None,
 
167
    # Proxies
 
168
    'http_proxy': None,
 
169
    'HTTP_PROXY': None,
 
170
    'https_proxy': None,
 
171
    'HTTPS_PROXY': None,
 
172
    'no_proxy': None,
 
173
    'NO_PROXY': None,
 
174
    'all_proxy': None,
 
175
    'ALL_PROXY': None,
 
176
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
177
    # least. If you do (care), please update this comment
 
178
    # -- vila 20080401
 
179
    'ftp_proxy': None,
 
180
    'FTP_PROXY': None,
 
181
    'BZR_REMOTE_PATH': None,
 
182
    # Generally speaking, we don't want apport reporting on crashes in
 
183
    # the test envirnoment unless we're specifically testing apport,
 
184
    # so that it doesn't leak into the real system environment.  We
 
185
    # use an env var so it propagates to subprocesses.
 
186
    'APPORT_DISABLE': '1',
 
187
    }
 
188
 
 
189
 
 
190
def override_os_environ(test, env=None):
 
191
    """Modify os.environ keeping a copy.
 
192
    
 
193
    :param test: A test instance
 
194
 
 
195
    :param env: A dict containing variable definitions to be installed
 
196
    """
 
197
    if env is None:
 
198
        env = isolated_environ
 
199
    test._original_os_environ = dict([(var, value)
 
200
                                      for var, value in os.environ.iteritems()])
 
201
    for var, value in env.iteritems():
 
202
        osutils.set_or_unset_env(var, value)
 
203
        if var not in test._original_os_environ:
 
204
            # The var is new, add it with a value of None, so
 
205
            # restore_os_environ will delete it
 
206
            test._original_os_environ[var] = None
 
207
 
 
208
 
 
209
def restore_os_environ(test):
 
210
    """Restore os.environ to its original state.
 
211
 
 
212
    :param test: A test instance previously passed to override_os_environ.
 
213
    """
 
214
    for var, value in test._original_os_environ.iteritems():
 
215
        # Restore the original value (or delete it if the value has been set to
 
216
        # None in override_os_environ).
 
217
        osutils.set_or_unset_env(var, value)
 
218
 
 
219
 
 
220
def _clear__type_equality_funcs(test):
 
221
    """Cleanup bound methods stored on TestCase instances
 
222
 
 
223
    Clear the dict breaking a few (mostly) harmless cycles in the affected
 
224
    unittests released with Python 2.6 and initial Python 2.7 versions.
 
225
 
 
226
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
 
227
    shipped in Oneiric, an object with no clear method was used, hence the
 
228
    extra complications, see bug 809048 for details.
 
229
    """
 
230
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
231
    if type_equality_funcs is not None:
 
232
        tef_clear = getattr(type_equality_funcs, "clear", None)
 
233
        if tef_clear is None:
 
234
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
 
235
            if tef_instance_dict is not None:
 
236
                tef_clear = tef_instance_dict.clear
 
237
        if tef_clear is not None:
 
238
            tef_clear()
 
239
 
 
240
 
 
241
class ExtendedTestResult(testtools.TextTestResult):
126
242
    """Accepts, reports and accumulates the results of running tests.
127
243
 
128
244
    Compared to the unittest version this class adds support for
149
265
        :param bench_history: Optionally, a writable file object to accumulate
150
266
            benchmark results.
151
267
        """
152
 
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
268
        testtools.TextTestResult.__init__(self, stream)
153
269
        if bench_history is not None:
154
270
            from bzrlib.version import _get_bzr_source_tree
155
271
            src_tree = _get_bzr_source_tree()
176
292
        self.count = 0
177
293
        self._overall_start_time = time.time()
178
294
        self._strict = strict
 
295
        self._first_thread_leaker_id = None
 
296
        self._tests_leaking_threads_count = 0
 
297
        self._traceback_from_test = None
179
298
 
180
299
    def stopTestRun(self):
181
300
        run = self.testsRun
182
301
        actionTaken = "Ran"
183
302
        stopTime = time.time()
184
303
        timeTaken = stopTime - self.startTime
185
 
        self.printErrors()
186
 
        self.stream.writeln(self.separator2)
187
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
304
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
 
305
        #                the parent class method is similar have to duplicate
 
306
        self._show_list('ERROR', self.errors)
 
307
        self._show_list('FAIL', self.failures)
 
308
        self.stream.write(self.sep2)
 
309
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
188
310
                            run, run != 1 and "s" or "", timeTaken))
189
 
        self.stream.writeln()
190
311
        if not self.wasSuccessful():
191
312
            self.stream.write("FAILED (")
192
313
            failed, errored = map(len, (self.failures, self.errors))
199
320
                if failed or errored: self.stream.write(", ")
200
321
                self.stream.write("known_failure_count=%d" %
201
322
                    self.known_failure_count)
202
 
            self.stream.writeln(")")
 
323
            self.stream.write(")\n")
203
324
        else:
204
325
            if self.known_failure_count:
205
 
                self.stream.writeln("OK (known_failures=%d)" %
 
326
                self.stream.write("OK (known_failures=%d)\n" %
206
327
                    self.known_failure_count)
207
328
            else:
208
 
                self.stream.writeln("OK")
 
329
                self.stream.write("OK\n")
209
330
        if self.skip_count > 0:
210
331
            skipped = self.skip_count
211
 
            self.stream.writeln('%d test%s skipped' %
 
332
            self.stream.write('%d test%s skipped\n' %
212
333
                                (skipped, skipped != 1 and "s" or ""))
213
334
        if self.unsupported:
214
335
            for feature, count in sorted(self.unsupported.items()):
215
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
336
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
216
337
                    (feature, count))
217
338
        if self._strict:
218
339
            ok = self.wasStrictlySuccessful()
219
340
        else:
220
341
            ok = self.wasSuccessful()
221
 
        if TestCase._first_thread_leaker_id:
 
342
        if self._first_thread_leaker_id:
222
343
            self.stream.write(
223
344
                '%s is leaking threads among %d leaking tests.\n' % (
224
 
                TestCase._first_thread_leaker_id,
225
 
                TestCase._leaking_threads_tests))
 
345
                self._first_thread_leaker_id,
 
346
                self._tests_leaking_threads_count))
226
347
            # We don't report the main thread as an active one.
227
348
            self.stream.write(
228
349
                '%d non-main threads were left active in the end.\n'
229
 
                % (TestCase._active_threads - 1))
230
 
 
231
 
    def _extractBenchmarkTime(self, testCase):
 
350
                % (len(self._active_threads) - 1))
 
351
 
 
352
    def getDescription(self, test):
 
353
        return test.id()
 
354
 
 
355
    def _extractBenchmarkTime(self, testCase, details=None):
232
356
        """Add a benchmark time for the current test case."""
 
357
        if details and 'benchtime' in details:
 
358
            return float(''.join(details['benchtime'].iter_bytes()))
233
359
        return getattr(testCase, "_benchtime", None)
234
360
 
235
361
    def _elapsedTestTimeString(self):
236
362
        """Return a time string for the overall time the current test has taken."""
237
 
        return self._formatTime(time.time() - self._start_time)
 
363
        return self._formatTime(self._delta_to_float(
 
364
            self._now() - self._start_datetime))
238
365
 
239
366
    def _testTimeString(self, testCase):
240
367
        benchmark_time = self._extractBenchmarkTime(testCase)
251
378
 
252
379
    def _shortened_test_description(self, test):
253
380
        what = test.id()
254
 
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
381
        what = re.sub(r'^bzrlib\.tests\.', '', what)
255
382
        return what
256
383
 
 
384
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
385
    #                multiple times in a row, because the handler is added for
 
386
    #                each test but the container list is shared between cases.
 
387
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
388
    def _record_traceback_from_test(self, exc_info):
 
389
        """Store the traceback from passed exc_info tuple till"""
 
390
        self._traceback_from_test = exc_info[2]
 
391
 
257
392
    def startTest(self, test):
258
 
        unittest.TestResult.startTest(self, test)
 
393
        super(ExtendedTestResult, self).startTest(test)
259
394
        if self.count == 0:
260
395
            self.startTests()
 
396
        self.count += 1
261
397
        self.report_test_start(test)
262
398
        test.number = self.count
263
399
        self._recordTestStartTime()
 
400
        # Make testtools cases give us the real traceback on failure
 
401
        addOnException = getattr(test, "addOnException", None)
 
402
        if addOnException is not None:
 
403
            addOnException(self._record_traceback_from_test)
 
404
        # Only check for thread leaks on bzrlib derived test cases
 
405
        if isinstance(test, TestCase):
 
406
            test.addCleanup(self._check_leaked_threads, test)
 
407
 
 
408
    def stopTest(self, test):
 
409
        super(ExtendedTestResult, self).stopTest(test)
 
410
        # Manually break cycles, means touching various private things but hey
 
411
        getDetails = getattr(test, "getDetails", None)
 
412
        if getDetails is not None:
 
413
            getDetails().clear()
 
414
        _clear__type_equality_funcs(test)
 
415
        self._traceback_from_test = None
264
416
 
265
417
    def startTests(self):
266
 
        import platform
267
 
        if getattr(sys, 'frozen', None) is None:
268
 
            bzr_path = osutils.realpath(sys.argv[0])
269
 
        else:
270
 
            bzr_path = sys.executable
271
 
        self.stream.write(
272
 
            'testing: %s\n' % (bzr_path,))
273
 
        self.stream.write(
274
 
            '   %s\n' % (
275
 
                    bzrlib.__path__[0],))
276
 
        self.stream.write(
277
 
            '   bzr-%s python-%s %s\n' % (
278
 
                    bzrlib.version_string,
279
 
                    bzrlib._format_version_tuple(sys.version_info),
280
 
                    platform.platform(aliased=1),
281
 
                    ))
282
 
        self.stream.write('\n')
 
418
        self.report_tests_starting()
 
419
        self._active_threads = threading.enumerate()
 
420
 
 
421
    def _check_leaked_threads(self, test):
 
422
        """See if any threads have leaked since last call
 
423
 
 
424
        A sample of live threads is stored in the _active_threads attribute,
 
425
        when this method runs it compares the current live threads and any not
 
426
        in the previous sample are treated as having leaked.
 
427
        """
 
428
        now_active_threads = set(threading.enumerate())
 
429
        threads_leaked = now_active_threads.difference(self._active_threads)
 
430
        if threads_leaked:
 
431
            self._report_thread_leak(test, threads_leaked, now_active_threads)
 
432
            self._tests_leaking_threads_count += 1
 
433
            if self._first_thread_leaker_id is None:
 
434
                self._first_thread_leaker_id = test.id()
 
435
            self._active_threads = now_active_threads
283
436
 
284
437
    def _recordTestStartTime(self):
285
438
        """Record that a test has started."""
286
 
        self._start_time = time.time()
287
 
 
288
 
    def _cleanupLogFile(self, test):
289
 
        # We can only do this if we have one of our TestCases, not if
290
 
        # we have a doctest.
291
 
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
292
 
        if setKeepLogfile is not None:
293
 
            setKeepLogfile()
 
439
        self._start_datetime = self._now()
294
440
 
295
441
    def addError(self, test, err):
296
442
        """Tell result that test finished with an error.
298
444
        Called from the TestCase run() method when the test
299
445
        fails with an unexpected error.
300
446
        """
301
 
        self._post_mortem()
302
 
        unittest.TestResult.addError(self, test, err)
 
447
        self._post_mortem(self._traceback_from_test)
 
448
        super(ExtendedTestResult, self).addError(test, err)
303
449
        self.error_count += 1
304
450
        self.report_error(test, err)
305
451
        if self.stop_early:
306
452
            self.stop()
307
 
        self._cleanupLogFile(test)
308
453
 
309
454
    def addFailure(self, test, err):
310
455
        """Tell result that test failed.
312
457
        Called from the TestCase run() method when the test
313
458
        fails because e.g. an assert() method failed.
314
459
        """
315
 
        self._post_mortem()
316
 
        unittest.TestResult.addFailure(self, test, err)
 
460
        self._post_mortem(self._traceback_from_test)
 
461
        super(ExtendedTestResult, self).addFailure(test, err)
317
462
        self.failure_count += 1
318
463
        self.report_failure(test, err)
319
464
        if self.stop_early:
320
465
            self.stop()
321
 
        self._cleanupLogFile(test)
322
466
 
323
 
    def addSuccess(self, test):
 
467
    def addSuccess(self, test, details=None):
324
468
        """Tell result that test completed successfully.
325
469
 
326
470
        Called from the TestCase run()
327
471
        """
328
472
        if self._bench_history is not None:
329
 
            benchmark_time = self._extractBenchmarkTime(test)
 
473
            benchmark_time = self._extractBenchmarkTime(test, details)
330
474
            if benchmark_time is not None:
331
475
                self._bench_history.write("%s %s\n" % (
332
476
                    self._formatTime(benchmark_time),
333
477
                    test.id()))
334
478
        self.report_success(test)
335
 
        self._cleanupLogFile(test)
336
 
        unittest.TestResult.addSuccess(self, test)
 
479
        super(ExtendedTestResult, self).addSuccess(test)
337
480
        test._log_contents = ''
338
481
 
339
482
    def addExpectedFailure(self, test, err):
340
483
        self.known_failure_count += 1
341
484
        self.report_known_failure(test, err)
342
485
 
 
486
    def addUnexpectedSuccess(self, test, details=None):
 
487
        """Tell result the test unexpectedly passed, counting as a failure
 
488
 
 
489
        When the minimum version of testtools required becomes 0.9.8 this
 
490
        can be updated to use the new handling there.
 
491
        """
 
492
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
493
        self.failure_count += 1
 
494
        self.report_unexpected_success(test,
 
495
            "".join(details["reason"].iter_text()))
 
496
        if self.stop_early:
 
497
            self.stop()
 
498
 
343
499
    def addNotSupported(self, test, feature):
344
500
        """The test will not be run because of a missing feature.
345
501
        """
362
518
        self.not_applicable_count += 1
363
519
        self.report_not_applicable(test, reason)
364
520
 
365
 
    def printErrorList(self, flavour, errors):
366
 
        for test, err in errors:
367
 
            self.stream.writeln(self.separator1)
368
 
            self.stream.write("%s: " % flavour)
369
 
            self.stream.writeln(self.getDescription(test))
370
 
            if getattr(test, '_get_log', None) is not None:
371
 
                log_contents = test._get_log()
372
 
                if log_contents:
373
 
                    self.stream.write('\n')
374
 
                    self.stream.write(
375
 
                            ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
376
 
                    self.stream.write('\n')
377
 
                    self.stream.write(log_contents)
378
 
                    self.stream.write('\n')
379
 
                    self.stream.write(
380
 
                            ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
381
 
                    self.stream.write('\n')
382
 
            self.stream.writeln(self.separator2)
383
 
            self.stream.writeln("%s" % err)
 
521
    def _count_stored_tests(self):
 
522
        """Count of tests instances kept alive due to not succeeding"""
 
523
        return self.error_count + self.failure_count + self.known_failure_count
384
524
 
385
 
    def _post_mortem(self):
 
525
    def _post_mortem(self, tb=None):
386
526
        """Start a PDB post mortem session."""
387
527
        if os.environ.get('BZR_TEST_PDB', None):
388
 
            import pdb;pdb.post_mortem()
 
528
            import pdb
 
529
            pdb.post_mortem(tb)
389
530
 
390
531
    def progress(self, offset, whence):
391
532
        """The test is adjusting the count of tests to run."""
396
537
        else:
397
538
            raise errors.BzrError("Unknown whence %r" % whence)
398
539
 
399
 
    def report_cleaning_up(self):
400
 
        pass
 
540
    def report_tests_starting(self):
 
541
        """Display information before the test run begins"""
 
542
        if getattr(sys, 'frozen', None) is None:
 
543
            bzr_path = osutils.realpath(sys.argv[0])
 
544
        else:
 
545
            bzr_path = sys.executable
 
546
        self.stream.write(
 
547
            'bzr selftest: %s\n' % (bzr_path,))
 
548
        self.stream.write(
 
549
            '   %s\n' % (
 
550
                    bzrlib.__path__[0],))
 
551
        self.stream.write(
 
552
            '   bzr-%s python-%s %s\n' % (
 
553
                    bzrlib.version_string,
 
554
                    bzrlib._format_version_tuple(sys.version_info),
 
555
                    platform.platform(aliased=1),
 
556
                    ))
 
557
        self.stream.write('\n')
 
558
 
 
559
    def report_test_start(self, test):
 
560
        """Display information on the test just about to be run"""
 
561
 
 
562
    def _report_thread_leak(self, test, leaked_threads, active_threads):
 
563
        """Display information on a test that leaked one or more threads"""
 
564
        # GZ 2010-09-09: A leak summary reported separately from the general
 
565
        #                thread debugging would be nice. Tests under subunit
 
566
        #                need something not using stream, perhaps adding a
 
567
        #                testtools details object would be fitting.
 
568
        if 'threads' in selftest_debug_flags:
 
569
            self.stream.write('%s is leaking, active is now %d\n' %
 
570
                (test.id(), len(active_threads)))
401
571
 
402
572
    def startTestRun(self):
403
573
        self.startTime = time.time()
440
610
        self.pb.finished()
441
611
        super(TextTestResult, self).stopTestRun()
442
612
 
443
 
    def startTestRun(self):
444
 
        super(TextTestResult, self).startTestRun()
 
613
    def report_tests_starting(self):
 
614
        super(TextTestResult, self).report_tests_starting()
445
615
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
446
616
 
447
 
    def printErrors(self):
448
 
        # clear the pb to make room for the error listing
449
 
        self.pb.clear()
450
 
        super(TextTestResult, self).printErrors()
451
 
 
452
617
    def _progress_prefix_text(self):
453
618
        # the longer this text, the less space we have to show the test
454
619
        # name...
467
632
            a += '%dm%ds' % (runtime / 60, runtime % 60)
468
633
        else:
469
634
            a += '%ds' % runtime
470
 
        if self.error_count:
471
 
            a += ', %d err' % self.error_count
472
 
        if self.failure_count:
473
 
            a += ', %d fail' % self.failure_count
 
635
        total_fail_count = self.error_count + self.failure_count
 
636
        if total_fail_count:
 
637
            a += ', %d failed' % total_fail_count
474
638
        # if self.unsupported:
475
639
        #     a += ', %d missing' % len(self.unsupported)
476
640
        a += ']'
477
641
        return a
478
642
 
479
643
    def report_test_start(self, test):
480
 
        self.count += 1
481
644
        self.pb.update(
482
645
                self._progress_prefix_text()
483
646
                + ' '
487
650
        return self._shortened_test_description(test)
488
651
 
489
652
    def report_error(self, test, err):
490
 
        ui.ui_factory.note('ERROR: %s\n    %s\n' % (
 
653
        self.stream.write('ERROR: %s\n    %s\n' % (
491
654
            self._test_description(test),
492
655
            err[1],
493
656
            ))
494
657
 
495
658
    def report_failure(self, test, err):
496
 
        ui.ui_factory.note('FAIL: %s\n    %s\n' % (
 
659
        self.stream.write('FAIL: %s\n    %s\n' % (
497
660
            self._test_description(test),
498
661
            err[1],
499
662
            ))
500
663
 
501
664
    def report_known_failure(self, test, err):
502
 
        ui.ui_factory.note('XFAIL: %s\n%s\n' % (
503
 
            self._test_description(test), err[1]))
 
665
        pass
 
666
 
 
667
    def report_unexpected_success(self, test, reason):
 
668
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
 
669
            self._test_description(test),
 
670
            "Unexpected success. Should have failed",
 
671
            reason,
 
672
            ))
504
673
 
505
674
    def report_skip(self, test, reason):
506
675
        pass
511
680
    def report_unsupported(self, test, feature):
512
681
        """test cannot be run because feature is missing."""
513
682
 
514
 
    def report_cleaning_up(self):
515
 
        self.pb.update('Cleaning up')
516
 
 
517
683
 
518
684
class VerboseTestResult(ExtendedTestResult):
519
685
    """Produce long output, with one line per test run plus times"""
526
692
            result = a_string
527
693
        return result.ljust(final_width)
528
694
 
529
 
    def startTestRun(self):
530
 
        super(VerboseTestResult, self).startTestRun()
 
695
    def report_tests_starting(self):
531
696
        self.stream.write('running %d tests...\n' % self.num_tests)
 
697
        super(VerboseTestResult, self).report_tests_starting()
532
698
 
533
699
    def report_test_start(self, test):
534
 
        self.count += 1
535
700
        name = self._shortened_test_description(test)
536
 
        # width needs space for 6 char status, plus 1 for slash, plus an
537
 
        # 11-char time string, plus a trailing blank
538
 
        # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
539
 
        self.stream.write(self._ellipsize_to_right(name,
540
 
                          osutils.terminal_width()-18))
 
701
        width = osutils.terminal_width()
 
702
        if width is not None:
 
703
            # width needs space for 6 char status, plus 1 for slash, plus an
 
704
            # 11-char time string, plus a trailing blank
 
705
            # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on
 
706
            # space
 
707
            self.stream.write(self._ellipsize_to_right(name, width-18))
 
708
        else:
 
709
            self.stream.write(name)
541
710
        self.stream.flush()
542
711
 
543
712
    def _error_summary(self, err):
545
714
        return '%s%s' % (indent, err[1])
546
715
 
547
716
    def report_error(self, test, err):
548
 
        self.stream.writeln('ERROR %s\n%s'
 
717
        self.stream.write('ERROR %s\n%s\n'
549
718
                % (self._testTimeString(test),
550
719
                   self._error_summary(err)))
551
720
 
552
721
    def report_failure(self, test, err):
553
 
        self.stream.writeln(' FAIL %s\n%s'
 
722
        self.stream.write(' FAIL %s\n%s\n'
554
723
                % (self._testTimeString(test),
555
724
                   self._error_summary(err)))
556
725
 
557
726
    def report_known_failure(self, test, err):
558
 
        self.stream.writeln('XFAIL %s\n%s'
 
727
        self.stream.write('XFAIL %s\n%s\n'
559
728
                % (self._testTimeString(test),
560
729
                   self._error_summary(err)))
561
730
 
 
731
    def report_unexpected_success(self, test, reason):
 
732
        self.stream.write(' FAIL %s\n%s: %s\n'
 
733
                % (self._testTimeString(test),
 
734
                   "Unexpected success. Should have failed",
 
735
                   reason))
 
736
 
562
737
    def report_success(self, test):
563
 
        self.stream.writeln('   OK %s' % self._testTimeString(test))
 
738
        self.stream.write('   OK %s\n' % self._testTimeString(test))
564
739
        for bench_called, stats in getattr(test, '_benchcalls', []):
565
 
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
740
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
566
741
            stats.pprint(file=self.stream)
567
742
        # flush the stream so that we get smooth output. This verbose mode is
568
743
        # used to show the output in PQM.
569
744
        self.stream.flush()
570
745
 
571
746
    def report_skip(self, test, reason):
572
 
        self.stream.writeln(' SKIP %s\n%s'
 
747
        self.stream.write(' SKIP %s\n%s\n'
573
748
                % (self._testTimeString(test), reason))
574
749
 
575
750
    def report_not_applicable(self, test, reason):
576
 
        self.stream.writeln('  N/A %s\n    %s'
 
751
        self.stream.write('  N/A %s\n    %s\n'
577
752
                % (self._testTimeString(test), reason))
578
753
 
579
754
    def report_unsupported(self, test, feature):
580
755
        """test cannot be run because feature is missing."""
581
 
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
 
756
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
582
757
                %(self._testTimeString(test), feature))
583
758
 
584
759
 
600
775
            applied left to right - the first element in the list is the 
601
776
            innermost decorator.
602
777
        """
603
 
        self.stream = unittest._WritelnDecorator(stream)
 
778
        # stream may know claim to know to write unicode strings, but in older
 
779
        # pythons this goes sufficiently wrong that it is a bad idea. (
 
780
        # specifically a built in file with encoding 'UTF-8' will still try
 
781
        # to encode using ascii.
 
782
        new_encoding = osutils.get_terminal_encoding()
 
783
        codec = codecs.lookup(new_encoding)
 
784
        if type(codec) is tuple:
 
785
            # Python 2.4
 
786
            encode = codec[0]
 
787
        else:
 
788
            encode = codec.encode
 
789
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
790
        #                so should swap to the plain codecs.StreamWriter
 
791
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
792
            "backslashreplace")
 
793
        stream.encoding = new_encoding
 
794
        self.stream = stream
604
795
        self.descriptions = descriptions
605
796
        self.verbosity = verbosity
606
797
        self._bench_history = bench_history
625
816
        for decorator in self._result_decorators:
626
817
            result = decorator(result)
627
818
            result.stop_early = self.stop_on_failure
628
 
        try:
629
 
            import testtools
630
 
        except ImportError:
631
 
            pass
632
 
        else:
633
 
            if isinstance(test, testtools.ConcurrentTestSuite):
634
 
                # We need to catch bzr specific behaviors
635
 
                result = BZRTransformingResult(result)
636
819
        result.startTestRun()
637
820
        try:
638
821
            test.run(result)
656
839
                        % (type(suite), suite))
657
840
 
658
841
 
659
 
class TestSkipped(Exception):
660
 
    """Indicates that a test was intentionally skipped, rather than failing."""
 
842
TestSkipped = testtools.testcase.TestSkipped
661
843
 
662
844
 
663
845
class TestNotApplicable(TestSkipped):
669
851
    """
670
852
 
671
853
 
672
 
class KnownFailure(AssertionError):
673
 
    """Indicates that a test failed in a precisely expected manner.
674
 
 
675
 
    Such failures dont block the whole test suite from passing because they are
676
 
    indicators of partially completed code or of future work. We have an
677
 
    explicit error for them so that we can ensure that they are always visible:
678
 
    KnownFailures are always shown in the output of bzr selftest.
679
 
    """
 
854
# traceback._some_str fails to format exceptions that have the default
 
855
# __str__ which does an implicit ascii conversion. However, repr() on those
 
856
# objects works, for all that its not quite what the doctor may have ordered.
 
857
def _clever_some_str(value):
 
858
    try:
 
859
        return str(value)
 
860
    except:
 
861
        try:
 
862
            return repr(value).replace('\\n', '\n')
 
863
        except:
 
864
            return '<unprintable %s object>' % type(value).__name__
 
865
 
 
866
traceback._some_str = _clever_some_str
 
867
 
 
868
 
 
869
# deprecated - use self.knownFailure(), or self.expectFailure.
 
870
KnownFailure = testtools.testcase._ExpectedFailure
680
871
 
681
872
 
682
873
class UnavailableFeature(Exception):
688
879
    """
689
880
 
690
881
 
691
 
class CommandFailed(Exception):
692
 
    pass
693
 
 
694
 
 
695
882
class StringIOWrapper(object):
696
883
    """A wrapper around cStringIO which just adds an encoding attribute.
697
884
 
734
921
    # XXX: Should probably unify more with CannedInputUIFactory or a
735
922
    # particular configuration of TextUIFactory, or otherwise have a clearer
736
923
    # idea of how they're supposed to be different.
737
 
    # See https://bugs.edge.launchpad.net/bzr/+bug/408213
 
924
    # See https://bugs.launchpad.net/bzr/+bug/408213
738
925
 
739
926
    def __init__(self, stdout=None, stderr=None, stdin=None):
740
927
        if stdin is not None:
758
945
        return NullProgressView()
759
946
 
760
947
 
761
 
class TestCase(unittest.TestCase):
 
948
def isolated_doctest_setUp(test):
 
949
    override_os_environ(test)
 
950
 
 
951
 
 
952
def isolated_doctest_tearDown(test):
 
953
    restore_os_environ(test)
 
954
 
 
955
 
 
956
def IsolatedDocTestSuite(*args, **kwargs):
 
957
    """Overrides doctest.DocTestSuite to handle isolation.
 
958
 
 
959
    The method is really a factory and users are expected to use it as such.
 
960
    """
 
961
 
 
962
    kwargs['setUp'] = isolated_doctest_setUp
 
963
    kwargs['tearDown'] = isolated_doctest_tearDown
 
964
    return doctest.DocTestSuite(*args, **kwargs)
 
965
 
 
966
 
 
967
class TestCase(testtools.TestCase):
762
968
    """Base class for bzr unit tests.
763
969
 
764
970
    Tests that need access to disk resources should subclass
774
980
    routine, and to build and check bzr trees.
775
981
 
776
982
    In addition to the usual method of overriding tearDown(), this class also
777
 
    allows subclasses to register functions into the _cleanups list, which is
 
983
    allows subclasses to register cleanup functions via addCleanup, which are
778
984
    run in order as the object is torn down.  It's less likely this will be
779
985
    accidentally overlooked.
780
986
    """
781
987
 
782
 
    _active_threads = None
783
 
    _leaking_threads_tests = 0
784
 
    _first_thread_leaker_id = None
785
 
    _log_file_name = None
786
 
    _log_contents = ''
787
 
    _keep_log_file = False
 
988
    _log_file = None
788
989
    # record lsprof data when performing benchmark calls.
789
990
    _gather_lsprof_in_benchmarks = False
790
 
    attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
791
 
                     '_log_contents', '_log_file_name', '_benchtime',
792
 
                     '_TestCase__testMethodName', '_TestCase__testMethodDoc',)
793
991
 
794
992
    def __init__(self, methodName='testMethod'):
795
993
        super(TestCase, self).__init__(methodName)
796
 
        self._cleanups = []
797
 
        self._bzr_test_setUp_run = False
798
 
        self._bzr_test_tearDown_run = False
799
994
        self._directory_isolation = True
 
995
        self.exception_handlers.insert(0,
 
996
            (UnavailableFeature, self._do_unsupported_or_skip))
 
997
        self.exception_handlers.insert(0,
 
998
            (TestNotApplicable, self._do_not_applicable))
800
999
 
801
1000
    def setUp(self):
802
 
        unittest.TestCase.setUp(self)
803
 
        self._bzr_test_setUp_run = True
 
1001
        super(TestCase, self).setUp()
 
1002
 
 
1003
        timeout = config.GlobalStack().get('selftest.timeout')
 
1004
        if timeout:
 
1005
            timeout_fixture = fixtures.TimeoutFixture(timeout)
 
1006
            timeout_fixture.setUp()
 
1007
            self.addCleanup(timeout_fixture.cleanUp)
 
1008
 
 
1009
        for feature in getattr(self, '_test_needs_features', []):
 
1010
            self.requireFeature(feature)
804
1011
        self._cleanEnvironment()
 
1012
 
 
1013
        if bzrlib.global_state is not None:
 
1014
            self.overrideAttr(bzrlib.global_state, 'cmdline_overrides',
 
1015
                              config.CommandLineStore())
 
1016
 
805
1017
        self._silenceUI()
806
1018
        self._startLogFile()
807
1019
        self._benchcalls = []
810
1022
        self._track_transports()
811
1023
        self._track_locks()
812
1024
        self._clear_debug_flags()
813
 
        TestCase._active_threads = threading.activeCount()
814
 
        self.addCleanup(self._check_leaked_threads)
 
1025
        # Isolate global verbosity level, to make sure it's reproducible
 
1026
        # between tests.  We should get rid of this altogether: bug 656694. --
 
1027
        # mbp 20101008
 
1028
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
 
1029
        # Isolate config option expansion until its default value for bzrlib is
 
1030
        # settled on or a the FIXME associated with _get_expand_default_value
 
1031
        # is addressed -- vila 20110219
 
1032
        self.overrideAttr(config, '_expand_default_value', None)
 
1033
        self._log_files = set()
 
1034
        # Each key in the ``_counters`` dict holds a value for a different
 
1035
        # counter. When the test ends, addDetail() should be used to output the
 
1036
        # counter values. This happens in install_counter_hook().
 
1037
        self._counters = {}
 
1038
        if 'config_stats' in selftest_debug_flags:
 
1039
            self._install_config_stats_hooks()
 
1040
        # Do not use i18n for tests (unless the test reverses this)
 
1041
        i18n.disable_i18n()
815
1042
 
816
1043
    def debug(self):
817
1044
        # debug a frame up.
818
1045
        import pdb
819
 
        pdb.Pdb().set_trace(sys._getframe().f_back)
820
 
 
821
 
    def _check_leaked_threads(self):
822
 
        active = threading.activeCount()
823
 
        leaked_threads = active - TestCase._active_threads
824
 
        TestCase._active_threads = active
825
 
        # If some tests make the number of threads *decrease*, we'll consider
826
 
        # that they are just observing old threads dieing, not agressively kill
827
 
        # random threads. So we don't report these tests as leaking. The risk
828
 
        # is that we have false positives that way (the test see 2 threads
829
 
        # going away but leak one) but it seems less likely than the actual
830
 
        # false positives (the test see threads going away and does not leak).
831
 
        if leaked_threads > 0:
832
 
            TestCase._leaking_threads_tests += 1
833
 
            if TestCase._first_thread_leaker_id is None:
834
 
                TestCase._first_thread_leaker_id = self.id()
 
1046
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
1047
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
1048
                ).set_trace(sys._getframe().f_back)
 
1049
 
 
1050
    def discardDetail(self, name):
 
1051
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1052
 
 
1053
        eg. bzr always adds the 'log' detail at startup, but we don't want to
 
1054
        include it for skipped, xfail, etc tests.
 
1055
 
 
1056
        It is safe to call this for a detail that doesn't exist, in case this
 
1057
        gets called multiple times.
 
1058
        """
 
1059
        # We cheat. details is stored in __details which means we shouldn't
 
1060
        # touch it. but getDetails() returns the dict directly, so we can
 
1061
        # mutate it.
 
1062
        details = self.getDetails()
 
1063
        if name in details:
 
1064
            del details[name]
 
1065
 
 
1066
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1067
        """Install a counting hook.
 
1068
 
 
1069
        Any hook can be counted as long as it doesn't need to return a value.
 
1070
 
 
1071
        :param hooks: Where the hook should be installed.
 
1072
 
 
1073
        :param name: The hook name that will be counted.
 
1074
 
 
1075
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1076
            to ``name``.
 
1077
        """
 
1078
        _counters = self._counters # Avoid closing over self
 
1079
        if counter_name is None:
 
1080
            counter_name = name
 
1081
        if _counters.has_key(counter_name):
 
1082
            raise AssertionError('%s is already used as a counter name'
 
1083
                                  % (counter_name,))
 
1084
        _counters[counter_name] = 0
 
1085
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1086
            lambda: ['%d' % (_counters[counter_name],)]))
 
1087
        def increment_counter(*args, **kwargs):
 
1088
            _counters[counter_name] += 1
 
1089
        label = 'count %s calls' % (counter_name,)
 
1090
        hooks.install_named_hook(name, increment_counter, label)
 
1091
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1092
 
 
1093
    def _install_config_stats_hooks(self):
 
1094
        """Install config hooks to count hook calls.
 
1095
 
 
1096
        """
 
1097
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1098
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1099
                                       'config.%s' % (hook_name,))
 
1100
 
 
1101
        # The OldConfigHooks are private and need special handling to protect
 
1102
        # against recursive tests (tests that run other tests), so we just do
 
1103
        # manually what registering them into _builtin_known_hooks will provide
 
1104
        # us.
 
1105
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1106
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1107
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1108
                                      'old_config.%s' % (hook_name,))
835
1109
 
836
1110
    def _clear_debug_flags(self):
837
1111
        """Prevent externally set debug flags affecting tests.
839
1113
        Tests that want to use debug flags can just set them in the
840
1114
        debug_flags set during setup/teardown.
841
1115
        """
842
 
        self._preserved_debug_flags = set(debug.debug_flags)
 
1116
        # Start with a copy of the current debug flags we can safely modify.
 
1117
        self.overrideAttr(debug, 'debug_flags', set(debug.debug_flags))
843
1118
        if 'allow_debug' not in selftest_debug_flags:
844
1119
            debug.debug_flags.clear()
845
1120
        if 'disable_lock_checks' not in selftest_debug_flags:
846
1121
            debug.debug_flags.add('strict_locks')
847
 
        self.addCleanup(self._restore_debug_flags)
848
1122
 
849
1123
    def _clear_hooks(self):
850
1124
        # prevent hooks affecting tests
 
1125
        known_hooks = hooks.known_hooks
851
1126
        self._preserved_hooks = {}
852
 
        for key, factory in hooks.known_hooks.items():
853
 
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
854
 
            current_hooks = hooks.known_hooks_key_to_object(key)
 
1127
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1128
            current_hooks = getattr(parent, name)
855
1129
            self._preserved_hooks[parent] = (name, current_hooks)
 
1130
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1131
        hooks._lazy_hooks = {}
856
1132
        self.addCleanup(self._restoreHooks)
857
 
        for key, factory in hooks.known_hooks.items():
858
 
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
 
1133
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1134
            factory = known_hooks.get(key)
859
1135
            setattr(parent, name, factory())
860
1136
        # this hook should always be installed
861
1137
        request._install_hook()
871
1147
    def _silenceUI(self):
872
1148
        """Turn off UI for duration of test"""
873
1149
        # by default the UI is off; tests can turn it on if they want it.
874
 
        saved = ui.ui_factory
875
 
        def _restore():
876
 
            ui.ui_factory = saved
877
 
        ui.ui_factory = ui.SilentUIFactory()
878
 
        self.addCleanup(_restore)
 
1150
        self.overrideAttr(ui, 'ui_factory', ui.SilentUIFactory())
879
1151
 
880
1152
    def _check_locks(self):
881
1153
        """Check that all lock take/release actions have been paired."""
894
1166
        # break some locks on purpose and should be taken into account by
895
1167
        # considering that breaking a lock is just a dirty way of releasing it.
896
1168
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
897
 
            message = ('Different number of acquired and '
898
 
                       'released or broken locks. (%s, %s + %s)' %
899
 
                       (acquired_locks, released_locks, broken_locks))
 
1169
            message = (
 
1170
                'Different number of acquired and '
 
1171
                'released or broken locks.\n'
 
1172
                'acquired=%s\n'
 
1173
                'released=%s\n'
 
1174
                'broken=%s\n' %
 
1175
                (acquired_locks, released_locks, broken_locks))
900
1176
            if not self._lock_check_thorough:
901
1177
                # Rather than fail, just warn
902
1178
                print "Broken test %s: %s" % (self, message)
910
1186
            self._lock_check_thorough = False
911
1187
        else:
912
1188
            self._lock_check_thorough = True
913
 
            
 
1189
 
914
1190
        self.addCleanup(self._check_locks)
915
1191
        _mod_lock.Lock.hooks.install_named_hook('lock_acquired',
916
1192
                                                self._lock_acquired, None)
930
1206
 
931
1207
    def permit_dir(self, name):
932
1208
        """Permit a directory to be used by this test. See permit_url."""
933
 
        name_transport = get_transport(name)
 
1209
        name_transport = _mod_transport.get_transport_from_path(name)
934
1210
        self.permit_url(name)
935
1211
        self.permit_url(name_transport.base)
936
1212
 
959
1235
            try:
960
1236
                workingtree.WorkingTree.open(path)
961
1237
            except (errors.NotBranchError, errors.NoWorkingTree):
962
 
                return
 
1238
                raise TestSkipped('Needs a working tree of bzr sources')
963
1239
        finally:
964
1240
            self.enable_directory_isolation()
965
1241
 
1009
1285
        server's urls to be used.
1010
1286
        """
1011
1287
        if backing_server is None:
1012
 
            transport_server.setUp()
 
1288
            transport_server.start_server()
1013
1289
        else:
1014
 
            transport_server.setUp(backing_server)
1015
 
        self.addCleanup(transport_server.tearDown)
 
1290
            transport_server.start_server(backing_server)
 
1291
        self.addCleanup(transport_server.stop_server)
1016
1292
        # Obtain a real transport because if the server supplies a password, it
1017
1293
        # will be hidden from the base on the client side.
1018
 
        t = get_transport(transport_server.get_url())
 
1294
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1019
1295
        # Some transport servers effectively chroot the backing transport;
1020
1296
        # others like SFTPServer don't - users of the transport can walk up the
1021
1297
        # transport to read the entire backing transport. This wouldn't matter
1032
1308
        if t.base.endswith('/work/'):
1033
1309
            # we have safety net/test root/work
1034
1310
            t = t.clone('../..')
1035
 
        elif isinstance(transport_server, server.SmartTCPServer_for_testing):
 
1311
        elif isinstance(transport_server,
 
1312
                        test_server.SmartTCPServer_for_testing):
1036
1313
            # The smart server adds a path similar to work, which is traversed
1037
1314
            # up from by the client. But the server is chrooted - the actual
1038
1315
            # backing transport is not escaped from, and VFS requests to the
1076
1353
        except UnicodeError, e:
1077
1354
            # If we can't compare without getting a UnicodeError, then
1078
1355
            # obviously they are different
1079
 
            mutter('UnicodeError: %s', e)
 
1356
            trace.mutter('UnicodeError: %s', e)
1080
1357
        if message:
1081
1358
            message += '\n'
1082
1359
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1083
1360
            % (message,
1084
 
               pformat(a), pformat(b)))
 
1361
               pprint.pformat(a), pprint.pformat(b)))
1085
1362
 
1086
1363
    assertEquals = assertEqual
1087
1364
 
1121
1398
                         'st_mtime did not match')
1122
1399
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1123
1400
                         'st_ctime did not match')
1124
 
        if sys.platform != 'win32':
 
1401
        if sys.platform == 'win32':
1125
1402
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1126
1403
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
1127
 
            # odd. Regardless we shouldn't actually try to assert anything
1128
 
            # about their values
 
1404
            # odd. We just force it to always be 0 to avoid any problems.
 
1405
            self.assertEqual(0, expected.st_dev)
 
1406
            self.assertEqual(0, actual.st_dev)
 
1407
            self.assertEqual(0, expected.st_ino)
 
1408
            self.assertEqual(0, actual.st_ino)
 
1409
        else:
1129
1410
            self.assertEqual(expected.st_dev, actual.st_dev,
1130
1411
                             'st_dev did not match')
1131
1412
            self.assertEqual(expected.st_ino, actual.st_ino,
1140
1421
                length, len(obj_with_len), obj_with_len))
1141
1422
 
1142
1423
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1143
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1424
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1144
1425
        """
1145
 
        from bzrlib import trace
1146
1426
        captured = []
1147
1427
        orig_log_exception_quietly = trace.log_exception_quietly
1148
1428
        try:
1149
1429
            def capture():
1150
1430
                orig_log_exception_quietly()
1151
 
                captured.append(sys.exc_info())
 
1431
                captured.append(sys.exc_info()[1])
1152
1432
            trace.log_exception_quietly = capture
1153
1433
            func(*args, **kwargs)
1154
1434
        finally:
1155
1435
            trace.log_exception_quietly = orig_log_exception_quietly
1156
1436
        self.assertLength(1, captured)
1157
 
        err = captured[0][1]
 
1437
        err = captured[0]
1158
1438
        self.assertIsInstance(err, exception_class)
1159
1439
        return err
1160
1440
 
1193
1473
            raise AssertionError('pattern "%s" found in "%s"'
1194
1474
                    % (needle_re, haystack))
1195
1475
 
 
1476
    def assertContainsString(self, haystack, needle):
 
1477
        if haystack.find(needle) == -1:
 
1478
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
 
1479
 
 
1480
    def assertNotContainsString(self, haystack, needle):
 
1481
        if haystack.find(needle) != -1:
 
1482
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1483
 
1196
1484
    def assertSubset(self, sublist, superlist):
1197
1485
        """Assert that every entry in sublist is present in superlist."""
1198
1486
        missing = set(sublist) - set(superlist)
1285
1573
                m += ": " + msg
1286
1574
            self.fail(m)
1287
1575
 
1288
 
    def expectFailure(self, reason, assertion, *args, **kwargs):
1289
 
        """Invoke a test, expecting it to fail for the given reason.
1290
 
 
1291
 
        This is for assertions that ought to succeed, but currently fail.
1292
 
        (The failure is *expected* but not *wanted*.)  Please be very precise
1293
 
        about the failure you're expecting.  If a new bug is introduced,
1294
 
        AssertionError should be raised, not KnownFailure.
1295
 
 
1296
 
        Frequently, expectFailure should be followed by an opposite assertion.
1297
 
        See example below.
1298
 
 
1299
 
        Intended to be used with a callable that raises AssertionError as the
1300
 
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
1301
 
 
1302
 
        Raises KnownFailure if the test fails.  Raises AssertionError if the
1303
 
        test succeeds.
1304
 
 
1305
 
        example usage::
1306
 
 
1307
 
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
1308
 
                             dynamic_val)
1309
 
          self.assertEqual(42, dynamic_val)
1310
 
 
1311
 
          This means that a dynamic_val of 54 will cause the test to raise
1312
 
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
1313
 
          only a dynamic_val of 42 will allow the test to pass.  Anything other
1314
 
          than 54 or 42 will cause an AssertionError.
1315
 
        """
1316
 
        try:
1317
 
            assertion(*args, **kwargs)
1318
 
        except AssertionError:
1319
 
            raise KnownFailure(reason)
1320
 
        else:
1321
 
            self.fail('Unexpected success.  Should have failed: %s' % reason)
1322
 
 
1323
1576
    def assertFileEqual(self, content, path):
1324
1577
        """Fail if path does not contain 'content'."""
1325
 
        self.failUnlessExists(path)
 
1578
        self.assertPathExists(path)
1326
1579
        f = file(path, 'rb')
1327
1580
        try:
1328
1581
            s = f.read()
1330
1583
            f.close()
1331
1584
        self.assertEqualDiff(content, s)
1332
1585
 
 
1586
    def assertDocstring(self, expected_docstring, obj):
 
1587
        """Fail if obj does not have expected_docstring"""
 
1588
        if __doc__ is None:
 
1589
            # With -OO the docstring should be None instead
 
1590
            self.assertIs(obj.__doc__, None)
 
1591
        else:
 
1592
            self.assertEqual(expected_docstring, obj.__doc__)
 
1593
 
 
1594
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1333
1595
    def failUnlessExists(self, path):
 
1596
        return self.assertPathExists(path)
 
1597
 
 
1598
    def assertPathExists(self, path):
1334
1599
        """Fail unless path or paths, which may be abs or relative, exist."""
1335
1600
        if not isinstance(path, basestring):
1336
1601
            for p in path:
1337
 
                self.failUnlessExists(p)
 
1602
                self.assertPathExists(p)
1338
1603
        else:
1339
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1604
            self.assertTrue(osutils.lexists(path),
 
1605
                path + " does not exist")
1340
1606
 
 
1607
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1341
1608
    def failIfExists(self, path):
 
1609
        return self.assertPathDoesNotExist(path)
 
1610
 
 
1611
    def assertPathDoesNotExist(self, path):
1342
1612
        """Fail if path or paths, which may be abs or relative, exist."""
1343
1613
        if not isinstance(path, basestring):
1344
1614
            for p in path:
1345
 
                self.failIfExists(p)
 
1615
                self.assertPathDoesNotExist(p)
1346
1616
        else:
1347
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1617
            self.assertFalse(osutils.lexists(path),
 
1618
                path + " exists")
1348
1619
 
1349
1620
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1350
1621
        """A helper for callDeprecated and applyDeprecated.
1376
1647
        not other callers that go direct to the warning module.
1377
1648
 
1378
1649
        To test that a deprecated method raises an error, do something like
1379
 
        this::
 
1650
        this (remember that both assertRaises and applyDeprecated delays *args
 
1651
        and **kwargs passing)::
1380
1652
 
1381
1653
            self.assertRaises(errors.ReservedId,
1382
1654
                self.applyDeprecated,
1460
1732
        return result
1461
1733
 
1462
1734
    def _startLogFile(self):
1463
 
        """Send bzr and test log messages to a temporary file.
1464
 
 
1465
 
        The file is removed as the test is torn down.
1466
 
        """
1467
 
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
1468
 
        self._log_file = os.fdopen(fileno, 'w+')
1469
 
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
1470
 
        self._log_file_name = name
 
1735
        """Setup a in-memory target for bzr and testcase log messages"""
 
1736
        pseudo_log_file = StringIO()
 
1737
        def _get_log_contents_for_weird_testtools_api():
 
1738
            return [pseudo_log_file.getvalue().decode(
 
1739
                "utf-8", "replace").encode("utf-8")]
 
1740
        self.addDetail("log", content.Content(content.ContentType("text",
 
1741
            "plain", {"charset": "utf8"}),
 
1742
            _get_log_contents_for_weird_testtools_api))
 
1743
        self._log_file = pseudo_log_file
 
1744
        self._log_memento = trace.push_log_file(self._log_file)
1471
1745
        self.addCleanup(self._finishLogFile)
1472
1746
 
1473
1747
    def _finishLogFile(self):
1474
 
        """Finished with the log file.
1475
 
 
1476
 
        Close the file and delete it, unless setKeepLogfile was called.
1477
 
        """
1478
 
        if self._log_file is None:
1479
 
            return
1480
 
        bzrlib.trace.pop_log_file(self._log_memento)
1481
 
        self._log_file.close()
1482
 
        self._log_file = None
1483
 
        if not self._keep_log_file:
1484
 
            os.remove(self._log_file_name)
1485
 
            self._log_file_name = None
1486
 
 
1487
 
    def setKeepLogfile(self):
1488
 
        """Make the logfile not be deleted when _finishLogFile is called."""
1489
 
        self._keep_log_file = True
 
1748
        """Flush and dereference the in-memory log for this testcase"""
 
1749
        if trace._trace_file:
 
1750
            # flush the log file, to get all content
 
1751
            trace._trace_file.flush()
 
1752
        trace.pop_log_file(self._log_memento)
 
1753
        # The logging module now tracks references for cleanup so discard ours
 
1754
        del self._log_memento
1490
1755
 
1491
1756
    def thisFailsStrictLockCheck(self):
1492
1757
        """It is known that this test would fail with -Dstrict_locks.
1501
1766
        """
1502
1767
        debug.debug_flags.discard('strict_locks')
1503
1768
 
1504
 
    def addCleanup(self, callable, *args, **kwargs):
1505
 
        """Arrange to run a callable when this case is torn down.
1506
 
 
1507
 
        Callables are run in the reverse of the order they are registered,
1508
 
        ie last-in first-out.
1509
 
        """
1510
 
        self._cleanups.append((callable, args, kwargs))
 
1769
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
 
1770
        """Overrides an object attribute restoring it after the test.
 
1771
 
 
1772
        :note: This should be used with discretion; you should think about
 
1773
        whether it's better to make the code testable without monkey-patching.
 
1774
 
 
1775
        :param obj: The object that will be mutated.
 
1776
 
 
1777
        :param attr_name: The attribute name we want to preserve/override in
 
1778
            the object.
 
1779
 
 
1780
        :param new: The optional value we want to set the attribute to.
 
1781
 
 
1782
        :returns: The actual attr value.
 
1783
        """
 
1784
        value = getattr(obj, attr_name)
 
1785
        # The actual value is captured by the call below
 
1786
        self.addCleanup(setattr, obj, attr_name, value)
 
1787
        if new is not _unitialized_attr:
 
1788
            setattr(obj, attr_name, new)
 
1789
        return value
 
1790
 
 
1791
    def overrideEnv(self, name, new):
 
1792
        """Set an environment variable, and reset it after the test.
 
1793
 
 
1794
        :param name: The environment variable name.
 
1795
 
 
1796
        :param new: The value to set the variable to. If None, the 
 
1797
            variable is deleted from the environment.
 
1798
 
 
1799
        :returns: The actual variable value.
 
1800
        """
 
1801
        value = osutils.set_or_unset_env(name, new)
 
1802
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1803
        return value
 
1804
 
 
1805
    def recordCalls(self, obj, attr_name):
 
1806
        """Monkeypatch in a wrapper that will record calls.
 
1807
 
 
1808
        The monkeypatch is automatically removed when the test concludes.
 
1809
 
 
1810
        :param obj: The namespace holding the reference to be replaced;
 
1811
            typically a module, class, or object.
 
1812
        :param attr_name: A string for the name of the attribute to 
 
1813
            patch.
 
1814
        :returns: A list that will be extended with one item every time the
 
1815
            function is called, with a tuple of (args, kwargs).
 
1816
        """
 
1817
        calls = []
 
1818
 
 
1819
        def decorator(*args, **kwargs):
 
1820
            calls.append((args, kwargs))
 
1821
            return orig(*args, **kwargs)
 
1822
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1823
        return calls
1511
1824
 
1512
1825
    def _cleanEnvironment(self):
1513
 
        new_env = {
1514
 
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1515
 
            'HOME': os.getcwd(),
1516
 
            # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1517
 
            # tests do check our impls match APPDATA
1518
 
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
1519
 
            'VISUAL': None,
1520
 
            'EDITOR': None,
1521
 
            'BZR_EMAIL': None,
1522
 
            'BZREMAIL': None, # may still be present in the environment
1523
 
            'EMAIL': None,
1524
 
            'BZR_PROGRESS_BAR': None,
1525
 
            'BZR_LOG': None,
1526
 
            'BZR_PLUGIN_PATH': None,
1527
 
            'BZR_CONCURRENCY': None,
1528
 
            # Make sure that any text ui tests are consistent regardless of
1529
 
            # the environment the test case is run in; you may want tests that
1530
 
            # test other combinations.  'dumb' is a reasonable guess for tests
1531
 
            # going to a pipe or a StringIO.
1532
 
            'TERM': 'dumb',
1533
 
            'LINES': '25',
1534
 
            'COLUMNS': '80',
1535
 
            # SSH Agent
1536
 
            'SSH_AUTH_SOCK': None,
1537
 
            # Proxies
1538
 
            'http_proxy': None,
1539
 
            'HTTP_PROXY': None,
1540
 
            'https_proxy': None,
1541
 
            'HTTPS_PROXY': None,
1542
 
            'no_proxy': None,
1543
 
            'NO_PROXY': None,
1544
 
            'all_proxy': None,
1545
 
            'ALL_PROXY': None,
1546
 
            # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1547
 
            # least. If you do (care), please update this comment
1548
 
            # -- vila 20080401
1549
 
            'ftp_proxy': None,
1550
 
            'FTP_PROXY': None,
1551
 
            'BZR_REMOTE_PATH': None,
1552
 
        }
1553
 
        self.__old_env = {}
1554
 
        self.addCleanup(self._restoreEnvironment)
1555
 
        for name, value in new_env.iteritems():
1556
 
            self._captureVar(name, value)
1557
 
 
1558
 
    def _captureVar(self, name, newvalue):
1559
 
        """Set an environment variable, and reset it when finished."""
1560
 
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
1561
 
 
1562
 
    def _restore_debug_flags(self):
1563
 
        debug.debug_flags.clear()
1564
 
        debug.debug_flags.update(self._preserved_debug_flags)
1565
 
 
1566
 
    def _restoreEnvironment(self):
1567
 
        for name, value in self.__old_env.iteritems():
1568
 
            osutils.set_or_unset_env(name, value)
 
1826
        for name, value in isolated_environ.iteritems():
 
1827
            self.overrideEnv(name, value)
1569
1828
 
1570
1829
    def _restoreHooks(self):
1571
1830
        for klass, (name, hooks) in self._preserved_hooks.items():
1572
1831
            setattr(klass, name, hooks)
 
1832
        self._preserved_hooks.clear()
 
1833
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1834
        self._preserved_lazy_hooks.clear()
1573
1835
 
1574
1836
    def knownFailure(self, reason):
1575
 
        """This test has failed for some known reason."""
1576
 
        raise KnownFailure(reason)
 
1837
        """Declare that this test fails for a known reason
 
1838
 
 
1839
        Tests that are known to fail should generally be using expectedFailure
 
1840
        with an appropriate reverse assertion if a change could cause the test
 
1841
        to start passing. Conversely if the test has no immediate prospect of
 
1842
        succeeding then using skip is more suitable.
 
1843
 
 
1844
        When this method is called while an exception is being handled, that
 
1845
        traceback will be used, otherwise a new exception will be thrown to
 
1846
        provide one but won't be reported.
 
1847
        """
 
1848
        self._add_reason(reason)
 
1849
        try:
 
1850
            exc_info = sys.exc_info()
 
1851
            if exc_info != (None, None, None):
 
1852
                self._report_traceback(exc_info)
 
1853
            else:
 
1854
                try:
 
1855
                    raise self.failureException(reason)
 
1856
                except self.failureException:
 
1857
                    exc_info = sys.exc_info()
 
1858
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1859
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1860
        finally:
 
1861
            del exc_info
 
1862
 
 
1863
    def _suppress_log(self):
 
1864
        """Remove the log info from details."""
 
1865
        self.discardDetail('log')
1577
1866
 
1578
1867
    def _do_skip(self, result, reason):
 
1868
        self._suppress_log()
1579
1869
        addSkip = getattr(result, 'addSkip', None)
1580
1870
        if not callable(addSkip):
1581
1871
            result.addSuccess(result)
1582
1872
        else:
1583
1873
            addSkip(self, reason)
1584
1874
 
1585
 
    def _do_known_failure(self, result):
 
1875
    @staticmethod
 
1876
    def _do_known_failure(self, result, e):
 
1877
        self._suppress_log()
1586
1878
        err = sys.exc_info()
1587
1879
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1588
1880
        if addExpectedFailure is not None:
1590
1882
        else:
1591
1883
            result.addSuccess(self)
1592
1884
 
 
1885
    @staticmethod
1593
1886
    def _do_not_applicable(self, result, e):
1594
1887
        if not e.args:
1595
1888
            reason = 'No reason given'
1596
1889
        else:
1597
1890
            reason = e.args[0]
 
1891
        self._suppress_log ()
1598
1892
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1599
1893
        if addNotApplicable is not None:
1600
1894
            result.addNotApplicable(self, reason)
1601
1895
        else:
1602
1896
            self._do_skip(result, reason)
1603
1897
 
1604
 
    def _do_unsupported_or_skip(self, result, reason):
 
1898
    @staticmethod
 
1899
    def _report_skip(self, result, err):
 
1900
        """Override the default _report_skip.
 
1901
 
 
1902
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1903
        already been formatted into the 'reason' string, and we can't pull it
 
1904
        out again.
 
1905
        """
 
1906
        self._suppress_log()
 
1907
        super(TestCase, self)._report_skip(self, result, err)
 
1908
 
 
1909
    @staticmethod
 
1910
    def _report_expected_failure(self, result, err):
 
1911
        """Strip the log.
 
1912
 
 
1913
        See _report_skip for motivation.
 
1914
        """
 
1915
        self._suppress_log()
 
1916
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1917
 
 
1918
    @staticmethod
 
1919
    def _do_unsupported_or_skip(self, result, e):
 
1920
        reason = e.args[0]
 
1921
        self._suppress_log()
1605
1922
        addNotSupported = getattr(result, 'addNotSupported', None)
1606
1923
        if addNotSupported is not None:
1607
1924
            result.addNotSupported(self, reason)
1608
1925
        else:
1609
1926
            self._do_skip(result, reason)
1610
1927
 
1611
 
    def run(self, result=None):
1612
 
        if result is None: result = self.defaultTestResult()
1613
 
        result.startTest(self)
1614
 
        try:
1615
 
            self._run(result)
1616
 
            return result
1617
 
        finally:
1618
 
            result.stopTest(self)
1619
 
 
1620
 
    def _run(self, result):
1621
 
        for feature in getattr(self, '_test_needs_features', []):
1622
 
            if not feature.available():
1623
 
                return self._do_unsupported_or_skip(result, feature)
1624
 
        try:
1625
 
            absent_attr = object()
1626
 
            # Python 2.5
1627
 
            method_name = getattr(self, '_testMethodName', absent_attr)
1628
 
            if method_name is absent_attr:
1629
 
                # Python 2.4
1630
 
                method_name = getattr(self, '_TestCase__testMethodName')
1631
 
            testMethod = getattr(self, method_name)
1632
 
            try:
1633
 
                try:
1634
 
                    self.setUp()
1635
 
                    if not self._bzr_test_setUp_run:
1636
 
                        self.fail(
1637
 
                            "test setUp did not invoke "
1638
 
                            "bzrlib.tests.TestCase's setUp")
1639
 
                except KeyboardInterrupt:
1640
 
                    self._runCleanups()
1641
 
                    raise
1642
 
                except KnownFailure:
1643
 
                    self._do_known_failure(result)
1644
 
                    self.tearDown()
1645
 
                    return
1646
 
                except TestNotApplicable, e:
1647
 
                    self._do_not_applicable(result, e)
1648
 
                    self.tearDown()
1649
 
                    return
1650
 
                except TestSkipped, e:
1651
 
                    self._do_skip(result, e.args[0])
1652
 
                    self.tearDown()
1653
 
                    return result
1654
 
                except UnavailableFeature, e:
1655
 
                    self._do_unsupported_or_skip(result, e.args[0])
1656
 
                    self.tearDown()
1657
 
                    return
1658
 
                except:
1659
 
                    result.addError(self, sys.exc_info())
1660
 
                    self._runCleanups()
1661
 
                    return result
1662
 
 
1663
 
                ok = False
1664
 
                try:
1665
 
                    testMethod()
1666
 
                    ok = True
1667
 
                except KnownFailure:
1668
 
                    self._do_known_failure(result)
1669
 
                except self.failureException:
1670
 
                    result.addFailure(self, sys.exc_info())
1671
 
                except TestNotApplicable, e:
1672
 
                    self._do_not_applicable(result, e)
1673
 
                except TestSkipped, e:
1674
 
                    if not e.args:
1675
 
                        reason = "No reason given."
1676
 
                    else:
1677
 
                        reason = e.args[0]
1678
 
                    self._do_skip(result, reason)
1679
 
                except UnavailableFeature, e:
1680
 
                    self._do_unsupported_or_skip(result, e.args[0])
1681
 
                except KeyboardInterrupt:
1682
 
                    self._runCleanups()
1683
 
                    raise
1684
 
                except:
1685
 
                    result.addError(self, sys.exc_info())
1686
 
 
1687
 
                try:
1688
 
                    self.tearDown()
1689
 
                    if not self._bzr_test_tearDown_run:
1690
 
                        self.fail(
1691
 
                            "test tearDown did not invoke "
1692
 
                            "bzrlib.tests.TestCase's tearDown")
1693
 
                except KeyboardInterrupt:
1694
 
                    self._runCleanups()
1695
 
                    raise
1696
 
                except:
1697
 
                    result.addError(self, sys.exc_info())
1698
 
                    self._runCleanups()
1699
 
                    ok = False
1700
 
                if ok: result.addSuccess(self)
1701
 
                return result
1702
 
            except KeyboardInterrupt:
1703
 
                self._runCleanups()
1704
 
                raise
1705
 
        finally:
1706
 
            saved_attrs = {}
1707
 
            for attr_name in self.attrs_to_keep:
1708
 
                if attr_name in self.__dict__:
1709
 
                    saved_attrs[attr_name] = self.__dict__[attr_name]
1710
 
            self.__dict__ = saved_attrs
1711
 
 
1712
 
    def tearDown(self):
1713
 
        self._runCleanups()
1714
 
        self._log_contents = ''
1715
 
        self._bzr_test_tearDown_run = True
1716
 
        unittest.TestCase.tearDown(self)
1717
 
 
1718
1928
    def time(self, callable, *args, **kwargs):
1719
1929
        """Run callable and accrue the time it takes to the benchmark time.
1720
1930
 
1723
1933
        self._benchcalls.
1724
1934
        """
1725
1935
        if self._benchtime is None:
 
1936
            self.addDetail('benchtime', content.Content(content.ContentType(
 
1937
                "text", "plain"), lambda:[str(self._benchtime)]))
1726
1938
            self._benchtime = 0
1727
1939
        start = time.time()
1728
1940
        try:
1737
1949
        finally:
1738
1950
            self._benchtime += time.time() - start
1739
1951
 
1740
 
    def _runCleanups(self):
1741
 
        """Run registered cleanup functions.
1742
 
 
1743
 
        This should only be called from TestCase.tearDown.
1744
 
        """
1745
 
        # TODO: Perhaps this should keep running cleanups even if
1746
 
        # one of them fails?
1747
 
 
1748
 
        # Actually pop the cleanups from the list so tearDown running
1749
 
        # twice is safe (this happens for skipped tests).
1750
 
        while self._cleanups:
1751
 
            cleanup, args, kwargs = self._cleanups.pop()
1752
 
            cleanup(*args, **kwargs)
1753
 
 
1754
1952
    def log(self, *args):
1755
 
        mutter(*args)
1756
 
 
1757
 
    def _get_log(self, keep_log_file=False):
1758
 
        """Get the log from bzrlib.trace calls from this test.
1759
 
 
1760
 
        :param keep_log_file: When True, if the log is still a file on disk
1761
 
            leave it as a file on disk. When False, if the log is still a file
1762
 
            on disk, the log file is deleted and the log preserved as
1763
 
            self._log_contents.
1764
 
        :return: A string containing the log.
 
1953
        trace.mutter(*args)
 
1954
 
 
1955
    def get_log(self):
 
1956
        """Get a unicode string containing the log from bzrlib.trace.
 
1957
 
 
1958
        Undecodable characters are replaced.
1765
1959
        """
1766
 
        # flush the log file, to get all content
1767
 
        import bzrlib.trace
1768
 
        if bzrlib.trace._trace_file:
1769
 
            bzrlib.trace._trace_file.flush()
1770
 
        if self._log_contents:
1771
 
            # XXX: this can hardly contain the content flushed above --vila
1772
 
            # 20080128
1773
 
            return self._log_contents
1774
 
        if self._log_file_name is not None:
1775
 
            logfile = open(self._log_file_name)
1776
 
            try:
1777
 
                log_contents = logfile.read()
1778
 
            finally:
1779
 
                logfile.close()
1780
 
            if not keep_log_file:
1781
 
                self._log_contents = log_contents
1782
 
                try:
1783
 
                    os.remove(self._log_file_name)
1784
 
                except OSError, e:
1785
 
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
1786
 
                        sys.stderr.write(('Unable to delete log file '
1787
 
                                             ' %r\n' % self._log_file_name))
1788
 
                    else:
1789
 
                        raise
1790
 
            return log_contents
1791
 
        else:
1792
 
            return "DELETED log file to reduce memory footprint"
 
1960
        return u"".join(self.getDetails()['log'].iter_text())
1793
1961
 
1794
1962
    def requireFeature(self, feature):
1795
1963
        """This test requires a specific feature is available.
1824
1992
 
1825
1993
        self.log('run bzr: %r', args)
1826
1994
        # FIXME: don't call into logging here
1827
 
        handler = logging.StreamHandler(stderr)
1828
 
        handler.setLevel(logging.INFO)
 
1995
        handler = trace.EncodedStreamHandler(stderr, errors="replace",
 
1996
            level=logging.INFO)
1829
1997
        logger = logging.getLogger('')
1830
1998
        logger.addHandler(handler)
1831
1999
        old_ui_factory = ui.ui_factory
1838
2006
 
1839
2007
        try:
1840
2008
            try:
1841
 
                result = self.apply_redirected(ui.ui_factory.stdin,
 
2009
                result = self.apply_redirected(
 
2010
                    ui.ui_factory.stdin,
1842
2011
                    stdout, stderr,
1843
 
                    bzrlib.commands.run_bzr_catch_user_errors,
 
2012
                    _mod_commands.run_bzr_catch_user_errors,
1844
2013
                    args)
1845
2014
            except KeyboardInterrupt:
1846
2015
                # Reraise KeyboardInterrupt with contents of redirected stdout
1988
2157
    def start_bzr_subprocess(self, process_args, env_changes=None,
1989
2158
                             skip_if_plan_to_signal=False,
1990
2159
                             working_dir=None,
1991
 
                             allow_plugins=False):
 
2160
                             allow_plugins=False, stderr=subprocess.PIPE):
1992
2161
        """Start bzr in a subprocess for testing.
1993
2162
 
1994
2163
        This starts a new Python interpreter and runs bzr in there.
2003
2172
            variables. A value of None will unset the env variable.
2004
2173
            The values must be strings. The change will only occur in the
2005
2174
            child, so you don't need to fix the environment after running.
2006
 
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
2007
 
            is not available.
 
2175
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2176
            doesn't support signalling subprocesses.
2008
2177
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
2178
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2179
            are those valid for the stderr argument of `subprocess.Popen`.
 
2180
            Default value is ``subprocess.PIPE``.
2009
2181
 
2010
2182
        :returns: Popen object for the started process.
2011
2183
        """
2012
2184
        if skip_if_plan_to_signal:
2013
 
            if not getattr(os, 'kill', None):
2014
 
                raise TestSkipped("os.kill not available.")
 
2185
            if os.name != "posix":
 
2186
                raise TestSkipped("Sending signals not supported")
2015
2187
 
2016
2188
        if env_changes is None:
2017
2189
            env_changes = {}
 
2190
        # Because $HOME is set to a tempdir for the context of a test, modules
 
2191
        # installed in the user dir will not be found unless $PYTHONUSERBASE
 
2192
        # gets set to the computed directory of this parent process.
 
2193
        if site.USER_BASE is not None:
 
2194
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
2018
2195
        old_env = {}
2019
2196
 
2020
2197
        def cleanup_environment():
2037
2214
            # so we will avoid using it on all platforms, just to
2038
2215
            # make sure the code path is used, and we don't break on win32
2039
2216
            cleanup_environment()
 
2217
            # Include the subprocess's log file in the test details, in case
 
2218
            # the test fails due to an error in the subprocess.
 
2219
            self._add_subprocess_log(trace._get_bzr_log_filename())
2040
2220
            command = [sys.executable]
2041
2221
            # frozen executables don't need the path to bzr
2042
2222
            if getattr(sys, "frozen", None) is None:
2044
2224
            if not allow_plugins:
2045
2225
                command.append('--no-plugins')
2046
2226
            command.extend(process_args)
2047
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
2227
            process = self._popen(command, stdin=subprocess.PIPE,
 
2228
                                  stdout=subprocess.PIPE,
 
2229
                                  stderr=stderr)
2048
2230
        finally:
2049
2231
            restore_environment()
2050
2232
            if cwd is not None:
2052
2234
 
2053
2235
        return process
2054
2236
 
 
2237
    def _add_subprocess_log(self, log_file_path):
 
2238
        if len(self._log_files) == 0:
 
2239
            # Register an addCleanup func.  We do this on the first call to
 
2240
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2241
            # addCleanup is registered after any cleanups for tempdirs that
 
2242
            # subclasses might create, which will probably remove the log file
 
2243
            # we want to read.
 
2244
            self.addCleanup(self._subprocess_log_cleanup)
 
2245
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2246
        # twice.
 
2247
        self._log_files.add(log_file_path)
 
2248
 
 
2249
    def _subprocess_log_cleanup(self):
 
2250
        for count, log_file_path in enumerate(self._log_files):
 
2251
            # We use buffer_now=True to avoid holding the file open beyond
 
2252
            # the life of this function, which might interfere with e.g.
 
2253
            # cleaning tempdirs on Windows.
 
2254
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2255
            #detail_content = content.content_from_file(
 
2256
            #    log_file_path, buffer_now=True)
 
2257
            with open(log_file_path, 'rb') as log_file:
 
2258
                log_file_bytes = log_file.read()
 
2259
            detail_content = content.Content(content.ContentType("text",
 
2260
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2261
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2262
                detail_content)
 
2263
 
2055
2264
    def _popen(self, *args, **kwargs):
2056
2265
        """Place a call to Popen.
2057
2266
 
2058
2267
        Allows tests to override this method to intercept the calls made to
2059
2268
        Popen for introspection.
2060
2269
        """
2061
 
        return Popen(*args, **kwargs)
 
2270
        return subprocess.Popen(*args, **kwargs)
2062
2271
 
2063
2272
    def get_source_path(self):
2064
2273
        """Return the path of the directory containing bzrlib."""
2066
2275
 
2067
2276
    def get_bzr_path(self):
2068
2277
        """Return the path of the 'bzr' executable for this test suite."""
2069
 
        bzr_path = self.get_source_path()+'/bzr'
 
2278
        bzr_path = os.path.join(self.get_source_path(), "bzr")
2070
2279
        if not os.path.isfile(bzr_path):
2071
2280
            # We are probably installed. Assume sys.argv is the right file
2072
2281
            bzr_path = sys.argv[0]
2094
2303
        if retcode is not None and retcode != process.returncode:
2095
2304
            if process_args is None:
2096
2305
                process_args = "(unknown args)"
2097
 
            mutter('Output of bzr %s:\n%s', process_args, out)
2098
 
            mutter('Error for bzr %s:\n%s', process_args, err)
 
2306
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
 
2307
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
2099
2308
            self.fail('Command bzr %s failed with retcode %s != %s'
2100
2309
                      % (process_args, retcode, process.returncode))
2101
2310
        return [out, err]
2102
2311
 
2103
 
    def check_inventory_shape(self, inv, shape):
2104
 
        """Compare an inventory to a list of expected names.
 
2312
    def check_tree_shape(self, tree, shape):
 
2313
        """Compare a tree to a list of expected names.
2105
2314
 
2106
2315
        Fail if they are not precisely equal.
2107
2316
        """
2108
2317
        extras = []
2109
2318
        shape = list(shape)             # copy
2110
 
        for path, ie in inv.entries():
 
2319
        for path, ie in tree.iter_entries_by_dir():
2111
2320
            name = path.replace('\\', '/')
2112
2321
            if ie.kind == 'directory':
2113
2322
                name = name + '/'
2114
 
            if name in shape:
 
2323
            if name == "/":
 
2324
                pass # ignore root entry
 
2325
            elif name in shape:
2115
2326
                shape.remove(name)
2116
2327
            else:
2117
2328
                extras.append(name)
2158
2369
 
2159
2370
        Tests that expect to provoke LockContention errors should call this.
2160
2371
        """
2161
 
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
2162
 
        def resetTimeout():
2163
 
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
2164
 
        self.addCleanup(resetTimeout)
2165
 
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
2372
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2166
2373
 
2167
2374
    def make_utf8_encoded_stringio(self, encoding_type=None):
2168
2375
        """Return a StringIOWrapper instance, that will encode Unicode
2181
2388
        from bzrlib.smart import request
2182
2389
        request_handlers = request.request_handlers
2183
2390
        orig_method = request_handlers.get(verb)
 
2391
        orig_info = request_handlers.get_info(verb)
2184
2392
        request_handlers.remove(verb)
2185
 
        def restoreVerb():
2186
 
            request_handlers.register(verb, orig_method)
2187
 
        self.addCleanup(restoreVerb)
 
2393
        self.addCleanup(request_handlers.register, verb, orig_method,
 
2394
            info=orig_info)
2188
2395
 
2189
2396
 
2190
2397
class CapturedCall(object):
2213
2420
class TestCaseWithMemoryTransport(TestCase):
2214
2421
    """Common test class for tests that do not need disk resources.
2215
2422
 
2216
 
    Tests that need disk resources should derive from TestCaseWithTransport.
 
2423
    Tests that need disk resources should derive from TestCaseInTempDir
 
2424
    orTestCaseWithTransport.
2217
2425
 
2218
2426
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2219
2427
 
2220
 
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
2428
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2221
2429
    a directory which does not exist. This serves to help ensure test isolation
2222
 
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
2223
 
    must exist. However, TestCaseWithMemoryTransport does not offer local
2224
 
    file defaults for the transport in tests, nor does it obey the command line
 
2430
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2431
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2432
    defaults for the transport in tests, nor does it obey the command line
2225
2433
    override, so tests that accidentally write to the common directory should
2226
2434
    be rare.
2227
2435
 
2228
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
2229
 
    a .bzr directory that stops us ascending higher into the filesystem.
 
2436
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2437
        ``.bzr`` directory that stops us ascending higher into the filesystem.
2230
2438
    """
2231
2439
 
2232
2440
    TEST_ROOT = None
2250
2458
 
2251
2459
        :param relpath: a path relative to the base url.
2252
2460
        """
2253
 
        t = get_transport(self.get_url(relpath))
 
2461
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2254
2462
        self.assertFalse(t.is_readonly())
2255
2463
        return t
2256
2464
 
2262
2470
 
2263
2471
        :param relpath: a path relative to the base url.
2264
2472
        """
2265
 
        t = get_transport(self.get_readonly_url(relpath))
 
2473
        t = _mod_transport.get_transport_from_url(
 
2474
            self.get_readonly_url(relpath))
2266
2475
        self.assertTrue(t.is_readonly())
2267
2476
        return t
2268
2477
 
2281
2490
        if self.__readonly_server is None:
2282
2491
            if self.transport_readonly_server is None:
2283
2492
                # readonly decorator requested
2284
 
                self.__readonly_server = ReadonlyServer()
 
2493
                self.__readonly_server = test_server.ReadonlyServer()
2285
2494
            else:
2286
2495
                # explicit readonly transport.
2287
2496
                self.__readonly_server = self.create_transport_readonly_server()
2310
2519
        is no means to override it.
2311
2520
        """
2312
2521
        if self.__vfs_server is None:
2313
 
            self.__vfs_server = MemoryServer()
 
2522
            self.__vfs_server = memory.MemoryServer()
2314
2523
            self.start_server(self.__vfs_server)
2315
2524
        return self.__vfs_server
2316
2525
 
2389
2598
        real branch.
2390
2599
        """
2391
2600
        root = TestCaseWithMemoryTransport.TEST_ROOT
2392
 
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2601
        # Make sure we get a readable and accessible home for .bzr.log
 
2602
        # and/or config files, and not fallback to weird defaults (see
 
2603
        # http://pad.lv/825027).
 
2604
        self.assertIs(None, os.environ.get('BZR_HOME', None))
 
2605
        os.environ['BZR_HOME'] = root
 
2606
        wt = bzrdir.BzrDir.create_standalone_workingtree(root)
 
2607
        del os.environ['BZR_HOME']
 
2608
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2609
        # we don't need to re-open the wt to check it hasn't changed.
 
2610
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2611
            wt.control_transport.get_bytes('dirstate'))
2393
2612
 
2394
2613
    def _check_safety_net(self):
2395
2614
        """Check that the safety .bzr directory have not been touched.
2398
2617
        propagating. This method ensures than a test did not leaked.
2399
2618
        """
2400
2619
        root = TestCaseWithMemoryTransport.TEST_ROOT
2401
 
        self.permit_url(get_transport(root).base)
2402
 
        wt = workingtree.WorkingTree.open(root)
2403
 
        last_rev = wt.last_revision()
2404
 
        if last_rev != 'null:':
 
2620
        t = _mod_transport.get_transport_from_path(root)
 
2621
        self.permit_url(t.base)
 
2622
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2623
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2405
2624
            # The current test have modified the /bzr directory, we need to
2406
2625
            # recreate a new one or all the followng tests will fail.
2407
2626
            # If you need to inspect its content uncomment the following line
2442
2661
    def make_branch(self, relpath, format=None):
2443
2662
        """Create a branch on the transport at relpath."""
2444
2663
        repo = self.make_repository(relpath, format=format)
2445
 
        return repo.bzrdir.create_branch()
 
2664
        return repo.bzrdir.create_branch(append_revisions_only=False)
 
2665
 
 
2666
    def get_default_format(self):
 
2667
        return 'default'
 
2668
 
 
2669
    def resolve_format(self, format):
 
2670
        """Resolve an object to a ControlDir format object.
 
2671
 
 
2672
        The initial format object can either already be
 
2673
        a ControlDirFormat, None (for the default format),
 
2674
        or a string with the name of the control dir format.
 
2675
 
 
2676
        :param format: Object to resolve
 
2677
        :return A ControlDirFormat instance
 
2678
        """
 
2679
        if format is None:
 
2680
            format = self.get_default_format()
 
2681
        if isinstance(format, basestring):
 
2682
            format = bzrdir.format_registry.make_bzrdir(format)
 
2683
        return format
2446
2684
 
2447
2685
    def make_bzrdir(self, relpath, format=None):
2448
2686
        try:
2449
2687
            # might be a relative or absolute path
2450
2688
            maybe_a_url = self.get_url(relpath)
2451
2689
            segments = maybe_a_url.rsplit('/', 1)
2452
 
            t = get_transport(maybe_a_url)
 
2690
            t = _mod_transport.get_transport(maybe_a_url)
2453
2691
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2454
2692
                t.ensure_base()
2455
 
            if format is None:
2456
 
                format = 'default'
2457
 
            if isinstance(format, basestring):
2458
 
                format = bzrdir.format_registry.make_bzrdir(format)
 
2693
            format = self.resolve_format(format)
2459
2694
            return format.initialize_on_transport(t)
2460
2695
        except errors.UninitializableFormat:
2461
2696
            raise TestSkipped("Format %s is not initializable." % format)
2462
2697
 
2463
 
    def make_repository(self, relpath, shared=False, format=None):
 
2698
    def make_repository(self, relpath, shared=None, format=None):
2464
2699
        """Create a repository on our default transport at relpath.
2465
2700
 
2466
2701
        Note that relpath must be a relative path, not a full url.
2472
2707
        made_control = self.make_bzrdir(relpath, format=format)
2473
2708
        return made_control.create_repository(shared=shared)
2474
2709
 
2475
 
    def make_smart_server(self, path):
2476
 
        smart_server = server.SmartTCPServer_for_testing()
2477
 
        self.start_server(smart_server, self.get_server())
2478
 
        remote_transport = get_transport(smart_server.get_url()).clone(path)
 
2710
    def make_smart_server(self, path, backing_server=None):
 
2711
        if backing_server is None:
 
2712
            backing_server = self.get_server()
 
2713
        smart_server = test_server.SmartTCPServer_for_testing()
 
2714
        self.start_server(smart_server, backing_server)
 
2715
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
 
2716
                                                   ).clone(path)
2479
2717
        return remote_transport
2480
2718
 
2481
2719
    def make_branch_and_memory_tree(self, relpath, format=None):
2491
2729
        test_home_dir = self.test_home_dir
2492
2730
        if isinstance(test_home_dir, unicode):
2493
2731
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2494
 
        os.environ['HOME'] = test_home_dir
2495
 
        os.environ['BZR_HOME'] = test_home_dir
 
2732
        self.overrideEnv('HOME', test_home_dir)
 
2733
        self.overrideEnv('BZR_HOME', test_home_dir)
2496
2734
 
2497
2735
    def setUp(self):
2498
2736
        super(TestCaseWithMemoryTransport, self).setUp()
 
2737
        # Ensure that ConnectedTransport doesn't leak sockets
 
2738
        def get_transport_from_url_with_cleanup(*args, **kwargs):
 
2739
            t = orig_get_transport_from_url(*args, **kwargs)
 
2740
            if isinstance(t, _mod_transport.ConnectedTransport):
 
2741
                self.addCleanup(t.disconnect)
 
2742
            return t
 
2743
 
 
2744
        orig_get_transport_from_url = self.overrideAttr(
 
2745
            _mod_transport, 'get_transport_from_url',
 
2746
            get_transport_from_url_with_cleanup)
2499
2747
        self._make_test_root()
2500
 
        _currentdir = os.getcwdu()
2501
 
        def _leaveDirectory():
2502
 
            os.chdir(_currentdir)
2503
 
        self.addCleanup(_leaveDirectory)
 
2748
        self.addCleanup(os.chdir, os.getcwdu())
2504
2749
        self.makeAndChdirToTestDir()
2505
2750
        self.overrideEnvironmentForTesting()
2506
2751
        self.__readonly_server = None
2509
2754
 
2510
2755
    def setup_smart_server_with_call_log(self):
2511
2756
        """Sets up a smart server as the transport server with a call log."""
2512
 
        self.transport_server = server.SmartTCPServer_for_testing
 
2757
        self.transport_server = test_server.SmartTCPServer_for_testing
2513
2758
        self.hpss_calls = []
2514
2759
        import traceback
2515
2760
        # Skip the current stack down to the caller of
2547
2792
 
2548
2793
    OVERRIDE_PYTHON = 'python'
2549
2794
 
 
2795
    def setUp(self):
 
2796
        super(TestCaseInTempDir, self).setUp()
 
2797
        # Remove the protection set in isolated_environ, we have a proper
 
2798
        # access to disk resources now.
 
2799
        self.overrideEnv('BZR_LOG', None)
 
2800
 
2550
2801
    def check_file_contents(self, filename, expect):
2551
2802
        self.log("check contents of file %s" % filename)
2552
 
        contents = file(filename, 'r').read()
 
2803
        f = file(filename)
 
2804
        try:
 
2805
            contents = f.read()
 
2806
        finally:
 
2807
            f.close()
2553
2808
        if contents != expect:
2554
2809
            self.log("expected: %r" % expect)
2555
2810
            self.log("actually: %r" % contents)
2629
2884
                "a list or a tuple. Got %r instead" % (shape,))
2630
2885
        # It's OK to just create them using forward slashes on windows.
2631
2886
        if transport is None or transport.is_readonly():
2632
 
            transport = get_transport(".")
 
2887
            transport = _mod_transport.get_transport_from_path(".")
2633
2888
        for name in shape:
2634
2889
            self.assertIsInstance(name, basestring)
2635
2890
            if name[-1] == '/':
2645
2900
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2646
2901
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2647
2902
 
2648
 
    def build_tree_contents(self, shape):
2649
 
        build_tree_contents(shape)
 
2903
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2650
2904
 
2651
2905
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2652
2906
        """Assert whether path or paths are in the WorkingTree"""
2721
2975
        # this obviously requires a format that supports branch references
2722
2976
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2723
2977
        # RBC 20060208
 
2978
        format = self.resolve_format(format=format)
 
2979
        if not format.supports_workingtrees:
 
2980
            b = self.make_branch(relpath+'.branch', format=format)
 
2981
            return b.create_checkout(relpath, lightweight=True)
2724
2982
        b = self.make_branch(relpath, format=format)
2725
2983
        try:
2726
2984
            return b.bzrdir.create_workingtree()
2728
2986
            # We can only make working trees locally at the moment.  If the
2729
2987
            # transport can't support them, then we keep the non-disk-backed
2730
2988
            # branch and create a local checkout.
2731
 
            if self.vfs_transport_factory is LocalURLServer:
 
2989
            if self.vfs_transport_factory is test_server.LocalURLServer:
2732
2990
                # the branch is colocated on disk, we cannot create a checkout.
2733
2991
                # hopefully callers will expect this.
2734
2992
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2793
3051
    """
2794
3052
 
2795
3053
    def setUp(self):
 
3054
        from bzrlib.tests import http_server
2796
3055
        super(ChrootedTestCase, self).setUp()
2797
 
        if not self.vfs_transport_factory == MemoryServer:
2798
 
            self.transport_readonly_server = HttpServer
 
3056
        if not self.vfs_transport_factory == memory.MemoryServer:
 
3057
            self.transport_readonly_server = http_server.HttpServer
2799
3058
 
2800
3059
 
2801
3060
def condition_id_re(pattern):
2804
3063
    :param pattern: A regular expression string.
2805
3064
    :return: A callable that returns True if the re matches.
2806
3065
    """
2807
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2808
 
        'test filter')
 
3066
    filter_re = re.compile(pattern, 0)
2809
3067
    def condition(test):
2810
3068
        test_id = test.id()
2811
3069
        return filter_re.search(test_id)
3025
3283
                            result_decorators=result_decorators,
3026
3284
                            )
3027
3285
    runner.stop_on_failure=stop_on_failure
 
3286
    if isinstance(suite, unittest.TestSuite):
 
3287
        # Empty out _tests list of passed suite and populate new TestSuite
 
3288
        suite._tests[:], suite = [], TestSuite(suite)
3028
3289
    # built in decorator factories:
3029
3290
    decorators = [
3030
3291
        random_order(random_seed, runner),
3063
3324
 
3064
3325
 
3065
3326
def fork_decorator(suite):
 
3327
    if getattr(os, "fork", None) is None:
 
3328
        raise errors.BzrCommandError("platform does not support fork,"
 
3329
            " try --parallel=subprocess instead.")
3066
3330
    concurrency = osutils.local_concurrency()
3067
3331
    if concurrency == 1:
3068
3332
        return suite
3123
3387
    return suite
3124
3388
 
3125
3389
 
3126
 
class TestDecorator(TestSuite):
 
3390
class TestDecorator(TestUtil.TestSuite):
3127
3391
    """A decorator for TestCase/TestSuite objects.
3128
 
    
3129
 
    Usually, subclasses should override __iter__(used when flattening test
3130
 
    suites), which we do to filter, reorder, parallelise and so on, run() and
3131
 
    debug().
 
3392
 
 
3393
    Contains rather than flattening suite passed on construction
3132
3394
    """
3133
3395
 
3134
 
    def __init__(self, suite):
3135
 
        TestSuite.__init__(self)
3136
 
        self.addTest(suite)
3137
 
 
3138
 
    def countTestCases(self):
3139
 
        cases = 0
3140
 
        for test in self:
3141
 
            cases += test.countTestCases()
3142
 
        return cases
3143
 
 
3144
 
    def debug(self):
3145
 
        for test in self:
3146
 
            test.debug()
3147
 
 
3148
 
    def run(self, result):
3149
 
        # Use iteration on self, not self._tests, to allow subclasses to hook
3150
 
        # into __iter__.
3151
 
        for test in self:
3152
 
            if result.shouldStop:
3153
 
                break
3154
 
            test.run(result)
3155
 
        return result
 
3396
    def __init__(self, suite=None):
 
3397
        super(TestDecorator, self).__init__()
 
3398
        if suite is not None:
 
3399
            self.addTest(suite)
 
3400
 
 
3401
    # Don't need subclass run method with suite emptying
 
3402
    run = unittest.TestSuite.run
3156
3403
 
3157
3404
 
3158
3405
class CountingDecorator(TestDecorator):
3169
3416
    """A decorator which excludes test matching an exclude pattern."""
3170
3417
 
3171
3418
    def __init__(self, suite, exclude_pattern):
3172
 
        TestDecorator.__init__(self, suite)
3173
 
        self.exclude_pattern = exclude_pattern
3174
 
        self.excluded = False
3175
 
 
3176
 
    def __iter__(self):
3177
 
        if self.excluded:
3178
 
            return iter(self._tests)
3179
 
        self.excluded = True
3180
 
        suite = exclude_tests_by_re(self, self.exclude_pattern)
3181
 
        del self._tests[:]
3182
 
        self.addTests(suite)
3183
 
        return iter(self._tests)
 
3419
        super(ExcludeDecorator, self).__init__(
 
3420
            exclude_tests_by_re(suite, exclude_pattern))
3184
3421
 
3185
3422
 
3186
3423
class FilterTestsDecorator(TestDecorator):
3187
3424
    """A decorator which filters tests to those matching a pattern."""
3188
3425
 
3189
3426
    def __init__(self, suite, pattern):
3190
 
        TestDecorator.__init__(self, suite)
3191
 
        self.pattern = pattern
3192
 
        self.filtered = False
3193
 
 
3194
 
    def __iter__(self):
3195
 
        if self.filtered:
3196
 
            return iter(self._tests)
3197
 
        self.filtered = True
3198
 
        suite = filter_suite_by_re(self, self.pattern)
3199
 
        del self._tests[:]
3200
 
        self.addTests(suite)
3201
 
        return iter(self._tests)
 
3427
        super(FilterTestsDecorator, self).__init__(
 
3428
            filter_suite_by_re(suite, pattern))
3202
3429
 
3203
3430
 
3204
3431
class RandomDecorator(TestDecorator):
3205
3432
    """A decorator which randomises the order of its tests."""
3206
3433
 
3207
3434
    def __init__(self, suite, random_seed, stream):
3208
 
        TestDecorator.__init__(self, suite)
3209
 
        self.random_seed = random_seed
3210
 
        self.randomised = False
3211
 
        self.stream = stream
3212
 
 
3213
 
    def __iter__(self):
3214
 
        if self.randomised:
3215
 
            return iter(self._tests)
3216
 
        self.randomised = True
3217
 
        self.stream.writeln("Randomizing test order using seed %s\n" %
3218
 
            (self.actual_seed()))
 
3435
        random_seed = self.actual_seed(random_seed)
 
3436
        stream.write("Randomizing test order using seed %s\n\n" %
 
3437
            (random_seed,))
3219
3438
        # Initialise the random number generator.
3220
 
        random.seed(self.actual_seed())
3221
 
        suite = randomize_suite(self)
3222
 
        del self._tests[:]
3223
 
        self.addTests(suite)
3224
 
        return iter(self._tests)
 
3439
        random.seed(random_seed)
 
3440
        super(RandomDecorator, self).__init__(randomize_suite(suite))
3225
3441
 
3226
 
    def actual_seed(self):
3227
 
        if self.random_seed == "now":
 
3442
    @staticmethod
 
3443
    def actual_seed(seed):
 
3444
        if seed == "now":
3228
3445
            # We convert the seed to a long to make it reuseable across
3229
3446
            # invocations (because the user can reenter it).
3230
 
            self.random_seed = long(time.time())
 
3447
            return long(time.time())
3231
3448
        else:
3232
3449
            # Convert the seed to a long if we can
3233
3450
            try:
3234
 
                self.random_seed = long(self.random_seed)
3235
 
            except:
 
3451
                return long(seed)
 
3452
            except (TypeError, ValueError):
3236
3453
                pass
3237
 
        return self.random_seed
 
3454
        return seed
3238
3455
 
3239
3456
 
3240
3457
class TestFirstDecorator(TestDecorator):
3241
3458
    """A decorator which moves named tests to the front."""
3242
3459
 
3243
3460
    def __init__(self, suite, pattern):
3244
 
        TestDecorator.__init__(self, suite)
3245
 
        self.pattern = pattern
3246
 
        self.filtered = False
3247
 
 
3248
 
    def __iter__(self):
3249
 
        if self.filtered:
3250
 
            return iter(self._tests)
3251
 
        self.filtered = True
3252
 
        suites = split_suite_by_re(self, self.pattern)
3253
 
        del self._tests[:]
3254
 
        self.addTests(suites)
3255
 
        return iter(self._tests)
 
3461
        super(TestFirstDecorator, self).__init__()
 
3462
        self.addTests(split_suite_by_re(suite, pattern))
3256
3463
 
3257
3464
 
3258
3465
def partition_tests(suite, count):
3259
3466
    """Partition suite into count lists of tests."""
3260
 
    result = []
3261
 
    tests = list(iter_suite_tests(suite))
3262
 
    tests_per_process = int(math.ceil(float(len(tests)) / count))
3263
 
    for block in range(count):
3264
 
        low_test = block * tests_per_process
3265
 
        high_test = low_test + tests_per_process
3266
 
        process_tests = tests[low_test:high_test]
3267
 
        result.append(process_tests)
3268
 
    return result
 
3467
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3468
    # splits up blocks of related tests that might run faster if they shared
 
3469
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3470
    # just one partition.  So the slowest partition shouldn't be much slower
 
3471
    # than the fastest.
 
3472
    partitions = [list() for i in range(count)]
 
3473
    tests = iter_suite_tests(suite)
 
3474
    for partition, test in itertools.izip(itertools.cycle(partitions), tests):
 
3475
        partition.append(test)
 
3476
    return partitions
 
3477
 
 
3478
 
 
3479
def workaround_zealous_crypto_random():
 
3480
    """Crypto.Random want to help us being secure, but we don't care here.
 
3481
 
 
3482
    This workaround some test failure related to the sftp server. Once paramiko
 
3483
    stop using the controversial API in Crypto.Random, we may get rid of it.
 
3484
    """
 
3485
    try:
 
3486
        from Crypto.Random import atfork
 
3487
        atfork()
 
3488
    except ImportError:
 
3489
        pass
3269
3490
 
3270
3491
 
3271
3492
def fork_for_tests(suite):
3276
3497
    """
3277
3498
    concurrency = osutils.local_concurrency()
3278
3499
    result = []
3279
 
    from subunit import TestProtocolClient, ProtocolTestCase
 
3500
    from subunit import ProtocolTestCase
 
3501
    from subunit.test_results import AutoTimingTestResultDecorator
3280
3502
    class TestInOtherProcess(ProtocolTestCase):
3281
3503
        # Should be in subunit, I think. RBC.
3282
3504
        def __init__(self, stream, pid):
3287
3509
            try:
3288
3510
                ProtocolTestCase.run(self, result)
3289
3511
            finally:
3290
 
                os.waitpid(self.pid, os.WNOHANG)
 
3512
                pid, status = os.waitpid(self.pid, 0)
 
3513
            # GZ 2011-10-18: If status is nonzero, should report to the result
 
3514
            #                that something went wrong.
3291
3515
 
3292
3516
    test_blocks = partition_tests(suite, concurrency)
 
3517
    # Clear the tests from the original suite so it doesn't keep them alive
 
3518
    suite._tests[:] = []
3293
3519
    for process_tests in test_blocks:
3294
 
        process_suite = TestSuite()
3295
 
        process_suite.addTests(process_tests)
 
3520
        process_suite = TestUtil.TestSuite(process_tests)
 
3521
        # Also clear each split list so new suite has only reference
 
3522
        process_tests[:] = []
3296
3523
        c2pread, c2pwrite = os.pipe()
3297
3524
        pid = os.fork()
3298
3525
        if pid == 0:
3299
3526
            try:
 
3527
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3528
                workaround_zealous_crypto_random()
3300
3529
                os.close(c2pread)
3301
3530
                # Leave stderr and stdout open so we can see test noise
3302
3531
                # Close stdin so that the child goes away if it decides to
3303
3532
                # read from stdin (otherwise its a roulette to see what
3304
3533
                # child actually gets keystrokes for pdb etc).
3305
3534
                sys.stdin.close()
3306
 
                sys.stdin = None
3307
 
                stream = os.fdopen(c2pwrite, 'wb', 1)
3308
 
                subunit_result = BzrAutoTimingTestResultDecorator(
3309
 
                    TestProtocolClient(stream))
 
3535
                subunit_result = AutoTimingTestResultDecorator(
 
3536
                    SubUnitBzrProtocolClient(stream))
3310
3537
                process_suite.run(subunit_result)
3311
 
            finally:
3312
 
                os._exit(0)
 
3538
            except:
 
3539
                # Try and report traceback on stream, but exit with error even
 
3540
                # if stream couldn't be created or something else goes wrong.
 
3541
                # The traceback is formatted to a string and written in one go
 
3542
                # to avoid interleaving lines from multiple failing children.
 
3543
                try:
 
3544
                    stream.write(traceback.format_exc())
 
3545
                finally:
 
3546
                    os._exit(1)
 
3547
            os._exit(0)
3313
3548
        else:
3314
3549
            os.close(c2pwrite)
3315
3550
            stream = os.fdopen(c2pread, 'rb', 1)
3362
3597
                '--subunit']
3363
3598
            if '--no-plugins' in sys.argv:
3364
3599
                argv.append('--no-plugins')
3365
 
            # stderr=STDOUT would be ideal, but until we prevent noise on
3366
 
            # stderr it can interrupt the subunit protocol.
3367
 
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3368
 
                bufsize=1)
 
3600
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3601
            # noise on stderr it can interrupt the subunit protocol.
 
3602
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3603
                                      stdout=subprocess.PIPE,
 
3604
                                      stderr=subprocess.PIPE,
 
3605
                                      bufsize=1)
3369
3606
            test = TestInSubprocess(process, test_list_file_name)
3370
3607
            result.append(test)
3371
3608
        except:
3374
3611
    return result
3375
3612
 
3376
3613
 
3377
 
class ForwardingResult(unittest.TestResult):
3378
 
 
3379
 
    def __init__(self, target):
3380
 
        unittest.TestResult.__init__(self)
3381
 
        self.result = target
3382
 
 
3383
 
    def startTest(self, test):
3384
 
        self.result.startTest(test)
3385
 
 
3386
 
    def stopTest(self, test):
3387
 
        self.result.stopTest(test)
3388
 
 
3389
 
    def startTestRun(self):
3390
 
        self.result.startTestRun()
3391
 
 
3392
 
    def stopTestRun(self):
3393
 
        self.result.stopTestRun()
3394
 
 
3395
 
    def addSkip(self, test, reason):
3396
 
        self.result.addSkip(test, reason)
3397
 
 
3398
 
    def addSuccess(self, test):
3399
 
        self.result.addSuccess(test)
3400
 
 
3401
 
    def addError(self, test, err):
3402
 
        self.result.addError(test, err)
3403
 
 
3404
 
    def addFailure(self, test, err):
3405
 
        self.result.addFailure(test, err)
3406
 
 
3407
 
 
3408
 
class BZRTransformingResult(ForwardingResult):
3409
 
 
3410
 
    def addError(self, test, err):
3411
 
        feature = self._error_looks_like('UnavailableFeature: ', err)
3412
 
        if feature is not None:
3413
 
            self.result.addNotSupported(test, feature)
3414
 
        else:
3415
 
            self.result.addError(test, err)
3416
 
 
3417
 
    def addFailure(self, test, err):
3418
 
        known = self._error_looks_like('KnownFailure: ', err)
3419
 
        if known is not None:
3420
 
            self.result.addExpectedFailure(test,
3421
 
                [KnownFailure, KnownFailure(known), None])
3422
 
        else:
3423
 
            self.result.addFailure(test, err)
3424
 
 
3425
 
    def _error_looks_like(self, prefix, err):
3426
 
        """Deserialize exception and returns the stringify value."""
3427
 
        import subunit
3428
 
        value = None
3429
 
        typ, exc, _ = err
3430
 
        if isinstance(exc, subunit.RemoteException):
3431
 
            # stringify the exception gives access to the remote traceback
3432
 
            # We search the last line for 'prefix'
3433
 
            lines = str(exc).split('\n')
3434
 
            while lines and not lines[-1]:
3435
 
                lines.pop(-1)
3436
 
            if lines:
3437
 
                if lines[-1].startswith(prefix):
3438
 
                    value = lines[-1][len(prefix):]
3439
 
        return value
3440
 
 
3441
 
 
3442
 
try:
3443
 
    from subunit.test_results import AutoTimingTestResultDecorator
3444
 
    # Expected failure should be seen as a success not a failure Once subunit
3445
 
    # provide native support for that, BZRTransformingResult and this class
3446
 
    # will become useless.
3447
 
    class BzrAutoTimingTestResultDecorator(AutoTimingTestResultDecorator):
3448
 
 
3449
 
        def addExpectedFailure(self, test, err):
3450
 
            self._before_event()
3451
 
            return self._call_maybe("addExpectedFailure", self._degrade_skip,
3452
 
                                    test, err)
3453
 
except ImportError:
3454
 
    # Let's just define a no-op decorator
3455
 
    BzrAutoTimingTestResultDecorator = lambda x:x
3456
 
 
3457
 
 
3458
 
class ProfileResult(ForwardingResult):
 
3614
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3459
3615
    """Generate profiling data for all activity between start and success.
3460
3616
    
3461
3617
    The profile data is appended to the test's _benchcalls attribute and can
3469
3625
 
3470
3626
    def startTest(self, test):
3471
3627
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3628
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3629
        # unavoidably fail.
 
3630
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3472
3631
        self.profiler.start()
3473
 
        ForwardingResult.startTest(self, test)
 
3632
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3474
3633
 
3475
3634
    def addSuccess(self, test):
3476
3635
        stats = self.profiler.stop()
3480
3639
            test._benchcalls = []
3481
3640
            calls = test._benchcalls
3482
3641
        calls.append(((test.id(), "", ""), stats))
3483
 
        ForwardingResult.addSuccess(self, test)
 
3642
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3484
3643
 
3485
3644
    def stopTest(self, test):
3486
 
        ForwardingResult.stopTest(self, test)
 
3645
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3487
3646
        self.profiler = None
3488
3647
 
3489
3648
 
3495
3654
#                           rather than failing tests. And no longer raise
3496
3655
#                           LockContention when fctnl locks are not being used
3497
3656
#                           with proper exclusion rules.
 
3657
#   -Ethreads               Will display thread ident at creation/join time to
 
3658
#                           help track thread leaks
 
3659
#   -Euncollected_cases     Display the identity of any test cases that weren't
 
3660
#                           deallocated after being completed.
 
3661
#   -Econfig_stats          Will collect statistics using addDetail
3498
3662
selftest_debug_flags = set()
3499
3663
 
3500
3664
 
3694
3858
                key, obj, help=help, info=info, override_existing=False)
3695
3859
        except KeyError:
3696
3860
            actual = self.get(key)
3697
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3698
 
                 % (key, actual, obj))
 
3861
            trace.note(
 
3862
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3863
                % (key, actual, obj))
3699
3864
 
3700
3865
    def resolve_alias(self, id_start):
3701
3866
        """Replace the alias by the prefix in the given string.
3719
3884
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3720
3885
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3721
3886
 
3722
 
# Obvious higest levels prefixes, feel free to add your own via a plugin
 
3887
# Obvious highest levels prefixes, feel free to add your own via a plugin
3723
3888
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3724
3889
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3725
3890
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3733
3898
        'bzrlib.doc',
3734
3899
        'bzrlib.tests.blackbox',
3735
3900
        'bzrlib.tests.commands',
 
3901
        'bzrlib.tests.doc_generate',
3736
3902
        'bzrlib.tests.per_branch',
3737
3903
        'bzrlib.tests.per_bzrdir',
 
3904
        'bzrlib.tests.per_controldir',
 
3905
        'bzrlib.tests.per_controldir_colo',
3738
3906
        'bzrlib.tests.per_foreign_vcs',
3739
3907
        'bzrlib.tests.per_interrepository',
3740
3908
        'bzrlib.tests.per_intertree',
3741
3909
        'bzrlib.tests.per_inventory',
3742
3910
        'bzrlib.tests.per_interbranch',
3743
3911
        'bzrlib.tests.per_lock',
 
3912
        'bzrlib.tests.per_merger',
3744
3913
        'bzrlib.tests.per_transport',
3745
3914
        'bzrlib.tests.per_tree',
3746
3915
        'bzrlib.tests.per_pack_repository',
3747
3916
        'bzrlib.tests.per_repository',
3748
3917
        'bzrlib.tests.per_repository_chk',
3749
3918
        'bzrlib.tests.per_repository_reference',
 
3919
        'bzrlib.tests.per_repository_vf',
3750
3920
        'bzrlib.tests.per_uifactory',
3751
3921
        'bzrlib.tests.per_versionedfile',
3752
3922
        'bzrlib.tests.per_workingtree',
3753
3923
        'bzrlib.tests.test__annotator',
 
3924
        'bzrlib.tests.test__bencode',
 
3925
        'bzrlib.tests.test__btree_serializer',
3754
3926
        'bzrlib.tests.test__chk_map',
3755
3927
        'bzrlib.tests.test__dirstate_helpers',
3756
3928
        'bzrlib.tests.test__groupcompress',
3764
3936
        'bzrlib.tests.test_api',
3765
3937
        'bzrlib.tests.test_atomicfile',
3766
3938
        'bzrlib.tests.test_bad_files',
3767
 
        'bzrlib.tests.test_bencode',
3768
3939
        'bzrlib.tests.test_bisect_multi',
3769
3940
        'bzrlib.tests.test_branch',
3770
3941
        'bzrlib.tests.test_branchbuilder',
3779
3950
        'bzrlib.tests.test_chunk_writer',
3780
3951
        'bzrlib.tests.test_clean_tree',
3781
3952
        'bzrlib.tests.test_cleanup',
 
3953
        'bzrlib.tests.test_cmdline',
3782
3954
        'bzrlib.tests.test_commands',
3783
3955
        'bzrlib.tests.test_commit',
3784
3956
        'bzrlib.tests.test_commit_merge',
3785
3957
        'bzrlib.tests.test_config',
3786
3958
        'bzrlib.tests.test_conflicts',
 
3959
        'bzrlib.tests.test_controldir',
3787
3960
        'bzrlib.tests.test_counted_lock',
3788
3961
        'bzrlib.tests.test_crash',
3789
3962
        'bzrlib.tests.test_decorators',
3790
3963
        'bzrlib.tests.test_delta',
3791
3964
        'bzrlib.tests.test_debug',
3792
 
        'bzrlib.tests.test_deprecated_graph',
3793
3965
        'bzrlib.tests.test_diff',
3794
3966
        'bzrlib.tests.test_directory_service',
3795
3967
        'bzrlib.tests.test_dirstate',
3796
3968
        'bzrlib.tests.test_email_message',
3797
3969
        'bzrlib.tests.test_eol_filters',
3798
3970
        'bzrlib.tests.test_errors',
 
3971
        'bzrlib.tests.test_estimate_compressed_size',
3799
3972
        'bzrlib.tests.test_export',
 
3973
        'bzrlib.tests.test_export_pot',
3800
3974
        'bzrlib.tests.test_extract',
 
3975
        'bzrlib.tests.test_features',
3801
3976
        'bzrlib.tests.test_fetch',
 
3977
        'bzrlib.tests.test_fixtures',
3802
3978
        'bzrlib.tests.test_fifo_cache',
3803
3979
        'bzrlib.tests.test_filters',
 
3980
        'bzrlib.tests.test_filter_tree',
3804
3981
        'bzrlib.tests.test_ftp_transport',
3805
3982
        'bzrlib.tests.test_foreign',
3806
3983
        'bzrlib.tests.test_generate_docs',
3815
3992
        'bzrlib.tests.test_http',
3816
3993
        'bzrlib.tests.test_http_response',
3817
3994
        'bzrlib.tests.test_https_ca_bundle',
 
3995
        'bzrlib.tests.test_i18n',
3818
3996
        'bzrlib.tests.test_identitymap',
3819
3997
        'bzrlib.tests.test_ignores',
3820
3998
        'bzrlib.tests.test_index',
 
3999
        'bzrlib.tests.test_import_tariff',
3821
4000
        'bzrlib.tests.test_info',
3822
4001
        'bzrlib.tests.test_inv',
3823
4002
        'bzrlib.tests.test_inventory_delta',
3824
4003
        'bzrlib.tests.test_knit',
3825
4004
        'bzrlib.tests.test_lazy_import',
3826
4005
        'bzrlib.tests.test_lazy_regex',
 
4006
        'bzrlib.tests.test_library_state',
3827
4007
        'bzrlib.tests.test_lock',
3828
4008
        'bzrlib.tests.test_lockable_files',
3829
4009
        'bzrlib.tests.test_lockdir',
3831
4011
        'bzrlib.tests.test_lru_cache',
3832
4012
        'bzrlib.tests.test_lsprof',
3833
4013
        'bzrlib.tests.test_mail_client',
 
4014
        'bzrlib.tests.test_matchers',
3834
4015
        'bzrlib.tests.test_memorytree',
3835
4016
        'bzrlib.tests.test_merge',
3836
4017
        'bzrlib.tests.test_merge3',
3837
4018
        'bzrlib.tests.test_merge_core',
3838
4019
        'bzrlib.tests.test_merge_directive',
 
4020
        'bzrlib.tests.test_mergetools',
3839
4021
        'bzrlib.tests.test_missing',
3840
4022
        'bzrlib.tests.test_msgeditor',
3841
4023
        'bzrlib.tests.test_multiparent',
3850
4032
        'bzrlib.tests.test_permissions',
3851
4033
        'bzrlib.tests.test_plugins',
3852
4034
        'bzrlib.tests.test_progress',
 
4035
        'bzrlib.tests.test_pyutils',
3853
4036
        'bzrlib.tests.test_read_bundle',
3854
4037
        'bzrlib.tests.test_reconcile',
3855
4038
        'bzrlib.tests.test_reconfigure',
3864
4047
        'bzrlib.tests.test_rio',
3865
4048
        'bzrlib.tests.test_rules',
3866
4049
        'bzrlib.tests.test_sampler',
 
4050
        'bzrlib.tests.test_scenarios',
3867
4051
        'bzrlib.tests.test_script',
3868
4052
        'bzrlib.tests.test_selftest',
3869
4053
        'bzrlib.tests.test_serializer',
3874
4058
        'bzrlib.tests.test_smart',
3875
4059
        'bzrlib.tests.test_smart_add',
3876
4060
        'bzrlib.tests.test_smart_request',
 
4061
        'bzrlib.tests.test_smart_signals',
3877
4062
        'bzrlib.tests.test_smart_transport',
3878
4063
        'bzrlib.tests.test_smtp_connection',
3879
4064
        'bzrlib.tests.test_source',
3885
4070
        'bzrlib.tests.test_switch',
3886
4071
        'bzrlib.tests.test_symbol_versioning',
3887
4072
        'bzrlib.tests.test_tag',
 
4073
        'bzrlib.tests.test_test_server',
3888
4074
        'bzrlib.tests.test_testament',
3889
4075
        'bzrlib.tests.test_textfile',
3890
4076
        'bzrlib.tests.test_textmerge',
 
4077
        'bzrlib.tests.test_cethread',
3891
4078
        'bzrlib.tests.test_timestamp',
3892
4079
        'bzrlib.tests.test_trace',
3893
4080
        'bzrlib.tests.test_transactions',
3896
4083
        'bzrlib.tests.test_transport_log',
3897
4084
        'bzrlib.tests.test_tree',
3898
4085
        'bzrlib.tests.test_treebuilder',
 
4086
        'bzrlib.tests.test_treeshape',
3899
4087
        'bzrlib.tests.test_tsort',
3900
4088
        'bzrlib.tests.test_tuned_gzip',
3901
4089
        'bzrlib.tests.test_ui',
3903
4091
        'bzrlib.tests.test_upgrade',
3904
4092
        'bzrlib.tests.test_upgrade_stacked',
3905
4093
        'bzrlib.tests.test_urlutils',
 
4094
        'bzrlib.tests.test_utextwrap',
3906
4095
        'bzrlib.tests.test_version',
3907
4096
        'bzrlib.tests.test_version_info',
 
4097
        'bzrlib.tests.test_versionedfile',
 
4098
        'bzrlib.tests.test_vf_search',
3908
4099
        'bzrlib.tests.test_weave',
3909
4100
        'bzrlib.tests.test_whitebox',
3910
4101
        'bzrlib.tests.test_win32utils',
3916
4107
 
3917
4108
 
3918
4109
def _test_suite_modules_to_doctest():
3919
 
    """Return the list of modules to doctest."""   
 
4110
    """Return the list of modules to doctest."""
 
4111
    if __doc__ is None:
 
4112
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
 
4113
        return []
3920
4114
    return [
3921
4115
        'bzrlib',
3922
4116
        'bzrlib.branchbuilder',
3923
 
        'bzrlib.export',
 
4117
        'bzrlib.decorators',
3924
4118
        'bzrlib.inventory',
3925
4119
        'bzrlib.iterablefile',
3926
4120
        'bzrlib.lockdir',
3927
4121
        'bzrlib.merge3',
3928
4122
        'bzrlib.option',
 
4123
        'bzrlib.pyutils',
3929
4124
        'bzrlib.symbol_versioning',
3930
4125
        'bzrlib.tests',
 
4126
        'bzrlib.tests.fixtures',
3931
4127
        'bzrlib.timestamp',
 
4128
        'bzrlib.transport.http',
3932
4129
        'bzrlib.version_info_formats.format_custom',
3933
4130
        ]
3934
4131
 
3987
4184
        try:
3988
4185
            # note that this really does mean "report only" -- doctest
3989
4186
            # still runs the rest of the examples
3990
 
            doc_suite = doctest.DocTestSuite(mod,
3991
 
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4187
            doc_suite = IsolatedDocTestSuite(
 
4188
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3992
4189
        except ValueError, e:
3993
4190
            print '**failed to get doctest for: %s\n%s' % (mod, e)
3994
4191
            raise
3997
4194
        suite.addTest(doc_suite)
3998
4195
 
3999
4196
    default_encoding = sys.getdefaultencoding()
4000
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4197
    for name, plugin in _mod_plugin.plugins().items():
4001
4198
        if not interesting_module(plugin.module.__name__):
4002
4199
            continue
4003
4200
        plugin_suite = plugin.test_suite()
4009
4206
        if plugin_suite is not None:
4010
4207
            suite.addTest(plugin_suite)
4011
4208
        if default_encoding != sys.getdefaultencoding():
4012
 
            bzrlib.trace.warning(
 
4209
            trace.warning(
4013
4210
                'Plugin "%s" tried to reset default encoding to: %s', name,
4014
4211
                sys.getdefaultencoding())
4015
4212
            reload(sys)
4030
4227
            # Some tests mentioned in the list are not in the test suite. The
4031
4228
            # list may be out of date, report to the tester.
4032
4229
            for id in not_found:
4033
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4230
                trace.warning('"%s" not found in the test suite', id)
4034
4231
        for id in duplicates:
4035
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4232
            trace.warning('"%s" is used as an id by several tests', id)
4036
4233
 
4037
4234
    return suite
4038
4235
 
4039
4236
 
4040
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4237
def multiply_scenarios(*scenarios):
 
4238
    """Multiply two or more iterables of scenarios.
 
4239
 
 
4240
    It is safe to pass scenario generators or iterators.
 
4241
 
 
4242
    :returns: A list of compound scenarios: the cross-product of all 
 
4243
        scenarios, with the names concatenated and the parameters
 
4244
        merged together.
 
4245
    """
 
4246
    return reduce(_multiply_two_scenarios, map(list, scenarios))
 
4247
 
 
4248
 
 
4249
def _multiply_two_scenarios(scenarios_left, scenarios_right):
4041
4250
    """Multiply two sets of scenarios.
4042
4251
 
4043
4252
    :returns: the cartesian product of the two sets of scenarios, that is
4074
4283
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
4075
4284
    ...     [('one', dict(param=1)),
4076
4285
    ...      ('two', dict(param=2))],
4077
 
    ...     TestSuite())
 
4286
    ...     TestUtil.TestSuite())
4078
4287
    >>> tests = list(iter_suite_tests(r))
4079
4288
    >>> len(tests)
4080
4289
    2
4127
4336
    :param new_id: The id to assign to it.
4128
4337
    :return: The new test.
4129
4338
    """
4130
 
    new_test = copy(test)
 
4339
    new_test = copy.copy(test)
4131
4340
    new_test.id = lambda: new_id
 
4341
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4342
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4343
    # read the test output for parameterized tests, because tracebacks will be
 
4344
    # associated with irrelevant tests.
 
4345
    try:
 
4346
        details = new_test._TestCase__details
 
4347
    except AttributeError:
 
4348
        # must be a different version of testtools than expected.  Do nothing.
 
4349
        pass
 
4350
    else:
 
4351
        # Reset the '__details' dict.
 
4352
        new_test._TestCase__details = {}
4132
4353
    return new_test
4133
4354
 
4134
4355
 
 
4356
def permute_tests_for_extension(standard_tests, loader, py_module_name,
 
4357
                                ext_module_name):
 
4358
    """Helper for permutating tests against an extension module.
 
4359
 
 
4360
    This is meant to be used inside a modules 'load_tests()' function. It will
 
4361
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
 
4362
    against both implementations. Setting 'test.module' to the appropriate
 
4363
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
 
4364
 
 
4365
    :param standard_tests: A test suite to permute
 
4366
    :param loader: A TestLoader
 
4367
    :param py_module_name: The python path to a python module that can always
 
4368
        be loaded, and will be considered the 'python' implementation. (eg
 
4369
        'bzrlib._chk_map_py')
 
4370
    :param ext_module_name: The python path to an extension module. If the
 
4371
        module cannot be loaded, a single test will be added, which notes that
 
4372
        the module is not available. If it can be loaded, all standard_tests
 
4373
        will be run against that module.
 
4374
    :return: (suite, feature) suite is a test-suite that has all the permuted
 
4375
        tests. feature is the Feature object that can be used to determine if
 
4376
        the module is available.
 
4377
    """
 
4378
 
 
4379
    from bzrlib.tests.features import ModuleAvailableFeature
 
4380
    py_module = pyutils.get_named_object(py_module_name)
 
4381
    scenarios = [
 
4382
        ('python', {'module': py_module}),
 
4383
    ]
 
4384
    suite = loader.suiteClass()
 
4385
    feature = ModuleAvailableFeature(ext_module_name)
 
4386
    if feature.available():
 
4387
        scenarios.append(('C', {'module': feature.module}))
 
4388
    else:
 
4389
        # the compiled module isn't available, so we add a failing test
 
4390
        class FailWithoutFeature(TestCase):
 
4391
            def test_fail(self):
 
4392
                self.requireFeature(feature)
 
4393
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
 
4394
    result = multiply_tests(standard_tests, scenarios, suite)
 
4395
    return result, feature
 
4396
 
 
4397
 
4135
4398
def _rmtree_temp_dir(dirname, test_id=None):
4136
4399
    # If LANG=C we probably have created some bogus paths
4137
4400
    # which rmtree(unicode) will fail to delete
4152
4415
        # possible info to the test runner is even worse.
4153
4416
        if test_id != None:
4154
4417
            ui.ui_factory.clear_term()
4155
 
            sys.stderr.write('While running: %s\n' % (test_id,))
 
4418
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4419
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4420
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4421
                                    ).encode('ascii', 'replace')
4156
4422
        sys.stderr.write('Unable to remove testing dir %s\n%s'
4157
 
                         % (os.path.basename(dirname), e))
4158
 
 
4159
 
 
4160
 
class Feature(object):
4161
 
    """An operating system Feature."""
4162
 
 
4163
 
    def __init__(self):
4164
 
        self._available = None
4165
 
 
4166
 
    def available(self):
4167
 
        """Is the feature available?
4168
 
 
4169
 
        :return: True if the feature is available.
4170
 
        """
4171
 
        if self._available is None:
4172
 
            self._available = self._probe()
4173
 
        return self._available
4174
 
 
4175
 
    def _probe(self):
4176
 
        """Implement this method in concrete features.
4177
 
 
4178
 
        :return: True if the feature is available.
4179
 
        """
4180
 
        raise NotImplementedError
4181
 
 
4182
 
    def __str__(self):
4183
 
        if getattr(self, 'feature_name', None):
4184
 
            return self.feature_name()
4185
 
        return self.__class__.__name__
4186
 
 
4187
 
 
4188
 
class _SymlinkFeature(Feature):
4189
 
 
4190
 
    def _probe(self):
4191
 
        return osutils.has_symlinks()
4192
 
 
4193
 
    def feature_name(self):
4194
 
        return 'symlinks'
4195
 
 
4196
 
SymlinkFeature = _SymlinkFeature()
4197
 
 
4198
 
 
4199
 
class _HardlinkFeature(Feature):
4200
 
 
4201
 
    def _probe(self):
4202
 
        return osutils.has_hardlinks()
4203
 
 
4204
 
    def feature_name(self):
4205
 
        return 'hardlinks'
4206
 
 
4207
 
HardlinkFeature = _HardlinkFeature()
4208
 
 
4209
 
 
4210
 
class _OsFifoFeature(Feature):
4211
 
 
4212
 
    def _probe(self):
4213
 
        return getattr(os, 'mkfifo', None)
4214
 
 
4215
 
    def feature_name(self):
4216
 
        return 'filesystem fifos'
4217
 
 
4218
 
OsFifoFeature = _OsFifoFeature()
4219
 
 
4220
 
 
4221
 
class _UnicodeFilenameFeature(Feature):
4222
 
    """Does the filesystem support Unicode filenames?"""
4223
 
 
4224
 
    def _probe(self):
4225
 
        try:
4226
 
            # Check for character combinations unlikely to be covered by any
4227
 
            # single non-unicode encoding. We use the characters
4228
 
            # - greek small letter alpha (U+03B1) and
4229
 
            # - braille pattern dots-123456 (U+283F).
4230
 
            os.stat(u'\u03b1\u283f')
4231
 
        except UnicodeEncodeError:
4232
 
            return False
4233
 
        except (IOError, OSError):
4234
 
            # The filesystem allows the Unicode filename but the file doesn't
4235
 
            # exist.
4236
 
            return True
4237
 
        else:
4238
 
            # The filesystem allows the Unicode filename and the file exists,
4239
 
            # for some reason.
4240
 
            return True
4241
 
 
4242
 
UnicodeFilenameFeature = _UnicodeFilenameFeature()
 
4423
                         % (os.path.basename(dirname), printable_e))
4243
4424
 
4244
4425
 
4245
4426
def probe_unicode_in_user_encoding():
4275
4456
    return None
4276
4457
 
4277
4458
 
4278
 
class _HTTPSServerFeature(Feature):
4279
 
    """Some tests want an https Server, check if one is available.
4280
 
 
4281
 
    Right now, the only way this is available is under python2.6 which provides
4282
 
    an ssl module.
4283
 
    """
4284
 
 
4285
 
    def _probe(self):
4286
 
        try:
4287
 
            import ssl
4288
 
            return True
4289
 
        except ImportError:
4290
 
            return False
4291
 
 
4292
 
    def feature_name(self):
4293
 
        return 'HTTPSServer'
4294
 
 
4295
 
 
4296
 
HTTPSServerFeature = _HTTPSServerFeature()
4297
 
 
4298
 
 
4299
 
class _ParamikoFeature(Feature):
4300
 
    """Is paramiko available?"""
4301
 
 
4302
 
    def _probe(self):
4303
 
        try:
4304
 
            from bzrlib.transport.sftp import SFTPAbsoluteServer
4305
 
            return True
4306
 
        except errors.ParamikoNotPresent:
4307
 
            return False
4308
 
 
4309
 
    def feature_name(self):
4310
 
        return "Paramiko"
4311
 
 
4312
 
 
4313
 
ParamikoFeature = _ParamikoFeature()
4314
 
 
4315
 
 
4316
 
class _UnicodeFilename(Feature):
4317
 
    """Does the filesystem support Unicode filenames?"""
4318
 
 
4319
 
    def _probe(self):
4320
 
        try:
4321
 
            os.stat(u'\u03b1')
4322
 
        except UnicodeEncodeError:
4323
 
            return False
4324
 
        except (IOError, OSError):
4325
 
            # The filesystem allows the Unicode filename but the file doesn't
4326
 
            # exist.
4327
 
            return True
4328
 
        else:
4329
 
            # The filesystem allows the Unicode filename and the file exists,
4330
 
            # for some reason.
4331
 
            return True
4332
 
 
4333
 
UnicodeFilename = _UnicodeFilename()
4334
 
 
4335
 
 
4336
 
class _UTF8Filesystem(Feature):
4337
 
    """Is the filesystem UTF-8?"""
4338
 
 
4339
 
    def _probe(self):
4340
 
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
4341
 
            return True
4342
 
        return False
4343
 
 
4344
 
UTF8Filesystem = _UTF8Filesystem()
4345
 
 
4346
 
 
4347
 
class _BreakinFeature(Feature):
4348
 
    """Does this platform support the breakin feature?"""
4349
 
 
4350
 
    def _probe(self):
4351
 
        from bzrlib import breakin
4352
 
        if breakin.determine_signal() is None:
4353
 
            return False
4354
 
        if sys.platform == 'win32':
4355
 
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
4356
 
            # We trigger SIGBREAK via a Console api so we need ctypes to
4357
 
            # access the function
4358
 
            try:
4359
 
                import ctypes
4360
 
            except OSError:
4361
 
                return False
4362
 
        return True
4363
 
 
4364
 
    def feature_name(self):
4365
 
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
4366
 
 
4367
 
 
4368
 
BreakinFeature = _BreakinFeature()
4369
 
 
4370
 
 
4371
 
class _CaseInsCasePresFilenameFeature(Feature):
4372
 
    """Is the file-system case insensitive, but case-preserving?"""
4373
 
 
4374
 
    def _probe(self):
4375
 
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
4376
 
        try:
4377
 
            # first check truly case-preserving for created files, then check
4378
 
            # case insensitive when opening existing files.
4379
 
            name = osutils.normpath(name)
4380
 
            base, rel = osutils.split(name)
4381
 
            found_rel = osutils.canonical_relpath(base, name)
4382
 
            return (found_rel == rel
4383
 
                    and os.path.isfile(name.upper())
4384
 
                    and os.path.isfile(name.lower()))
4385
 
        finally:
4386
 
            os.close(fileno)
4387
 
            os.remove(name)
4388
 
 
4389
 
    def feature_name(self):
4390
 
        return "case-insensitive case-preserving filesystem"
4391
 
 
4392
 
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
4393
 
 
4394
 
 
4395
 
class _CaseInsensitiveFilesystemFeature(Feature):
4396
 
    """Check if underlying filesystem is case-insensitive but *not* case
4397
 
    preserving.
4398
 
    """
4399
 
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
4400
 
    # more likely to be case preserving, so this case is rare.
4401
 
 
4402
 
    def _probe(self):
4403
 
        if CaseInsCasePresFilenameFeature.available():
4404
 
            return False
4405
 
 
4406
 
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
4407
 
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
4408
 
            TestCaseWithMemoryTransport.TEST_ROOT = root
4409
 
        else:
4410
 
            root = TestCaseWithMemoryTransport.TEST_ROOT
4411
 
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
4412
 
            dir=root)
4413
 
        name_a = osutils.pathjoin(tdir, 'a')
4414
 
        name_A = osutils.pathjoin(tdir, 'A')
4415
 
        os.mkdir(name_a)
4416
 
        result = osutils.isdir(name_A)
4417
 
        _rmtree_temp_dir(tdir)
4418
 
        return result
4419
 
 
4420
 
    def feature_name(self):
4421
 
        return 'case-insensitive filesystem'
4422
 
 
4423
 
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
4424
 
 
4425
 
 
4426
 
class _SubUnitFeature(Feature):
4427
 
    """Check if subunit is available."""
4428
 
 
4429
 
    def _probe(self):
4430
 
        try:
4431
 
            import subunit
4432
 
            return True
4433
 
        except ImportError:
4434
 
            return False
4435
 
 
4436
 
    def feature_name(self):
4437
 
        return 'subunit'
4438
 
 
4439
 
SubUnitFeature = _SubUnitFeature()
4440
4459
# Only define SubUnitBzrRunner if subunit is available.
4441
4460
try:
4442
4461
    from subunit import TestProtocolClient
 
4462
    from subunit.test_results import AutoTimingTestResultDecorator
 
4463
    class SubUnitBzrProtocolClient(TestProtocolClient):
 
4464
 
 
4465
        def stopTest(self, test):
 
4466
            super(SubUnitBzrProtocolClient, self).stopTest(test)
 
4467
            _clear__type_equality_funcs(test)
 
4468
 
 
4469
        def addSuccess(self, test, details=None):
 
4470
            # The subunit client always includes the details in the subunit
 
4471
            # stream, but we don't want to include it in ours.
 
4472
            if details is not None and 'log' in details:
 
4473
                del details['log']
 
4474
            return super(SubUnitBzrProtocolClient, self).addSuccess(
 
4475
                test, details)
 
4476
 
4443
4477
    class SubUnitBzrRunner(TextTestRunner):
4444
4478
        def run(self, test):
4445
 
            result = BzrAutoTimingTestResultDecorator(
4446
 
                TestProtocolClient(self.stream))
 
4479
            result = AutoTimingTestResultDecorator(
 
4480
                SubUnitBzrProtocolClient(self.stream))
4447
4481
            test.run(result)
4448
4482
            return result
4449
4483
except ImportError:
4450
4484
    pass
 
4485
 
 
4486
 
 
4487
# API compatibility for old plugins; see bug 892622.
 
4488
for name in [
 
4489
    'Feature',
 
4490
    'HTTPServerFeature', 
 
4491
    'ModuleAvailableFeature',
 
4492
    'HTTPSServerFeature', 'SymlinkFeature', 'HardlinkFeature',
 
4493
    'OsFifoFeature', 'UnicodeFilenameFeature',
 
4494
    'ByteStringNamedFilesystem', 'UTF8Filesystem',
 
4495
    'BreakinFeature', 'CaseInsCasePresFilenameFeature',
 
4496
    'CaseInsensitiveFilesystemFeature', 'case_sensitive_filesystem_feature',
 
4497
    'posix_permissions_feature',
 
4498
    ]:
 
4499
    globals()[name] = _CompatabilityThunkFeature(
 
4500
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4501
        'bzrlib.tests', name,
 
4502
        name, 'bzrlib.tests.features')
 
4503
 
 
4504
 
 
4505
for (old_name, new_name) in [
 
4506
    ('UnicodeFilename', 'UnicodeFilenameFeature'),
 
4507
    ]:
 
4508
    globals()[name] = _CompatabilityThunkFeature(
 
4509
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4510
        'bzrlib.tests', old_name,
 
4511
        new_name, 'bzrlib.tests.features')