~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2013, 2015, 2016 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
"""Testing framework extensions"""
18
 
 
19
 
from __future__ import absolute_import
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
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)
20
23
 
21
24
# NOTE: Some classes in here use camelCaseNaming() rather than
22
25
# underscore_naming().  That's for consistency with unittest; it's not the
25
28
 
26
29
import atexit
27
30
import codecs
28
 
import copy
29
31
from cStringIO import StringIO
30
32
import difflib
31
33
import doctest
32
34
import errno
33
 
import itertools
34
35
import logging
35
 
import math
36
36
import os
37
 
import platform
38
 
import pprint
 
37
from pprint import pformat
39
38
import random
40
39
import re
41
40
import shlex
42
 
import site
43
41
import stat
44
 
import subprocess
 
42
from subprocess import Popen, PIPE
45
43
import sys
46
44
import tempfile
47
45
import threading
48
46
import time
49
 
import traceback
50
47
import unittest
51
48
import warnings
52
49
 
53
 
import testtools
54
 
# nb: check this before importing anything else from within it
55
 
_testtools_version = getattr(testtools, '__version__', ())
56
 
if _testtools_version < (0, 9, 5):
57
 
    raise ImportError("need at least testtools 0.9.5: %s is %r"
58
 
        % (testtools.__file__, _testtools_version))
59
 
from testtools import content
60
50
 
61
 
import bzrlib
62
51
from bzrlib import (
63
52
    branchbuilder,
64
 
    controldir,
65
 
    chk_map,
66
 
    commands as _mod_commands,
67
 
    config,
68
 
    i18n,
 
53
    bzrdir,
69
54
    debug,
70
55
    errors,
71
 
    hooks,
72
 
    lock as _mod_lock,
73
 
    lockdir,
74
56
    memorytree,
75
57
    osutils,
76
 
    plugin as _mod_plugin,
77
 
    pyutils,
 
58
    progress,
78
59
    ui,
79
60
    urlutils,
80
61
    registry,
81
 
    symbol_versioning,
82
 
    trace,
83
 
    transport as _mod_transport,
84
62
    workingtree,
85
63
    )
 
64
import bzrlib.branch
 
65
import bzrlib.commands
 
66
import bzrlib.timestamp
 
67
import bzrlib.export
 
68
import bzrlib.inventory
 
69
import bzrlib.iterablefile
 
70
import bzrlib.lockdir
86
71
try:
87
72
    import bzrlib.lsprof
88
73
except ImportError:
89
74
    # lsprof not available
90
75
    pass
91
 
from bzrlib.smart import client, request
92
 
from bzrlib.transport import (
93
 
    memory,
94
 
    pathfilter,
95
 
    )
 
76
from bzrlib.merge import merge_inner
 
77
import bzrlib.merge3
 
78
import bzrlib.plugin
 
79
import bzrlib.store
 
80
from bzrlib import symbol_versioning
96
81
from bzrlib.symbol_versioning import (
 
82
    DEPRECATED_PARAMETER,
97
83
    deprecated_function,
98
 
    deprecated_in,
99
 
    )
100
 
from bzrlib.tests import (
101
 
    fixtures,
102
 
    test_server,
103
 
    TestUtil,
104
 
    treeshape,
105
 
    )
106
 
from bzrlib.ui import NullProgressView
107
 
from bzrlib.ui.text import TextUIFactory
108
 
from bzrlib.tests.features import _CompatabilityThunkFeature
 
84
    deprecated_method,
 
85
    deprecated_passed,
 
86
    )
 
87
import bzrlib.trace
 
88
from bzrlib.transport import get_transport
 
89
import bzrlib.transport
 
90
from bzrlib.transport.local import LocalURLServer
 
91
from bzrlib.transport.memory import MemoryServer
 
92
from bzrlib.transport.readonly import ReadonlyServer
 
93
from bzrlib.trace import mutter, note
 
94
from bzrlib.tests import TestUtil
 
95
from bzrlib.tests.http_server import HttpServer
 
96
from bzrlib.tests.TestUtil import (
 
97
                          TestSuite,
 
98
                          TestLoader,
 
99
                          )
 
100
from bzrlib.tests.treeshape import build_tree_contents
 
101
import bzrlib.version_info_formats.format_custom
 
102
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
109
103
 
110
104
# Mark this python module as being part of the implementation
111
105
# of unittest: this gives us better tracebacks where the last
112
106
# shown frame is the test code, not our assertXYZ.
113
107
__unittest = 1
114
108
 
115
 
default_transport = test_server.LocalURLServer
116
 
 
117
 
 
118
 
_unitialized_attr = object()
119
 
"""A sentinel needed to act as a default value in a method signature."""
120
 
 
121
 
 
122
 
# Subunit result codes, defined here to prevent a hard dependency on subunit.
123
 
SUBUNIT_SEEK_SET = 0
124
 
SUBUNIT_SEEK_CUR = 1
125
 
 
126
 
# These are intentionally brought into this namespace. That way plugins, etc
127
 
# can just "from bzrlib.tests import TestCase, TestLoader, etc"
128
 
TestSuite = TestUtil.TestSuite
129
 
TestLoader = TestUtil.TestLoader
130
 
 
131
 
# Tests should run in a clean and clearly defined environment. The goal is to
132
 
# keep them isolated from the running environment as mush as possible. The test
133
 
# framework ensures the variables defined below are set (or deleted if the
134
 
# value is None) before a test is run and reset to their original value after
135
 
# the test is run. Generally if some code depends on an environment variable,
136
 
# the tests should start without this variable in the environment. There are a
137
 
# few exceptions but you shouldn't violate this rule lightly.
138
 
isolated_environ = {
139
 
    'BZR_HOME': None,
140
 
    'HOME': None,
141
 
    'XDG_CONFIG_HOME': None,
142
 
    # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
143
 
    # tests do check our impls match APPDATA
144
 
    'BZR_EDITOR': None, # test_msgeditor manipulates this variable
145
 
    'VISUAL': None,
146
 
    'EDITOR': None,
147
 
    'BZR_EMAIL': None,
148
 
    'BZREMAIL': None, # may still be present in the environment
149
 
    'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
150
 
    'BZR_PROGRESS_BAR': None,
151
 
    # This should trap leaks to ~/.bzr.log. This occurs when tests use TestCase
152
 
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
153
 
    # TestCase should not use disk resources, BZR_LOG is one.
154
 
    'BZR_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
155
 
    'BZR_PLUGIN_PATH': None,
156
 
    'BZR_DISABLE_PLUGINS': None,
157
 
    'BZR_PLUGINS_AT': None,
158
 
    'BZR_CONCURRENCY': None,
159
 
    # Make sure that any text ui tests are consistent regardless of
160
 
    # the environment the test case is run in; you may want tests that
161
 
    # test other combinations.  'dumb' is a reasonable guess for tests
162
 
    # going to a pipe or a StringIO.
163
 
    'TERM': 'dumb',
164
 
    'LINES': '25',
165
 
    'COLUMNS': '80',
166
 
    'BZR_COLUMNS': '80',
167
 
    # Disable SSH Agent
168
 
    'SSH_AUTH_SOCK': None,
169
 
    # Proxies
170
 
    'http_proxy': None,
171
 
    'HTTP_PROXY': None,
172
 
    'https_proxy': None,
173
 
    'HTTPS_PROXY': None,
174
 
    'no_proxy': None,
175
 
    'NO_PROXY': None,
176
 
    'all_proxy': None,
177
 
    'ALL_PROXY': None,
178
 
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
179
 
    # least. If you do (care), please update this comment
180
 
    # -- vila 20080401
181
 
    'ftp_proxy': None,
182
 
    'FTP_PROXY': None,
183
 
    'BZR_REMOTE_PATH': None,
184
 
    # Generally speaking, we don't want apport reporting on crashes in
185
 
    # the test envirnoment unless we're specifically testing apport,
186
 
    # so that it doesn't leak into the real system environment.  We
187
 
    # use an env var so it propagates to subprocesses.
188
 
    'APPORT_DISABLE': '1',
189
 
    }
190
 
 
191
 
 
192
 
def override_os_environ(test, env=None):
193
 
    """Modify os.environ keeping a copy.
194
 
    
195
 
    :param test: A test instance
196
 
 
197
 
    :param env: A dict containing variable definitions to be installed
198
 
    """
199
 
    if env is None:
200
 
        env = isolated_environ
201
 
    test._original_os_environ = dict([(var, value)
202
 
                                      for var, value in os.environ.iteritems()])
203
 
    for var, value in env.iteritems():
204
 
        osutils.set_or_unset_env(var, value)
205
 
        if var not in test._original_os_environ:
206
 
            # The var is new, add it with a value of None, so
207
 
            # restore_os_environ will delete it
208
 
            test._original_os_environ[var] = None
209
 
 
210
 
 
211
 
def restore_os_environ(test):
212
 
    """Restore os.environ to its original state.
213
 
 
214
 
    :param test: A test instance previously passed to override_os_environ.
215
 
    """
216
 
    for var, value in test._original_os_environ.iteritems():
217
 
        # Restore the original value (or delete it if the value has been set to
218
 
        # None in override_os_environ).
219
 
        osutils.set_or_unset_env(var, value)
220
 
 
221
 
 
222
 
def _clear__type_equality_funcs(test):
223
 
    """Cleanup bound methods stored on TestCase instances
224
 
 
225
 
    Clear the dict breaking a few (mostly) harmless cycles in the affected
226
 
    unittests released with Python 2.6 and initial Python 2.7 versions.
227
 
 
228
 
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
229
 
    shipped in Oneiric, an object with no clear method was used, hence the
230
 
    extra complications, see bug 809048 for details.
231
 
    """
232
 
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
233
 
    if type_equality_funcs is not None:
234
 
        tef_clear = getattr(type_equality_funcs, "clear", None)
235
 
        if tef_clear is None:
236
 
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
237
 
            if tef_instance_dict is not None:
238
 
                tef_clear = tef_instance_dict.clear
239
 
        if tef_clear is not None:
240
 
            tef_clear()
241
 
 
242
 
 
243
 
class ExtendedTestResult(testtools.TextTestResult):
 
109
default_transport = LocalURLServer
 
110
 
 
111
 
 
112
class ExtendedTestResult(unittest._TextTestResult):
244
113
    """Accepts, reports and accumulates the results of running tests.
245
114
 
246
115
    Compared to the unittest version this class adds support for
249
118
    different types of display.
250
119
 
251
120
    When a test finishes, in whatever way, it calls one of the addSuccess,
252
 
    addFailure or addError methods.  These in turn may redirect to a more
 
121
    addFailure or addError classes.  These in turn may redirect to a more
253
122
    specific case for the special test results supported by our extended
254
123
    tests.
255
124
 
257
126
    """
258
127
 
259
128
    stop_early = False
260
 
 
 
129
    
261
130
    def __init__(self, stream, descriptions, verbosity,
262
131
                 bench_history=None,
263
 
                 strict=False,
 
132
                 num_tests=None,
264
133
                 ):
265
134
        """Construct new TestResult.
266
135
 
267
136
        :param bench_history: Optionally, a writable file object to accumulate
268
137
            benchmark results.
269
138
        """
270
 
        testtools.TextTestResult.__init__(self, stream)
 
139
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
271
140
        if bench_history is not None:
272
141
            from bzrlib.version import _get_bzr_source_tree
273
142
            src_tree = _get_bzr_source_tree()
284
153
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
285
154
        self._bench_history = bench_history
286
155
        self.ui = ui.ui_factory
287
 
        self.num_tests = 0
 
156
        self.num_tests = num_tests
288
157
        self.error_count = 0
289
158
        self.failure_count = 0
290
159
        self.known_failure_count = 0
293
162
        self.unsupported = {}
294
163
        self.count = 0
295
164
        self._overall_start_time = time.time()
296
 
        self._strict = strict
297
 
        self._first_thread_leaker_id = None
298
 
        self._tests_leaking_threads_count = 0
299
 
        self._traceback_from_test = None
300
 
 
301
 
    def stopTestRun(self):
302
 
        run = self.testsRun
303
 
        actionTaken = "Ran"
304
 
        stopTime = time.time()
305
 
        timeTaken = stopTime - self.startTime
306
 
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
307
 
        #                the parent class method is similar have to duplicate
308
 
        self._show_list('ERROR', self.errors)
309
 
        self._show_list('FAIL', self.failures)
310
 
        self.stream.write(self.sep2)
311
 
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
312
 
                            run, run != 1 and "s" or "", timeTaken))
313
 
        if not self.wasSuccessful():
314
 
            self.stream.write("FAILED (")
315
 
            failed, errored = map(len, (self.failures, self.errors))
316
 
            if failed:
317
 
                self.stream.write("failures=%d" % failed)
318
 
            if errored:
319
 
                if failed: self.stream.write(", ")
320
 
                self.stream.write("errors=%d" % errored)
321
 
            if self.known_failure_count:
322
 
                if failed or errored: self.stream.write(", ")
323
 
                self.stream.write("known_failure_count=%d" %
324
 
                    self.known_failure_count)
325
 
            self.stream.write(")\n")
326
 
        else:
327
 
            if self.known_failure_count:
328
 
                self.stream.write("OK (known_failures=%d)\n" %
329
 
                    self.known_failure_count)
330
 
            else:
331
 
                self.stream.write("OK\n")
332
 
        if self.skip_count > 0:
333
 
            skipped = self.skip_count
334
 
            self.stream.write('%d test%s skipped\n' %
335
 
                                (skipped, skipped != 1 and "s" or ""))
336
 
        if self.unsupported:
337
 
            for feature, count in sorted(self.unsupported.items()):
338
 
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
339
 
                    (feature, count))
340
 
        if self._strict:
341
 
            ok = self.wasStrictlySuccessful()
342
 
        else:
343
 
            ok = self.wasSuccessful()
344
 
        if self._first_thread_leaker_id:
345
 
            self.stream.write(
346
 
                '%s is leaking threads among %d leaking tests.\n' % (
347
 
                self._first_thread_leaker_id,
348
 
                self._tests_leaking_threads_count))
349
 
            # We don't report the main thread as an active one.
350
 
            self.stream.write(
351
 
                '%d non-main threads were left active in the end.\n'
352
 
                % (len(self._active_threads) - 1))
353
 
 
354
 
    def getDescription(self, test):
355
 
        return test.id()
356
 
 
357
 
    def _extractBenchmarkTime(self, testCase, details=None):
 
165
    
 
166
    def _extractBenchmarkTime(self, testCase):
358
167
        """Add a benchmark time for the current test case."""
359
 
        if details and 'benchtime' in details:
360
 
            return float(''.join(details['benchtime'].iter_bytes()))
361
168
        return getattr(testCase, "_benchtime", None)
362
 
 
363
 
    def _delta_to_float(self, a_timedelta, precision):
364
 
        # This calls ceiling to ensure that the most pessimistic view of time
365
 
        # taken is shown (rather than leaving it to the Python %f operator
366
 
        # to decide whether to round/floor/ceiling. This was added when we
367
 
        # had pyp3 test failures that suggest a floor was happening.
368
 
        shift = 10 ** precision
369
 
        return math.ceil((a_timedelta.days * 86400.0 + a_timedelta.seconds +
370
 
            a_timedelta.microseconds / 1000000.0) * shift) / shift
371
 
 
 
169
    
372
170
    def _elapsedTestTimeString(self):
373
171
        """Return a time string for the overall time the current test has taken."""
374
 
        return self._formatTime(self._delta_to_float(
375
 
            self._now() - self._start_datetime, 3))
 
172
        return self._formatTime(time.time() - self._start_time)
376
173
 
377
174
    def _testTimeString(self, testCase):
378
175
        benchmark_time = self._extractBenchmarkTime(testCase)
379
176
        if benchmark_time is not None:
380
 
            return self._formatTime(benchmark_time) + "*"
 
177
            return "%s/%s" % (
 
178
                self._formatTime(benchmark_time),
 
179
                self._elapsedTestTimeString())
381
180
        else:
382
 
            return self._elapsedTestTimeString()
 
181
            return "           %s" % self._elapsedTestTimeString()
383
182
 
384
183
    def _formatTime(self, seconds):
385
184
        """Format seconds as milliseconds with leading spaces."""
389
188
 
390
189
    def _shortened_test_description(self, test):
391
190
        what = test.id()
392
 
        what = re.sub(r'^bzrlib\.tests\.', '', what)
 
191
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
393
192
        return what
394
193
 
395
 
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
396
 
    #                multiple times in a row, because the handler is added for
397
 
    #                each test but the container list is shared between cases.
398
 
    #                See lp:498869 lp:625574 and lp:637725 for background.
399
 
    def _record_traceback_from_test(self, exc_info):
400
 
        """Store the traceback from passed exc_info tuple till"""
401
 
        self._traceback_from_test = exc_info[2]
402
 
 
403
194
    def startTest(self, test):
404
 
        super(ExtendedTestResult, self).startTest(test)
405
 
        if self.count == 0:
406
 
            self.startTests()
407
 
        self.count += 1
 
195
        unittest.TestResult.startTest(self, test)
408
196
        self.report_test_start(test)
409
197
        test.number = self.count
410
198
        self._recordTestStartTime()
411
 
        # Make testtools cases give us the real traceback on failure
412
 
        addOnException = getattr(test, "addOnException", None)
413
 
        if addOnException is not None:
414
 
            addOnException(self._record_traceback_from_test)
415
 
        # Only check for thread leaks on bzrlib derived test cases
416
 
        if isinstance(test, TestCase):
417
 
            test.addCleanup(self._check_leaked_threads, test)
418
 
 
419
 
    def stopTest(self, test):
420
 
        super(ExtendedTestResult, self).stopTest(test)
421
 
        # Manually break cycles, means touching various private things but hey
422
 
        getDetails = getattr(test, "getDetails", None)
423
 
        if getDetails is not None:
424
 
            getDetails().clear()
425
 
        _clear__type_equality_funcs(test)
426
 
        self._traceback_from_test = None
427
 
 
428
 
    def startTests(self):
429
 
        self.report_tests_starting()
430
 
        self._active_threads = threading.enumerate()
431
 
 
432
 
    def _check_leaked_threads(self, test):
433
 
        """See if any threads have leaked since last call
434
 
 
435
 
        A sample of live threads is stored in the _active_threads attribute,
436
 
        when this method runs it compares the current live threads and any not
437
 
        in the previous sample are treated as having leaked.
438
 
        """
439
 
        now_active_threads = set(threading.enumerate())
440
 
        threads_leaked = now_active_threads.difference(self._active_threads)
441
 
        if threads_leaked:
442
 
            self._report_thread_leak(test, threads_leaked, now_active_threads)
443
 
            self._tests_leaking_threads_count += 1
444
 
            if self._first_thread_leaker_id is None:
445
 
                self._first_thread_leaker_id = test.id()
446
 
            self._active_threads = now_active_threads
447
199
 
448
200
    def _recordTestStartTime(self):
449
201
        """Record that a test has started."""
450
 
        self._start_datetime = self._now()
 
202
        self._start_time = time.time()
 
203
 
 
204
    def _cleanupLogFile(self, test):
 
205
        # We can only do this if we have one of our TestCases, not if
 
206
        # we have a doctest.
 
207
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
 
208
        if setKeepLogfile is not None:
 
209
            setKeepLogfile()
451
210
 
452
211
    def addError(self, test, err):
453
212
        """Tell result that test finished with an error.
455
214
        Called from the TestCase run() method when the test
456
215
        fails with an unexpected error.
457
216
        """
458
 
        self._post_mortem(self._traceback_from_test)
459
 
        super(ExtendedTestResult, self).addError(test, err)
460
 
        self.error_count += 1
461
 
        self.report_error(test, err)
462
 
        if self.stop_early:
463
 
            self.stop()
 
217
        self._testConcluded(test)
 
218
        if isinstance(err[1], TestSkipped):
 
219
            return self._addSkipped(test, err)
 
220
        elif isinstance(err[1], UnavailableFeature):
 
221
            return self.addNotSupported(test, err[1].args[0])
 
222
        else:
 
223
            unittest.TestResult.addError(self, test, err)
 
224
            self.error_count += 1
 
225
            self.report_error(test, err)
 
226
            if self.stop_early:
 
227
                self.stop()
 
228
            self._cleanupLogFile(test)
464
229
 
465
230
    def addFailure(self, test, err):
466
231
        """Tell result that test failed.
468
233
        Called from the TestCase run() method when the test
469
234
        fails because e.g. an assert() method failed.
470
235
        """
471
 
        self._post_mortem(self._traceback_from_test)
472
 
        super(ExtendedTestResult, self).addFailure(test, err)
473
 
        self.failure_count += 1
474
 
        self.report_failure(test, err)
475
 
        if self.stop_early:
476
 
            self.stop()
 
236
        self._testConcluded(test)
 
237
        if isinstance(err[1], KnownFailure):
 
238
            return self._addKnownFailure(test, err)
 
239
        else:
 
240
            unittest.TestResult.addFailure(self, test, err)
 
241
            self.failure_count += 1
 
242
            self.report_failure(test, err)
 
243
            if self.stop_early:
 
244
                self.stop()
 
245
            self._cleanupLogFile(test)
477
246
 
478
 
    def addSuccess(self, test, details=None):
 
247
    def addSuccess(self, test):
479
248
        """Tell result that test completed successfully.
480
249
 
481
250
        Called from the TestCase run()
482
251
        """
 
252
        self._testConcluded(test)
483
253
        if self._bench_history is not None:
484
 
            benchmark_time = self._extractBenchmarkTime(test, details)
 
254
            benchmark_time = self._extractBenchmarkTime(test)
485
255
            if benchmark_time is not None:
486
256
                self._bench_history.write("%s %s\n" % (
487
257
                    self._formatTime(benchmark_time),
488
258
                    test.id()))
489
259
        self.report_success(test)
490
 
        super(ExtendedTestResult, self).addSuccess(test)
 
260
        self._cleanupLogFile(test)
 
261
        unittest.TestResult.addSuccess(self, test)
491
262
        test._log_contents = ''
492
263
 
493
 
    def addExpectedFailure(self, test, err):
 
264
    def _testConcluded(self, test):
 
265
        """Common code when a test has finished.
 
266
 
 
267
        Called regardless of whether it succeded, failed, etc.
 
268
        """
 
269
        pass
 
270
 
 
271
    def _addKnownFailure(self, test, err):
494
272
        self.known_failure_count += 1
495
273
        self.report_known_failure(test, err)
496
274
 
497
 
    def addUnexpectedSuccess(self, test, details=None):
498
 
        """Tell result the test unexpectedly passed, counting as a failure
499
 
 
500
 
        When the minimum version of testtools required becomes 0.9.8 this
501
 
        can be updated to use the new handling there.
502
 
        """
503
 
        super(ExtendedTestResult, self).addFailure(test, details=details)
504
 
        self.failure_count += 1
505
 
        self.report_unexpected_success(test,
506
 
            "".join(details["reason"].iter_text()))
507
 
        if self.stop_early:
508
 
            self.stop()
509
 
 
510
275
    def addNotSupported(self, test, feature):
511
276
        """The test will not be run because of a missing feature.
512
277
        """
513
278
        # this can be called in two different ways: it may be that the
514
 
        # test started running, and then raised (through requireFeature)
 
279
        # test started running, and then raised (through addError) 
515
280
        # UnavailableFeature.  Alternatively this method can be called
516
 
        # while probing for features before running the test code proper; in
517
 
        # that case we will see startTest and stopTest, but the test will
518
 
        # never actually run.
 
281
        # while probing for features before running the tests; in that
 
282
        # case we will see startTest and stopTest, but the test will never
 
283
        # actually run.
519
284
        self.unsupported.setdefault(str(feature), 0)
520
285
        self.unsupported[str(feature)] += 1
521
286
        self.report_unsupported(test, feature)
522
287
 
523
 
    def addSkip(self, test, reason):
524
 
        """A test has not run for 'reason'."""
525
 
        self.skip_count += 1
526
 
        self.report_skip(test, reason)
527
 
 
528
 
    def addNotApplicable(self, test, reason):
529
 
        self.not_applicable_count += 1
530
 
        self.report_not_applicable(test, reason)
531
 
 
532
 
    def _count_stored_tests(self):
533
 
        """Count of tests instances kept alive due to not succeeding"""
534
 
        return self.error_count + self.failure_count + self.known_failure_count
535
 
 
536
 
    def _post_mortem(self, tb=None):
537
 
        """Start a PDB post mortem session."""
538
 
        if os.environ.get('BZR_TEST_PDB', None):
539
 
            import pdb
540
 
            pdb.post_mortem(tb)
541
 
 
542
 
    def progress(self, offset, whence):
543
 
        """The test is adjusting the count of tests to run."""
544
 
        if whence == SUBUNIT_SEEK_SET:
545
 
            self.num_tests = offset
546
 
        elif whence == SUBUNIT_SEEK_CUR:
547
 
            self.num_tests += offset
548
 
        else:
549
 
            raise errors.BzrError("Unknown whence %r" % whence)
550
 
 
551
 
    def report_tests_starting(self):
552
 
        """Display information before the test run begins"""
553
 
        if getattr(sys, 'frozen', None) is None:
554
 
            bzr_path = osutils.realpath(sys.argv[0])
555
 
        else:
556
 
            bzr_path = sys.executable
557
 
        self.stream.write(
558
 
            'bzr selftest: %s\n' % (bzr_path,))
559
 
        self.stream.write(
560
 
            '   %s\n' % (
561
 
                    bzrlib.__path__[0],))
562
 
        self.stream.write(
563
 
            '   bzr-%s python-%s %s\n' % (
564
 
                    bzrlib.version_string,
565
 
                    bzrlib._format_version_tuple(sys.version_info),
566
 
                    platform.platform(aliased=1),
567
 
                    ))
568
 
        self.stream.write('\n')
569
 
 
570
 
    def report_test_start(self, test):
571
 
        """Display information on the test just about to be run"""
572
 
 
573
 
    def _report_thread_leak(self, test, leaked_threads, active_threads):
574
 
        """Display information on a test that leaked one or more threads"""
575
 
        # GZ 2010-09-09: A leak summary reported separately from the general
576
 
        #                thread debugging would be nice. Tests under subunit
577
 
        #                need something not using stream, perhaps adding a
578
 
        #                testtools details object would be fitting.
579
 
        if 'threads' in selftest_debug_flags:
580
 
            self.stream.write('%s is leaking, active is now %d\n' %
581
 
                (test.id(), len(active_threads)))
582
 
 
583
 
    def startTestRun(self):
584
 
        self.startTime = time.time()
 
288
    def _addSkipped(self, test, skip_excinfo):
 
289
        if isinstance(skip_excinfo[1], TestNotApplicable):
 
290
            self.not_applicable_count += 1
 
291
            self.report_not_applicable(test, skip_excinfo)
 
292
        else:
 
293
            self.skip_count += 1
 
294
            self.report_skip(test, skip_excinfo)
 
295
        try:
 
296
            test.tearDown()
 
297
        except KeyboardInterrupt:
 
298
            raise
 
299
        except:
 
300
            self.addError(test, test._exc_info())
 
301
        else:
 
302
            # seems best to treat this as success from point-of-view of unittest
 
303
            # -- it actually does nothing so it barely matters :)
 
304
            unittest.TestResult.addSuccess(self, test)
 
305
            test._log_contents = ''
 
306
 
 
307
    def printErrorList(self, flavour, errors):
 
308
        for test, err in errors:
 
309
            self.stream.writeln(self.separator1)
 
310
            self.stream.write("%s: " % flavour)
 
311
            self.stream.writeln(self.getDescription(test))
 
312
            if getattr(test, '_get_log', None) is not None:
 
313
                self.stream.write('\n')
 
314
                self.stream.write(
 
315
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
 
316
                self.stream.write('\n')
 
317
                self.stream.write(test._get_log())
 
318
                self.stream.write('\n')
 
319
                self.stream.write(
 
320
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
 
321
                self.stream.write('\n')
 
322
            self.stream.writeln(self.separator2)
 
323
            self.stream.writeln("%s" % err)
 
324
 
 
325
    def finished(self):
 
326
        pass
 
327
 
 
328
    def report_cleaning_up(self):
 
329
        pass
585
330
 
586
331
    def report_success(self, test):
587
332
        pass
597
342
 
598
343
    def __init__(self, stream, descriptions, verbosity,
599
344
                 bench_history=None,
 
345
                 num_tests=None,
600
346
                 pb=None,
601
 
                 strict=None,
602
347
                 ):
603
348
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
604
 
            bench_history, strict)
605
 
        # We no longer pass them around, but just rely on the UIFactory stack
606
 
        # for state
607
 
        if pb is not None:
608
 
            warnings.warn("Passing pb to TextTestResult is deprecated")
609
 
        self.pb = self.ui.nested_progress_bar()
 
349
            bench_history, num_tests)
 
350
        if pb is None:
 
351
            self.pb = self.ui.nested_progress_bar()
 
352
            self._supplied_pb = False
 
353
        else:
 
354
            self.pb = pb
 
355
            self._supplied_pb = True
610
356
        self.pb.show_pct = False
611
357
        self.pb.show_spinner = False
612
358
        self.pb.show_eta = False,
613
359
        self.pb.show_count = False
614
360
        self.pb.show_bar = False
615
 
        self.pb.update_latency = 0
616
 
        self.pb.show_transport_activity = False
617
 
 
618
 
    def stopTestRun(self):
619
 
        # called when the tests that are going to run have run
620
 
        self.pb.clear()
621
 
        self.pb.finished()
622
 
        super(TextTestResult, self).stopTestRun()
623
 
 
624
 
    def report_tests_starting(self):
625
 
        super(TextTestResult, self).report_tests_starting()
626
 
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
 
361
 
 
362
    def report_starting(self):
 
363
        self.pb.update('[test 0/%d] starting...' % (self.num_tests))
627
364
 
628
365
    def _progress_prefix_text(self):
629
366
        # the longer this text, the less space we have to show the test
635
372
        ##     a += ', %d skip' % self.skip_count
636
373
        ## if self.known_failure_count:
637
374
        ##     a += '+%dX' % self.known_failure_count
638
 
        if self.num_tests:
 
375
        if self.num_tests is not None:
639
376
            a +='/%d' % self.num_tests
640
377
        a += ' in '
641
378
        runtime = time.time() - self._overall_start_time
643
380
            a += '%dm%ds' % (runtime / 60, runtime % 60)
644
381
        else:
645
382
            a += '%ds' % runtime
646
 
        total_fail_count = self.error_count + self.failure_count
647
 
        if total_fail_count:
648
 
            a += ', %d failed' % total_fail_count
649
 
        # if self.unsupported:
650
 
        #     a += ', %d missing' % len(self.unsupported)
 
383
        if self.error_count:
 
384
            a += ', %d err' % self.error_count
 
385
        if self.failure_count:
 
386
            a += ', %d fail' % self.failure_count
 
387
        if self.unsupported:
 
388
            a += ', %d missing' % len(self.unsupported)
651
389
        a += ']'
652
390
        return a
653
391
 
654
392
    def report_test_start(self, test):
 
393
        self.count += 1
655
394
        self.pb.update(
656
395
                self._progress_prefix_text()
657
 
                + ' '
 
396
                + ' ' 
658
397
                + self._shortened_test_description(test))
659
398
 
660
399
    def _test_description(self, test):
661
400
        return self._shortened_test_description(test)
662
401
 
663
402
    def report_error(self, test, err):
664
 
        self.stream.write('ERROR: %s\n    %s\n' % (
 
403
        self.pb.note('ERROR: %s\n    %s\n', 
665
404
            self._test_description(test),
666
405
            err[1],
667
 
            ))
 
406
            )
668
407
 
669
408
    def report_failure(self, test, err):
670
 
        self.stream.write('FAIL: %s\n    %s\n' % (
 
409
        self.pb.note('FAIL: %s\n    %s\n', 
671
410
            self._test_description(test),
672
411
            err[1],
673
 
            ))
 
412
            )
674
413
 
675
414
    def report_known_failure(self, test, err):
676
 
        pass
677
 
 
678
 
    def report_unexpected_success(self, test, reason):
679
 
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
680
 
            self._test_description(test),
681
 
            "Unexpected success. Should have failed",
682
 
            reason,
683
 
            ))
684
 
 
685
 
    def report_skip(self, test, reason):
686
 
        pass
687
 
 
688
 
    def report_not_applicable(self, test, reason):
 
415
        self.pb.note('XFAIL: %s\n%s\n',
 
416
            self._test_description(test), err[1])
 
417
 
 
418
    def report_skip(self, test, skip_excinfo):
 
419
        pass
 
420
 
 
421
    def report_not_applicable(self, test, skip_excinfo):
689
422
        pass
690
423
 
691
424
    def report_unsupported(self, test, feature):
692
425
        """test cannot be run because feature is missing."""
 
426
                  
 
427
    def report_cleaning_up(self):
 
428
        self.pb.update('cleaning up...')
 
429
 
 
430
    def finished(self):
 
431
        if not self._supplied_pb:
 
432
            self.pb.finished()
693
433
 
694
434
 
695
435
class VerboseTestResult(ExtendedTestResult):
703
443
            result = a_string
704
444
        return result.ljust(final_width)
705
445
 
706
 
    def report_tests_starting(self):
 
446
    def report_starting(self):
707
447
        self.stream.write('running %d tests...\n' % self.num_tests)
708
 
        super(VerboseTestResult, self).report_tests_starting()
709
448
 
710
449
    def report_test_start(self, test):
 
450
        self.count += 1
711
451
        name = self._shortened_test_description(test)
712
 
        width = osutils.terminal_width()
713
 
        if width is not None:
714
 
            # width needs space for 6 char status, plus 1 for slash, plus an
715
 
            # 11-char time string, plus a trailing blank
716
 
            # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on
717
 
            # space
718
 
            self.stream.write(self._ellipsize_to_right(name, width-18))
719
 
        else:
720
 
            self.stream.write(name)
 
452
        # width needs space for 6 char status, plus 1 for slash, plus 2 10-char
 
453
        # numbers, plus a trailing blank
 
454
        # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
 
455
        self.stream.write(self._ellipsize_to_right(name,
 
456
                          osutils.terminal_width()-30))
721
457
        self.stream.flush()
722
458
 
723
459
    def _error_summary(self, err):
725
461
        return '%s%s' % (indent, err[1])
726
462
 
727
463
    def report_error(self, test, err):
728
 
        self.stream.write('ERROR %s\n%s\n'
 
464
        self.stream.writeln('ERROR %s\n%s'
729
465
                % (self._testTimeString(test),
730
466
                   self._error_summary(err)))
731
467
 
732
468
    def report_failure(self, test, err):
733
 
        self.stream.write(' FAIL %s\n%s\n'
 
469
        self.stream.writeln(' FAIL %s\n%s'
734
470
                % (self._testTimeString(test),
735
471
                   self._error_summary(err)))
736
472
 
737
473
    def report_known_failure(self, test, err):
738
 
        self.stream.write('XFAIL %s\n%s\n'
 
474
        self.stream.writeln('XFAIL %s\n%s'
739
475
                % (self._testTimeString(test),
740
476
                   self._error_summary(err)))
741
477
 
742
 
    def report_unexpected_success(self, test, reason):
743
 
        self.stream.write(' FAIL %s\n%s: %s\n'
744
 
                % (self._testTimeString(test),
745
 
                   "Unexpected success. Should have failed",
746
 
                   reason))
747
 
 
748
478
    def report_success(self, test):
749
 
        self.stream.write('   OK %s\n' % self._testTimeString(test))
 
479
        self.stream.writeln('   OK %s' % self._testTimeString(test))
750
480
        for bench_called, stats in getattr(test, '_benchcalls', []):
751
 
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
 
481
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
752
482
            stats.pprint(file=self.stream)
753
483
        # flush the stream so that we get smooth output. This verbose mode is
754
484
        # used to show the output in PQM.
755
485
        self.stream.flush()
756
486
 
757
 
    def report_skip(self, test, reason):
758
 
        self.stream.write(' SKIP %s\n%s\n'
759
 
                % (self._testTimeString(test), reason))
 
487
    def report_skip(self, test, skip_excinfo):
 
488
        self.stream.writeln(' SKIP %s\n%s'
 
489
                % (self._testTimeString(test),
 
490
                   self._error_summary(skip_excinfo)))
760
491
 
761
 
    def report_not_applicable(self, test, reason):
762
 
        self.stream.write('  N/A %s\n    %s\n'
763
 
                % (self._testTimeString(test), reason))
 
492
    def report_not_applicable(self, test, skip_excinfo):
 
493
        self.stream.writeln('  N/A %s\n%s'
 
494
                % (self._testTimeString(test),
 
495
                   self._error_summary(skip_excinfo)))
764
496
 
765
497
    def report_unsupported(self, test, feature):
766
498
        """test cannot be run because feature is missing."""
767
 
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
 
499
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
768
500
                %(self._testTimeString(test), feature))
769
501
 
770
502
 
776
508
                 descriptions=0,
777
509
                 verbosity=1,
778
510
                 bench_history=None,
779
 
                 strict=False,
780
 
                 result_decorators=None,
 
511
                 list_only=False
781
512
                 ):
782
 
        """Create a TextTestRunner.
783
 
 
784
 
        :param result_decorators: An optional list of decorators to apply
785
 
            to the result object being used by the runner. Decorators are
786
 
            applied left to right - the first element in the list is the 
787
 
            innermost decorator.
788
 
        """
789
 
        # stream may know claim to know to write unicode strings, but in older
790
 
        # pythons this goes sufficiently wrong that it is a bad idea. (
791
 
        # specifically a built in file with encoding 'UTF-8' will still try
792
 
        # to encode using ascii.
793
 
        new_encoding = osutils.get_terminal_encoding()
794
 
        codec = codecs.lookup(new_encoding)
795
 
        if type(codec) is tuple:
796
 
            # Python 2.4
797
 
            encode = codec[0]
798
 
        else:
799
 
            encode = codec.encode
800
 
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
801
 
        #                so should swap to the plain codecs.StreamWriter
802
 
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
803
 
            "backslashreplace")
804
 
        stream.encoding = new_encoding
805
 
        self.stream = stream
 
513
        self.stream = unittest._WritelnDecorator(stream)
806
514
        self.descriptions = descriptions
807
515
        self.verbosity = verbosity
808
516
        self._bench_history = bench_history
809
 
        self._strict = strict
810
 
        self._result_decorators = result_decorators or []
 
517
        self.list_only = list_only
811
518
 
812
519
    def run(self, test):
813
520
        "Run the given test case or test suite."
 
521
        startTime = time.time()
814
522
        if self.verbosity == 1:
815
523
            result_class = TextTestResult
816
524
        elif self.verbosity >= 2:
817
525
            result_class = VerboseTestResult
818
 
        original_result = result_class(self.stream,
 
526
        result = result_class(self.stream,
819
527
                              self.descriptions,
820
528
                              self.verbosity,
821
529
                              bench_history=self._bench_history,
822
 
                              strict=self._strict,
 
530
                              num_tests=test.countTestCases(),
823
531
                              )
824
 
        # Signal to result objects that look at stop early policy to stop,
825
 
        original_result.stop_early = self.stop_on_failure
826
 
        result = original_result
827
 
        for decorator in self._result_decorators:
828
 
            result = decorator(result)
829
 
            result.stop_early = self.stop_on_failure
830
 
        result.startTestRun()
831
 
        try:
 
532
        result.stop_early = self.stop_on_failure
 
533
        result.report_starting()
 
534
        if self.list_only:
 
535
            if self.verbosity >= 2:
 
536
                self.stream.writeln("Listing tests only ...\n")
 
537
            run = 0
 
538
            for t in iter_suite_tests(test):
 
539
                self.stream.writeln("%s" % (t.id()))
 
540
                run += 1
 
541
            actionTaken = "Listed"
 
542
        else: 
832
543
            test.run(result)
833
 
        finally:
834
 
            result.stopTestRun()
835
 
        # higher level code uses our extended protocol to determine
836
 
        # what exit code to give.
837
 
        return original_result
 
544
            run = result.testsRun
 
545
            actionTaken = "Ran"
 
546
        stopTime = time.time()
 
547
        timeTaken = stopTime - startTime
 
548
        result.printErrors()
 
549
        self.stream.writeln(result.separator2)
 
550
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
551
                            run, run != 1 and "s" or "", timeTaken))
 
552
        self.stream.writeln()
 
553
        if not result.wasSuccessful():
 
554
            self.stream.write("FAILED (")
 
555
            failed, errored = map(len, (result.failures, result.errors))
 
556
            if failed:
 
557
                self.stream.write("failures=%d" % failed)
 
558
            if errored:
 
559
                if failed: self.stream.write(", ")
 
560
                self.stream.write("errors=%d" % errored)
 
561
            if result.known_failure_count:
 
562
                if failed or errored: self.stream.write(", ")
 
563
                self.stream.write("known_failure_count=%d" %
 
564
                    result.known_failure_count)
 
565
            self.stream.writeln(")")
 
566
        else:
 
567
            if result.known_failure_count:
 
568
                self.stream.writeln("OK (known_failures=%d)" %
 
569
                    result.known_failure_count)
 
570
            else:
 
571
                self.stream.writeln("OK")
 
572
        if result.skip_count > 0:
 
573
            skipped = result.skip_count
 
574
            self.stream.writeln('%d test%s skipped' %
 
575
                                (skipped, skipped != 1 and "s" or ""))
 
576
        if result.unsupported:
 
577
            for feature, count in sorted(result.unsupported.items()):
 
578
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
579
                    (feature, count))
 
580
        result.finished()
 
581
        return result
838
582
 
839
583
 
840
584
def iter_suite_tests(suite):
841
585
    """Return all tests in a suite, recursing through nested suites"""
842
 
    if isinstance(suite, unittest.TestCase):
843
 
        yield suite
844
 
    elif isinstance(suite, unittest.TestSuite):
845
 
        for item in suite:
 
586
    for item in suite._tests:
 
587
        if isinstance(item, unittest.TestCase):
 
588
            yield item
 
589
        elif isinstance(item, unittest.TestSuite):
846
590
            for r in iter_suite_tests(item):
847
591
                yield r
848
 
    else:
849
 
        raise Exception('unknown type %r for object %r'
850
 
                        % (type(suite), suite))
851
 
 
852
 
 
853
 
TestSkipped = testtools.testcase.TestSkipped
 
592
        else:
 
593
            raise Exception('unknown object %r inside test suite %r'
 
594
                            % (item, suite))
 
595
 
 
596
 
 
597
class TestSkipped(Exception):
 
598
    """Indicates that a test was intentionally skipped, rather than failing."""
854
599
 
855
600
 
856
601
class TestNotApplicable(TestSkipped):
857
602
    """A test is not applicable to the situation where it was run.
858
603
 
859
 
    This is only normally raised by parameterized tests, if they find that
860
 
    the instance they're constructed upon does not support one aspect
 
604
    This is only normally raised by parameterized tests, if they find that 
 
605
    the instance they're constructed upon does not support one aspect 
861
606
    of its interface.
862
607
    """
863
608
 
864
609
 
865
 
# traceback._some_str fails to format exceptions that have the default
866
 
# __str__ which does an implicit ascii conversion. However, repr() on those
867
 
# objects works, for all that its not quite what the doctor may have ordered.
868
 
def _clever_some_str(value):
869
 
    try:
870
 
        return str(value)
871
 
    except:
872
 
        try:
873
 
            return repr(value).replace('\\n', '\n')
874
 
        except:
875
 
            return '<unprintable %s object>' % type(value).__name__
876
 
 
877
 
traceback._some_str = _clever_some_str
878
 
 
879
 
 
880
 
# deprecated - use self.knownFailure(), or self.expectFailure.
881
 
KnownFailure = testtools.testcase._ExpectedFailure
 
610
class KnownFailure(AssertionError):
 
611
    """Indicates that a test failed in a precisely expected manner.
 
612
 
 
613
    Such failures dont block the whole test suite from passing because they are
 
614
    indicators of partially completed code or of future work. We have an
 
615
    explicit error for them so that we can ensure that they are always visible:
 
616
    KnownFailures are always shown in the output of bzr selftest.
 
617
    """
882
618
 
883
619
 
884
620
class UnavailableFeature(Exception):
885
621
    """A feature required for this test was not available.
886
622
 
887
 
    This can be considered a specialised form of SkippedTest.
888
 
 
889
623
    The feature should be used to construct the exception.
890
624
    """
891
625
 
892
626
 
 
627
class CommandFailed(Exception):
 
628
    pass
 
629
 
 
630
 
893
631
class StringIOWrapper(object):
894
632
    """A wrapper around cStringIO which just adds an encoding attribute.
895
 
 
 
633
    
896
634
    Internally we can check sys.stdout to see what the output encoding
897
635
    should be. However, cStringIO has no encoding attribute that we can
898
636
    set. So we wrap it instead.
916
654
            return setattr(self._cstring, name, val)
917
655
 
918
656
 
919
 
class TestUIFactory(TextUIFactory):
 
657
class TestUIFactory(ui.CLIUIFactory):
920
658
    """A UI Factory for testing.
921
659
 
922
660
    Hide the progress bar but emit note()s.
923
661
    Redirect stdin.
924
662
    Allows get_password to be tested without real tty attached.
925
 
 
926
 
    See also CannedInputUIFactory which lets you provide programmatic input in
927
 
    a structured way.
928
663
    """
929
 
    # TODO: Capture progress events at the model level and allow them to be
930
 
    # observed by tests that care.
931
 
    #
932
 
    # XXX: Should probably unify more with CannedInputUIFactory or a
933
 
    # particular configuration of TextUIFactory, or otherwise have a clearer
934
 
    # idea of how they're supposed to be different.
935
 
    # See https://bugs.launchpad.net/bzr/+bug/408213
936
664
 
937
 
    def __init__(self, stdout=None, stderr=None, stdin=None):
 
665
    def __init__(self,
 
666
                 stdout=None,
 
667
                 stderr=None,
 
668
                 stdin=None):
 
669
        super(TestUIFactory, self).__init__()
938
670
        if stdin is not None:
939
671
            # We use a StringIOWrapper to be able to test various
940
672
            # encodings, but the user is still responsible to
941
673
            # encode the string and to set the encoding attribute
942
674
            # of StringIOWrapper.
943
 
            stdin = StringIOWrapper(stdin)
944
 
        super(TestUIFactory, self).__init__(stdin, stdout, stderr)
945
 
 
946
 
    def get_non_echoed_password(self):
 
675
            self.stdin = StringIOWrapper(stdin)
 
676
        if stdout is None:
 
677
            self.stdout = sys.stdout
 
678
        else:
 
679
            self.stdout = stdout
 
680
        if stderr is None:
 
681
            self.stderr = sys.stderr
 
682
        else:
 
683
            self.stderr = stderr
 
684
 
 
685
    def clear(self):
 
686
        """See progress.ProgressBar.clear()."""
 
687
 
 
688
    def clear_term(self):
 
689
        """See progress.ProgressBar.clear_term()."""
 
690
 
 
691
    def clear_term(self):
 
692
        """See progress.ProgressBar.clear_term()."""
 
693
 
 
694
    def finished(self):
 
695
        """See progress.ProgressBar.finished()."""
 
696
 
 
697
    def note(self, fmt_string, *args, **kwargs):
 
698
        """See progress.ProgressBar.note()."""
 
699
        self.stdout.write((fmt_string + "\n") % args)
 
700
 
 
701
    def progress_bar(self):
 
702
        return self
 
703
 
 
704
    def nested_progress_bar(self):
 
705
        return self
 
706
 
 
707
    def update(self, message, count=None, total=None):
 
708
        """See progress.ProgressBar.update()."""
 
709
 
 
710
    def get_non_echoed_password(self, prompt):
947
711
        """Get password from stdin without trying to handle the echo mode"""
 
712
        if prompt:
 
713
            self.stdout.write(prompt.encode(self.stdout.encoding, 'replace'))
948
714
        password = self.stdin.readline()
949
715
        if not password:
950
716
            raise EOFError
952
718
            password = password[:-1]
953
719
        return password
954
720
 
955
 
    def make_progress_view(self):
956
 
        return NullProgressView()
957
 
 
958
 
 
959
 
def isolated_doctest_setUp(test):
960
 
    override_os_environ(test)
961
 
 
962
 
 
963
 
def isolated_doctest_tearDown(test):
964
 
    restore_os_environ(test)
965
 
 
966
 
 
967
 
def IsolatedDocTestSuite(*args, **kwargs):
968
 
    """Overrides doctest.DocTestSuite to handle isolation.
969
 
 
970
 
    The method is really a factory and users are expected to use it as such.
971
 
    """
972
 
 
973
 
    kwargs['setUp'] = isolated_doctest_setUp
974
 
    kwargs['tearDown'] = isolated_doctest_tearDown
975
 
    return doctest.DocTestSuite(*args, **kwargs)
976
 
 
977
 
 
978
 
class TestCase(testtools.TestCase):
 
721
 
 
722
def _report_leaked_threads():
 
723
    bzrlib.trace.warning('%s is leaking threads among %d leaking tests',
 
724
                         TestCase._first_thread_leaker_id,
 
725
                         TestCase._leaking_threads_tests)
 
726
 
 
727
 
 
728
class TestCase(unittest.TestCase):
979
729
    """Base class for bzr unit tests.
980
 
 
981
 
    Tests that need access to disk resources should subclass
 
730
    
 
731
    Tests that need access to disk resources should subclass 
982
732
    TestCaseInTempDir not TestCase.
983
733
 
984
734
    Error and debug log messages are redirected from their usual
986
736
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
987
737
    so that it can also capture file IO.  When the test completes this file
988
738
    is read into memory and removed from disk.
989
 
 
 
739
       
990
740
    There are also convenience functions to invoke bzr's command-line
991
741
    routine, and to build and check bzr trees.
992
 
 
 
742
   
993
743
    In addition to the usual method of overriding tearDown(), this class also
994
 
    allows subclasses to register cleanup functions via addCleanup, which are
 
744
    allows subclasses to register functions into the _cleanups list, which is
995
745
    run in order as the object is torn down.  It's less likely this will be
996
746
    accidentally overlooked.
997
747
    """
998
748
 
999
 
    _log_file = None
 
749
    _active_threads = None
 
750
    _leaking_threads_tests = 0
 
751
    _first_thread_leaker_id = None
 
752
    _log_file_name = None
 
753
    _log_contents = ''
 
754
    _keep_log_file = False
1000
755
    # record lsprof data when performing benchmark calls.
1001
756
    _gather_lsprof_in_benchmarks = False
 
757
    attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
 
758
                     '_log_contents', '_log_file_name', '_benchtime',
 
759
                     '_TestCase__testMethodName')
1002
760
 
1003
761
    def __init__(self, methodName='testMethod'):
1004
762
        super(TestCase, self).__init__(methodName)
1005
 
        self._directory_isolation = True
1006
 
        self.exception_handlers.insert(0,
1007
 
            (UnavailableFeature, self._do_unsupported_or_skip))
1008
 
        self.exception_handlers.insert(0,
1009
 
            (TestNotApplicable, self._do_not_applicable))
 
763
        self._cleanups = []
1010
764
 
1011
765
    def setUp(self):
1012
 
        super(TestCase, self).setUp()
1013
 
 
1014
 
        # At this point we're still accessing the config files in $BZR_HOME (as
1015
 
        # set by the user running selftest).
1016
 
        timeout = config.GlobalStack().get('selftest.timeout')
1017
 
        if timeout:
1018
 
            timeout_fixture = fixtures.TimeoutFixture(timeout)
1019
 
            timeout_fixture.setUp()
1020
 
            self.addCleanup(timeout_fixture.cleanUp)
1021
 
 
1022
 
        for feature in getattr(self, '_test_needs_features', []):
1023
 
            self.requireFeature(feature)
 
766
        unittest.TestCase.setUp(self)
1024
767
        self._cleanEnvironment()
1025
 
 
1026
 
        if bzrlib.global_state is not None:
1027
 
            self.overrideAttr(bzrlib.global_state, 'cmdline_overrides',
1028
 
                              config.CommandLineStore())
1029
 
 
1030
768
        self._silenceUI()
1031
769
        self._startLogFile()
1032
770
        self._benchcalls = []
1033
771
        self._benchtime = None
1034
772
        self._clear_hooks()
1035
 
        self._track_transports()
1036
 
        self._track_locks()
1037
773
        self._clear_debug_flags()
1038
 
        # Isolate global verbosity level, to make sure it's reproducible
1039
 
        # between tests.  We should get rid of this altogether: bug 656694. --
1040
 
        # mbp 20101008
1041
 
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
1042
 
        self._log_files = set()
1043
 
        # Each key in the ``_counters`` dict holds a value for a different
1044
 
        # counter. When the test ends, addDetail() should be used to output the
1045
 
        # counter values. This happens in install_counter_hook().
1046
 
        self._counters = {}
1047
 
        if 'config_stats' in selftest_debug_flags:
1048
 
            self._install_config_stats_hooks()
1049
 
        # Do not use i18n for tests (unless the test reverses this)
1050
 
        i18n.disable_i18n()
1051
 
 
1052
 
    def debug(self):
1053
 
        # debug a frame up.
1054
 
        import pdb
1055
 
        # The sys preserved stdin/stdout should allow blackbox tests debugging
1056
 
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
1057
 
                ).set_trace(sys._getframe().f_back)
1058
 
 
1059
 
    def discardDetail(self, name):
1060
 
        """Extend the addDetail, getDetails api so we can remove a detail.
1061
 
 
1062
 
        eg. bzr always adds the 'log' detail at startup, but we don't want to
1063
 
        include it for skipped, xfail, etc tests.
1064
 
 
1065
 
        It is safe to call this for a detail that doesn't exist, in case this
1066
 
        gets called multiple times.
1067
 
        """
1068
 
        # We cheat. details is stored in __details which means we shouldn't
1069
 
        # touch it. but getDetails() returns the dict directly, so we can
1070
 
        # mutate it.
1071
 
        details = self.getDetails()
1072
 
        if name in details:
1073
 
            del details[name]
1074
 
 
1075
 
    def install_counter_hook(self, hooks, name, counter_name=None):
1076
 
        """Install a counting hook.
1077
 
 
1078
 
        Any hook can be counted as long as it doesn't need to return a value.
1079
 
 
1080
 
        :param hooks: Where the hook should be installed.
1081
 
 
1082
 
        :param name: The hook name that will be counted.
1083
 
 
1084
 
        :param counter_name: The counter identifier in ``_counters``, defaults
1085
 
            to ``name``.
1086
 
        """
1087
 
        _counters = self._counters # Avoid closing over self
1088
 
        if counter_name is None:
1089
 
            counter_name = name
1090
 
        if _counters.has_key(counter_name):
1091
 
            raise AssertionError('%s is already used as a counter name'
1092
 
                                  % (counter_name,))
1093
 
        _counters[counter_name] = 0
1094
 
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
1095
 
            lambda: ['%d' % (_counters[counter_name],)]))
1096
 
        def increment_counter(*args, **kwargs):
1097
 
            _counters[counter_name] += 1
1098
 
        label = 'count %s calls' % (counter_name,)
1099
 
        hooks.install_named_hook(name, increment_counter, label)
1100
 
        self.addCleanup(hooks.uninstall_named_hook, name, label)
1101
 
 
1102
 
    def _install_config_stats_hooks(self):
1103
 
        """Install config hooks to count hook calls.
1104
 
 
1105
 
        """
1106
 
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
1107
 
            self.install_counter_hook(config.ConfigHooks, hook_name,
1108
 
                                       'config.%s' % (hook_name,))
1109
 
 
1110
 
        # The OldConfigHooks are private and need special handling to protect
1111
 
        # against recursive tests (tests that run other tests), so we just do
1112
 
        # manually what registering them into _builtin_known_hooks will provide
1113
 
        # us.
1114
 
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
1115
 
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
1116
 
            self.install_counter_hook(config.OldConfigHooks, hook_name,
1117
 
                                      'old_config.%s' % (hook_name,))
 
774
        TestCase._active_threads = threading.activeCount()
 
775
        self.addCleanup(self._check_leaked_threads)
 
776
 
 
777
    def _check_leaked_threads(self):
 
778
        active = threading.activeCount()
 
779
        leaked_threads = active - TestCase._active_threads
 
780
        TestCase._active_threads = active
 
781
        if leaked_threads:
 
782
            TestCase._leaking_threads_tests += 1
 
783
            if TestCase._first_thread_leaker_id is None:
 
784
                TestCase._first_thread_leaker_id = self.id()
 
785
                # we're not specifically told when all tests are finished.
 
786
                # This will do. We use a function to avoid keeping a reference
 
787
                # to a TestCase object.
 
788
                atexit.register(_report_leaked_threads)
1118
789
 
1119
790
    def _clear_debug_flags(self):
1120
791
        """Prevent externally set debug flags affecting tests.
1121
 
 
 
792
        
1122
793
        Tests that want to use debug flags can just set them in the
1123
794
        debug_flags set during setup/teardown.
1124
795
        """
1125
 
        # Start with a copy of the current debug flags we can safely modify.
1126
 
        self.overrideAttr(debug, 'debug_flags', set(debug.debug_flags))
1127
796
        if 'allow_debug' not in selftest_debug_flags:
 
797
            self._preserved_debug_flags = set(debug.debug_flags)
1128
798
            debug.debug_flags.clear()
1129
 
        if 'disable_lock_checks' not in selftest_debug_flags:
1130
 
            debug.debug_flags.add('strict_locks')
 
799
            self.addCleanup(self._restore_debug_flags)
1131
800
 
1132
801
    def _clear_hooks(self):
1133
802
        # prevent hooks affecting tests
1134
 
        known_hooks = hooks.known_hooks
1135
 
        self._preserved_hooks = {}
1136
 
        for key, (parent, name) in known_hooks.iter_parent_objects():
1137
 
            current_hooks = getattr(parent, name)
1138
 
            self._preserved_hooks[parent] = (name, current_hooks)
1139
 
        self._preserved_lazy_hooks = hooks._lazy_hooks
1140
 
        hooks._lazy_hooks = {}
 
803
        import bzrlib.branch
 
804
        import bzrlib.smart.server
 
805
        self._preserved_hooks = {
 
806
            bzrlib.branch.Branch: bzrlib.branch.Branch.hooks,
 
807
            bzrlib.mutabletree.MutableTree: bzrlib.mutabletree.MutableTree.hooks,
 
808
            bzrlib.smart.server.SmartTCPServer: bzrlib.smart.server.SmartTCPServer.hooks,
 
809
            }
1141
810
        self.addCleanup(self._restoreHooks)
1142
 
        for key, (parent, name) in known_hooks.iter_parent_objects():
1143
 
            factory = known_hooks.get(key)
1144
 
            setattr(parent, name, factory())
1145
 
        # this hook should always be installed
1146
 
        request._install_hook()
1147
 
 
1148
 
    def disable_directory_isolation(self):
1149
 
        """Turn off directory isolation checks."""
1150
 
        self._directory_isolation = False
1151
 
 
1152
 
    def enable_directory_isolation(self):
1153
 
        """Enable directory isolation checks."""
1154
 
        self._directory_isolation = True
 
811
        # reset all hooks to an empty instance of the appropriate type
 
812
        bzrlib.branch.Branch.hooks = bzrlib.branch.BranchHooks()
 
813
        bzrlib.smart.server.SmartTCPServer.hooks = bzrlib.smart.server.SmartServerHooks()
1155
814
 
1156
815
    def _silenceUI(self):
1157
816
        """Turn off UI for duration of test"""
1158
817
        # by default the UI is off; tests can turn it on if they want it.
1159
 
        self.overrideAttr(ui, 'ui_factory', ui.SilentUIFactory())
1160
 
 
1161
 
    def _check_locks(self):
1162
 
        """Check that all lock take/release actions have been paired."""
1163
 
        # We always check for mismatched locks. If a mismatch is found, we
1164
 
        # fail unless -Edisable_lock_checks is supplied to selftest, in which
1165
 
        # case we just print a warning.
1166
 
        # unhook:
1167
 
        acquired_locks = [lock for action, lock in self._lock_actions
1168
 
                          if action == 'acquired']
1169
 
        released_locks = [lock for action, lock in self._lock_actions
1170
 
                          if action == 'released']
1171
 
        broken_locks = [lock for action, lock in self._lock_actions
1172
 
                        if action == 'broken']
1173
 
        # trivially, given the tests for lock acquistion and release, if we
1174
 
        # have as many in each list, it should be ok. Some lock tests also
1175
 
        # break some locks on purpose and should be taken into account by
1176
 
        # considering that breaking a lock is just a dirty way of releasing it.
1177
 
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
1178
 
            message = (
1179
 
                'Different number of acquired and '
1180
 
                'released or broken locks.\n'
1181
 
                'acquired=%s\n'
1182
 
                'released=%s\n'
1183
 
                'broken=%s\n' %
1184
 
                (acquired_locks, released_locks, broken_locks))
1185
 
            if not self._lock_check_thorough:
1186
 
                # Rather than fail, just warn
1187
 
                print "Broken test %s: %s" % (self, message)
1188
 
                return
1189
 
            self.fail(message)
1190
 
 
1191
 
    def _track_locks(self):
1192
 
        """Track lock activity during tests."""
1193
 
        self._lock_actions = []
1194
 
        if 'disable_lock_checks' in selftest_debug_flags:
1195
 
            self._lock_check_thorough = False
1196
 
        else:
1197
 
            self._lock_check_thorough = True
1198
 
 
1199
 
        self.addCleanup(self._check_locks)
1200
 
        _mod_lock.Lock.hooks.install_named_hook('lock_acquired',
1201
 
                                                self._lock_acquired, None)
1202
 
        _mod_lock.Lock.hooks.install_named_hook('lock_released',
1203
 
                                                self._lock_released, None)
1204
 
        _mod_lock.Lock.hooks.install_named_hook('lock_broken',
1205
 
                                                self._lock_broken, None)
1206
 
 
1207
 
    def _lock_acquired(self, result):
1208
 
        self._lock_actions.append(('acquired', result))
1209
 
 
1210
 
    def _lock_released(self, result):
1211
 
        self._lock_actions.append(('released', result))
1212
 
 
1213
 
    def _lock_broken(self, result):
1214
 
        self._lock_actions.append(('broken', result))
1215
 
 
1216
 
    def permit_dir(self, name):
1217
 
        """Permit a directory to be used by this test. See permit_url."""
1218
 
        name_transport = _mod_transport.get_transport_from_path(name)
1219
 
        self.permit_url(name)
1220
 
        self.permit_url(name_transport.base)
1221
 
 
1222
 
    def permit_url(self, url):
1223
 
        """Declare that url is an ok url to use in this test.
1224
 
        
1225
 
        Do this for memory transports, temporary test directory etc.
1226
 
        
1227
 
        Do not do this for the current working directory, /tmp, or any other
1228
 
        preexisting non isolated url.
1229
 
        """
1230
 
        if not url.endswith('/'):
1231
 
            url += '/'
1232
 
        self._bzr_selftest_roots.append(url)
1233
 
 
1234
 
    def permit_source_tree_branch_repo(self):
1235
 
        """Permit the source tree bzr is running from to be opened.
1236
 
 
1237
 
        Some code such as bzrlib.version attempts to read from the bzr branch
1238
 
        that bzr is executing from (if any). This method permits that directory
1239
 
        to be used in the test suite.
1240
 
        """
1241
 
        path = self.get_source_path()
1242
 
        self.record_directory_isolation()
1243
 
        try:
1244
 
            try:
1245
 
                workingtree.WorkingTree.open(path)
1246
 
            except (errors.NotBranchError, errors.NoWorkingTree):
1247
 
                raise TestSkipped('Needs a working tree of bzr sources')
1248
 
        finally:
1249
 
            self.enable_directory_isolation()
1250
 
 
1251
 
    def _preopen_isolate_transport(self, transport):
1252
 
        """Check that all transport openings are done in the test work area."""
1253
 
        while isinstance(transport, pathfilter.PathFilteringTransport):
1254
 
            # Unwrap pathfiltered transports
1255
 
            transport = transport.server.backing_transport.clone(
1256
 
                transport._filter('.'))
1257
 
        url = transport.base
1258
 
        # ReadonlySmartTCPServer_for_testing decorates the backing transport
1259
 
        # urls it is given by prepending readonly+. This is appropriate as the
1260
 
        # client shouldn't know that the server is readonly (or not readonly).
1261
 
        # We could register all servers twice, with readonly+ prepending, but
1262
 
        # that makes for a long list; this is about the same but easier to
1263
 
        # read.
1264
 
        if url.startswith('readonly+'):
1265
 
            url = url[len('readonly+'):]
1266
 
        self._preopen_isolate_url(url)
1267
 
 
1268
 
    def _preopen_isolate_url(self, url):
1269
 
        if not self._directory_isolation:
1270
 
            return
1271
 
        if self._directory_isolation == 'record':
1272
 
            self._bzr_selftest_roots.append(url)
1273
 
            return
1274
 
        # This prevents all transports, including e.g. sftp ones backed on disk
1275
 
        # from working unless they are explicitly granted permission. We then
1276
 
        # depend on the code that sets up test transports to check that they are
1277
 
        # appropriately isolated and enable their use by calling
1278
 
        # self.permit_transport()
1279
 
        if not osutils.is_inside_any(self._bzr_selftest_roots, url):
1280
 
            raise errors.BzrError("Attempt to escape test isolation: %r %r"
1281
 
                % (url, self._bzr_selftest_roots))
1282
 
 
1283
 
    def record_directory_isolation(self):
1284
 
        """Gather accessed directories to permit later access.
1285
 
        
1286
 
        This is used for tests that access the branch bzr is running from.
1287
 
        """
1288
 
        self._directory_isolation = "record"
1289
 
 
1290
 
    def start_server(self, transport_server, backing_server=None):
1291
 
        """Start transport_server for this test.
1292
 
 
1293
 
        This starts the server, registers a cleanup for it and permits the
1294
 
        server's urls to be used.
1295
 
        """
1296
 
        if backing_server is None:
1297
 
            transport_server.start_server()
1298
 
        else:
1299
 
            transport_server.start_server(backing_server)
1300
 
        self.addCleanup(transport_server.stop_server)
1301
 
        # Obtain a real transport because if the server supplies a password, it
1302
 
        # will be hidden from the base on the client side.
1303
 
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1304
 
        # Some transport servers effectively chroot the backing transport;
1305
 
        # others like SFTPServer don't - users of the transport can walk up the
1306
 
        # transport to read the entire backing transport. This wouldn't matter
1307
 
        # except that the workdir tests are given - and that they expect the
1308
 
        # server's url to point at - is one directory under the safety net. So
1309
 
        # Branch operations into the transport will attempt to walk up one
1310
 
        # directory. Chrooting all servers would avoid this but also mean that
1311
 
        # we wouldn't be testing directly against non-root urls. Alternatively
1312
 
        # getting the test framework to start the server with a backing server
1313
 
        # at the actual safety net directory would work too, but this then
1314
 
        # means that the self.get_url/self.get_transport methods would need
1315
 
        # to transform all their results. On balance its cleaner to handle it
1316
 
        # here, and permit a higher url when we have one of these transports.
1317
 
        if t.base.endswith('/work/'):
1318
 
            # we have safety net/test root/work
1319
 
            t = t.clone('../..')
1320
 
        elif isinstance(transport_server,
1321
 
                        test_server.SmartTCPServer_for_testing):
1322
 
            # The smart server adds a path similar to work, which is traversed
1323
 
            # up from by the client. But the server is chrooted - the actual
1324
 
            # backing transport is not escaped from, and VFS requests to the
1325
 
            # root will error (because they try to escape the chroot).
1326
 
            t2 = t.clone('..')
1327
 
            while t2.base != t.base:
1328
 
                t = t2
1329
 
                t2 = t.clone('..')
1330
 
        self.permit_url(t.base)
1331
 
 
1332
 
    def _track_transports(self):
1333
 
        """Install checks for transport usage."""
1334
 
        # TestCase has no safe place it can write to.
1335
 
        self._bzr_selftest_roots = []
1336
 
        # Currently the easiest way to be sure that nothing is going on is to
1337
 
        # hook into bzr dir opening. This leaves a small window of error for
1338
 
        # transport tests, but they are well known, and we can improve on this
1339
 
        # step.
1340
 
        controldir.ControlDir.hooks.install_named_hook("pre_open",
1341
 
            self._preopen_isolate_transport, "Check bzr directories are safe.")
 
818
        saved = ui.ui_factory
 
819
        def _restore():
 
820
            ui.ui_factory = saved
 
821
        ui.ui_factory = ui.SilentUIFactory()
 
822
        self.addCleanup(_restore)
1342
823
 
1343
824
    def _ndiff_strings(self, a, b):
1344
825
        """Return ndiff between two strings containing lines.
1345
 
 
 
826
        
1346
827
        A trailing newline is added if missing to make the strings
1347
828
        print properly."""
1348
829
        if b and b[-1] != '\n':
1362
843
        except UnicodeError, e:
1363
844
            # If we can't compare without getting a UnicodeError, then
1364
845
            # obviously they are different
1365
 
            trace.mutter('UnicodeError: %s', e)
 
846
            mutter('UnicodeError: %s', e)
1366
847
        if message:
1367
848
            message += '\n'
1368
849
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1369
850
            % (message,
1370
 
               pprint.pformat(a), pprint.pformat(b)))
 
851
               pformat(a), pformat(b)))
1371
852
 
1372
 
    # FIXME: This is deprecated in unittest2 but plugins may still use it so we
1373
 
    # need a deprecation period for them -- vila 2016-02-01
1374
853
    assertEquals = assertEqual
1375
854
 
1376
855
    def assertEqualDiff(self, a, b, message=None):
1377
856
        """Assert two texts are equal, if not raise an exception.
1378
 
 
1379
 
        This is intended for use with multi-line strings where it can
 
857
        
 
858
        This is intended for use with multi-line strings where it can 
1380
859
        be hard to find the differences by eye.
1381
860
        """
1382
 
        # TODO: perhaps override assertEqual to call this for strings?
 
861
        # TODO: perhaps override assertEquals to call this for strings?
1383
862
        if a == b:
1384
863
            return
1385
864
        if message is None:
1386
865
            message = "texts not equal:\n"
 
866
        if a == b + '\n':
 
867
            message = 'first string is missing a final newline.\n'
1387
868
        if a + '\n' == b:
1388
 
            message = 'first string is missing a final newline.\n'
1389
 
        if a == b + '\n':
1390
869
            message = 'second string is missing a final newline.\n'
1391
870
        raise AssertionError(message +
1392
871
                             self._ndiff_strings(a, b))
1393
 
 
 
872
        
1394
873
    def assertEqualMode(self, mode, mode_test):
1395
874
        self.assertEqual(mode, mode_test,
1396
875
                         'mode mismatch %o != %o' % (mode, mode_test))
1397
876
 
1398
 
    def assertEqualStat(self, expected, actual):
1399
 
        """assert that expected and actual are the same stat result.
1400
 
 
1401
 
        :param expected: A stat result.
1402
 
        :param actual: A stat result.
1403
 
        :raises AssertionError: If the expected and actual stat values differ
1404
 
            other than by atime.
1405
 
        """
1406
 
        self.assertEqual(expected.st_size, actual.st_size,
1407
 
                         'st_size did not match')
1408
 
        self.assertEqual(expected.st_mtime, actual.st_mtime,
1409
 
                         'st_mtime did not match')
1410
 
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1411
 
                         'st_ctime did not match')
1412
 
        if sys.platform == 'win32':
1413
 
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1414
 
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
1415
 
            # odd. We just force it to always be 0 to avoid any problems.
1416
 
            self.assertEqual(0, expected.st_dev)
1417
 
            self.assertEqual(0, actual.st_dev)
1418
 
            self.assertEqual(0, expected.st_ino)
1419
 
            self.assertEqual(0, actual.st_ino)
1420
 
        else:
1421
 
            self.assertEqual(expected.st_dev, actual.st_dev,
1422
 
                             'st_dev did not match')
1423
 
            self.assertEqual(expected.st_ino, actual.st_ino,
1424
 
                             'st_ino did not match')
1425
 
        self.assertEqual(expected.st_mode, actual.st_mode,
1426
 
                         'st_mode did not match')
1427
 
 
1428
 
    def assertLength(self, length, obj_with_len):
1429
 
        """Assert that obj_with_len is of length length."""
1430
 
        if len(obj_with_len) != length:
1431
 
            self.fail("Incorrect length: wanted %d, got %d for %r" % (
1432
 
                length, len(obj_with_len), obj_with_len))
1433
 
 
1434
 
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1435
 
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1436
 
        """
1437
 
        captured = []
1438
 
        orig_log_exception_quietly = trace.log_exception_quietly
1439
 
        try:
1440
 
            def capture():
1441
 
                orig_log_exception_quietly()
1442
 
                captured.append(sys.exc_info()[1])
1443
 
            trace.log_exception_quietly = capture
1444
 
            func(*args, **kwargs)
1445
 
        finally:
1446
 
            trace.log_exception_quietly = orig_log_exception_quietly
1447
 
        self.assertLength(1, captured)
1448
 
        err = captured[0]
1449
 
        self.assertIsInstance(err, exception_class)
1450
 
        return err
1451
 
 
1452
877
    def assertPositive(self, val):
1453
878
        """Assert that val is greater than 0."""
1454
879
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
1466
891
        if not s.endswith(suffix):
1467
892
            raise AssertionError('string %r does not end with %r' % (s, suffix))
1468
893
 
1469
 
    def assertContainsRe(self, haystack, needle_re, flags=0):
 
894
    def assertContainsRe(self, haystack, needle_re):
1470
895
        """Assert that a contains something matching a regular expression."""
1471
 
        if not re.search(needle_re, haystack, flags):
 
896
        if not re.search(needle_re, haystack):
1472
897
            if '\n' in haystack or len(haystack) > 60:
1473
898
                # a long string, format it in a more readable way
1474
899
                raise AssertionError(
1478
903
                raise AssertionError('pattern "%s" not found in "%s"'
1479
904
                        % (needle_re, haystack))
1480
905
 
1481
 
    def assertNotContainsRe(self, haystack, needle_re, flags=0):
 
906
    def assertNotContainsRe(self, haystack, needle_re):
1482
907
        """Assert that a does not match a regular expression"""
1483
 
        if re.search(needle_re, haystack, flags):
 
908
        if re.search(needle_re, haystack):
1484
909
            raise AssertionError('pattern "%s" found in "%s"'
1485
910
                    % (needle_re, haystack))
1486
911
 
1487
 
    def assertContainsString(self, haystack, needle):
1488
 
        if haystack.find(needle) == -1:
1489
 
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1490
 
 
1491
 
    def assertNotContainsString(self, haystack, needle):
1492
 
        if haystack.find(needle) != -1:
1493
 
            self.fail("string %r found in '''%s'''" % (needle, haystack))
1494
 
 
1495
912
    def assertSubset(self, sublist, superlist):
1496
913
        """Assert that every entry in sublist is present in superlist."""
1497
914
        missing = set(sublist) - set(superlist)
1501
918
 
1502
919
    def assertListRaises(self, excClass, func, *args, **kwargs):
1503
920
        """Fail unless excClass is raised when the iterator from func is used.
1504
 
 
 
921
        
1505
922
        Many functions can return generators this makes sure
1506
923
        to wrap them in a list() call to make sure the whole generator
1507
924
        is run, and that the proper exception is raised.
1554
971
                raise AssertionError("%r is %r." % (left, right))
1555
972
 
1556
973
    def assertTransportMode(self, transport, path, mode):
1557
 
        """Fail if a path does not have mode "mode".
1558
 
 
 
974
        """Fail if a path does not have mode mode.
 
975
        
1559
976
        If modes are not supported on this transport, the assertion is ignored.
1560
977
        """
1561
978
        if not transport._can_roundtrip_unix_modebits():
1563
980
        path_stat = transport.stat(path)
1564
981
        actual_mode = stat.S_IMODE(path_stat.st_mode)
1565
982
        self.assertEqual(mode, actual_mode,
1566
 
                         'mode of %r incorrect (%s != %s)'
1567
 
                         % (path, oct(mode), oct(actual_mode)))
 
983
            'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
1568
984
 
1569
985
    def assertIsSameRealPath(self, path1, path2):
1570
986
        """Fail if path1 and path2 points to different files"""
1572
988
                         osutils.realpath(path2),
1573
989
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1574
990
 
1575
 
    def assertIsInstance(self, obj, kls, msg=None):
1576
 
        """Fail if obj is not an instance of kls
1577
 
        
1578
 
        :param msg: Supplementary message to show if the assertion fails.
1579
 
        """
 
991
    def assertIsInstance(self, obj, kls):
 
992
        """Fail if obj is not an instance of kls"""
1580
993
        if not isinstance(obj, kls):
1581
 
            m = "%r is an instance of %s rather than %s" % (
1582
 
                obj, obj.__class__, kls)
1583
 
            if msg:
1584
 
                m += ": " + msg
1585
 
            self.fail(m)
 
994
            self.fail("%r is an instance of %s rather than %s" % (
 
995
                obj, obj.__class__, kls))
 
996
 
 
997
    def expectFailure(self, reason, assertion, *args, **kwargs):
 
998
        """Invoke a test, expecting it to fail for the given reason.
 
999
 
 
1000
        This is for assertions that ought to succeed, but currently fail.
 
1001
        (The failure is *expected* but not *wanted*.)  Please be very precise
 
1002
        about the failure you're expecting.  If a new bug is introduced,
 
1003
        AssertionError should be raised, not KnownFailure.
 
1004
 
 
1005
        Frequently, expectFailure should be followed by an opposite assertion.
 
1006
        See example below.
 
1007
 
 
1008
        Intended to be used with a callable that raises AssertionError as the
 
1009
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
 
1010
 
 
1011
        Raises KnownFailure if the test fails.  Raises AssertionError if the
 
1012
        test succeeds.
 
1013
 
 
1014
        example usage::
 
1015
 
 
1016
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
 
1017
                             dynamic_val)
 
1018
          self.assertEqual(42, dynamic_val)
 
1019
 
 
1020
          This means that a dynamic_val of 54 will cause the test to raise
 
1021
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
 
1022
          only a dynamic_val of 42 will allow the test to pass.  Anything other
 
1023
          than 54 or 42 will cause an AssertionError.
 
1024
        """
 
1025
        try:
 
1026
            assertion(*args, **kwargs)
 
1027
        except AssertionError:
 
1028
            raise KnownFailure(reason)
 
1029
        else:
 
1030
            self.fail('Unexpected success.  Should have failed: %s' % reason)
1586
1031
 
1587
1032
    def assertFileEqual(self, content, path):
1588
1033
        """Fail if path does not contain 'content'."""
1589
 
        self.assertPathExists(path)
 
1034
        self.failUnlessExists(path)
1590
1035
        f = file(path, 'rb')
1591
1036
        try:
1592
1037
            s = f.read()
1594
1039
            f.close()
1595
1040
        self.assertEqualDiff(content, s)
1596
1041
 
1597
 
    def assertDocstring(self, expected_docstring, obj):
1598
 
        """Fail if obj does not have expected_docstring"""
1599
 
        if __doc__ is None:
1600
 
            # With -OO the docstring should be None instead
1601
 
            self.assertIs(obj.__doc__, None)
1602
 
        else:
1603
 
            self.assertEqual(expected_docstring, obj.__doc__)
1604
 
 
1605
 
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1606
1042
    def failUnlessExists(self, path):
1607
 
        return self.assertPathExists(path)
1608
 
 
1609
 
    def assertPathExists(self, path):
1610
1043
        """Fail unless path or paths, which may be abs or relative, exist."""
1611
1044
        if not isinstance(path, basestring):
1612
1045
            for p in path:
1613
 
                self.assertPathExists(p)
 
1046
                self.failUnlessExists(p)
1614
1047
        else:
1615
 
            self.assertTrue(osutils.lexists(path),
1616
 
                path + " does not exist")
 
1048
            self.failUnless(osutils.lexists(path),path+" does not exist")
1617
1049
 
1618
 
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1619
1050
    def failIfExists(self, path):
1620
 
        return self.assertPathDoesNotExist(path)
1621
 
 
1622
 
    def assertPathDoesNotExist(self, path):
1623
1051
        """Fail if path or paths, which may be abs or relative, exist."""
1624
1052
        if not isinstance(path, basestring):
1625
1053
            for p in path:
1626
 
                self.assertPathDoesNotExist(p)
 
1054
                self.failIfExists(p)
1627
1055
        else:
1628
 
            self.assertFalse(osutils.lexists(path),
1629
 
                path + " exists")
 
1056
            self.failIf(osutils.lexists(path),path+" exists")
1630
1057
 
1631
1058
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1632
1059
        """A helper for callDeprecated and applyDeprecated.
1658
1085
        not other callers that go direct to the warning module.
1659
1086
 
1660
1087
        To test that a deprecated method raises an error, do something like
1661
 
        this (remember that both assertRaises and applyDeprecated delays *args
1662
 
        and **kwargs passing)::
 
1088
        this::
1663
1089
 
1664
1090
            self.assertRaises(errors.ReservedId,
1665
1091
                self.applyDeprecated,
1705
1131
        # warnings.  It's the easiest way to insulate ourselves from -Werror,
1706
1132
        # though.  -- Andrew, 20071062
1707
1133
        wlist = []
1708
 
        def _catcher(message, category, filename, lineno, file=None, line=None):
 
1134
        def _catcher(message, category, filename, lineno, file=None):
1709
1135
            # despite the name, 'message' is normally(?) a Warning subclass
1710
1136
            # instance
1711
1137
            wlist.append(message)
1723
1149
    def callDeprecated(self, expected, callable, *args, **kwargs):
1724
1150
        """Assert that a callable is deprecated in a particular way.
1725
1151
 
1726
 
        This is a very precise test for unusual requirements. The
 
1152
        This is a very precise test for unusual requirements. The 
1727
1153
        applyDeprecated helper function is probably more suited for most tests
1728
1154
        as it allows you to simply specify the deprecation format being used
1729
1155
        and will ensure that that is issued for the function being called.
1743
1169
        return result
1744
1170
 
1745
1171
    def _startLogFile(self):
1746
 
        """Setup a in-memory target for bzr and testcase log messages"""
1747
 
        pseudo_log_file = StringIO()
1748
 
        def _get_log_contents_for_weird_testtools_api():
1749
 
            return [pseudo_log_file.getvalue().decode(
1750
 
                "utf-8", "replace").encode("utf-8")]
1751
 
        self.addDetail("log", content.Content(content.ContentType("text",
1752
 
            "plain", {"charset": "utf8"}),
1753
 
            _get_log_contents_for_weird_testtools_api))
1754
 
        self._log_file = pseudo_log_file
1755
 
        self._log_memento = trace.push_log_file(self._log_file)
 
1172
        """Send bzr and test log messages to a temporary file.
 
1173
 
 
1174
        The file is removed as the test is torn down.
 
1175
        """
 
1176
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
 
1177
        self._log_file = os.fdopen(fileno, 'w+')
 
1178
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
 
1179
        self._log_file_name = name
1756
1180
        self.addCleanup(self._finishLogFile)
1757
1181
 
1758
1182
    def _finishLogFile(self):
1759
 
        """Flush and dereference the in-memory log for this testcase"""
1760
 
        if trace._trace_file:
1761
 
            # flush the log file, to get all content
1762
 
            trace._trace_file.flush()
1763
 
        trace.pop_log_file(self._log_memento)
1764
 
        # The logging module now tracks references for cleanup so discard ours
1765
 
        del self._log_memento
1766
 
 
1767
 
    def thisFailsStrictLockCheck(self):
1768
 
        """It is known that this test would fail with -Dstrict_locks.
1769
 
 
1770
 
        By default, all tests are run with strict lock checking unless
1771
 
        -Edisable_lock_checks is supplied. However there are some tests which
1772
 
        we know fail strict locks at this point that have not been fixed.
1773
 
        They should call this function to disable the strict checking.
1774
 
 
1775
 
        This should be used sparingly, it is much better to fix the locking
1776
 
        issues rather than papering over the problem by calling this function.
1777
 
        """
1778
 
        debug.debug_flags.discard('strict_locks')
1779
 
 
1780
 
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1781
 
        """Overrides an object attribute restoring it after the test.
1782
 
 
1783
 
        :note: This should be used with discretion; you should think about
1784
 
        whether it's better to make the code testable without monkey-patching.
1785
 
 
1786
 
        :param obj: The object that will be mutated.
1787
 
 
1788
 
        :param attr_name: The attribute name we want to preserve/override in
1789
 
            the object.
1790
 
 
1791
 
        :param new: The optional value we want to set the attribute to.
1792
 
 
1793
 
        :returns: The actual attr value.
1794
 
        """
1795
 
        # The actual value is captured by the call below
1796
 
        value = getattr(obj, attr_name, _unitialized_attr)
1797
 
        if value is _unitialized_attr:
1798
 
            # When the test completes, the attribute should not exist, but if
1799
 
            # we aren't setting a value, we don't need to do anything.
1800
 
            if new is not _unitialized_attr:
1801
 
                self.addCleanup(delattr, obj, attr_name)
1802
 
        else:
1803
 
            self.addCleanup(setattr, obj, attr_name, value)
1804
 
        if new is not _unitialized_attr:
1805
 
            setattr(obj, attr_name, new)
1806
 
        return value
1807
 
 
1808
 
    def overrideEnv(self, name, new):
1809
 
        """Set an environment variable, and reset it after the test.
1810
 
 
1811
 
        :param name: The environment variable name.
1812
 
 
1813
 
        :param new: The value to set the variable to. If None, the 
1814
 
            variable is deleted from the environment.
1815
 
 
1816
 
        :returns: The actual variable value.
1817
 
        """
1818
 
        value = osutils.set_or_unset_env(name, new)
1819
 
        self.addCleanup(osutils.set_or_unset_env, name, value)
1820
 
        return value
1821
 
 
1822
 
    def recordCalls(self, obj, attr_name):
1823
 
        """Monkeypatch in a wrapper that will record calls.
1824
 
 
1825
 
        The monkeypatch is automatically removed when the test concludes.
1826
 
 
1827
 
        :param obj: The namespace holding the reference to be replaced;
1828
 
            typically a module, class, or object.
1829
 
        :param attr_name: A string for the name of the attribute to 
1830
 
            patch.
1831
 
        :returns: A list that will be extended with one item every time the
1832
 
            function is called, with a tuple of (args, kwargs).
1833
 
        """
1834
 
        calls = []
1835
 
 
1836
 
        def decorator(*args, **kwargs):
1837
 
            calls.append((args, kwargs))
1838
 
            return orig(*args, **kwargs)
1839
 
        orig = self.overrideAttr(obj, attr_name, decorator)
1840
 
        return calls
 
1183
        """Finished with the log file.
 
1184
 
 
1185
        Close the file and delete it, unless setKeepLogfile was called.
 
1186
        """
 
1187
        if self._log_file is None:
 
1188
            return
 
1189
        bzrlib.trace.pop_log_file(self._log_memento)
 
1190
        self._log_file.close()
 
1191
        self._log_file = None
 
1192
        if not self._keep_log_file:
 
1193
            os.remove(self._log_file_name)
 
1194
            self._log_file_name = None
 
1195
 
 
1196
    def setKeepLogfile(self):
 
1197
        """Make the logfile not be deleted when _finishLogFile is called."""
 
1198
        self._keep_log_file = True
 
1199
 
 
1200
    def addCleanup(self, callable, *args, **kwargs):
 
1201
        """Arrange to run a callable when this case is torn down.
 
1202
 
 
1203
        Callables are run in the reverse of the order they are registered, 
 
1204
        ie last-in first-out.
 
1205
        """
 
1206
        self._cleanups.append((callable, args, kwargs))
1841
1207
 
1842
1208
    def _cleanEnvironment(self):
1843
 
        for name, value in isolated_environ.iteritems():
1844
 
            self.overrideEnv(name, value)
 
1209
        new_env = {
 
1210
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
 
1211
            'HOME': os.getcwd(),
 
1212
            'APPDATA': None,  # bzr now use Win32 API and don't rely on APPDATA
 
1213
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
1214
            'BZR_EMAIL': None,
 
1215
            'BZREMAIL': None, # may still be present in the environment
 
1216
            'EMAIL': None,
 
1217
            'BZR_PROGRESS_BAR': None,
 
1218
            'BZR_LOG': None,
 
1219
            # SSH Agent
 
1220
            'SSH_AUTH_SOCK': None,
 
1221
            # Proxies
 
1222
            'http_proxy': None,
 
1223
            'HTTP_PROXY': None,
 
1224
            'https_proxy': None,
 
1225
            'HTTPS_PROXY': None,
 
1226
            'no_proxy': None,
 
1227
            'NO_PROXY': None,
 
1228
            'all_proxy': None,
 
1229
            'ALL_PROXY': None,
 
1230
            # Nobody cares about these ones AFAIK. So far at
 
1231
            # least. If you do (care), please update this comment
 
1232
            # -- vila 20061212
 
1233
            'ftp_proxy': None,
 
1234
            'FTP_PROXY': None,
 
1235
            'BZR_REMOTE_PATH': None,
 
1236
        }
 
1237
        self.__old_env = {}
 
1238
        self.addCleanup(self._restoreEnvironment)
 
1239
        for name, value in new_env.iteritems():
 
1240
            self._captureVar(name, value)
 
1241
 
 
1242
    def _captureVar(self, name, newvalue):
 
1243
        """Set an environment variable, and reset it when finished."""
 
1244
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
 
1245
 
 
1246
    def _restore_debug_flags(self):
 
1247
        debug.debug_flags.clear()
 
1248
        debug.debug_flags.update(self._preserved_debug_flags)
 
1249
 
 
1250
    def _restoreEnvironment(self):
 
1251
        for name, value in self.__old_env.iteritems():
 
1252
            osutils.set_or_unset_env(name, value)
1845
1253
 
1846
1254
    def _restoreHooks(self):
1847
 
        for klass, (name, hooks) in self._preserved_hooks.items():
1848
 
            setattr(klass, name, hooks)
1849
 
        self._preserved_hooks.clear()
1850
 
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
1851
 
        self._preserved_lazy_hooks.clear()
 
1255
        for klass, hooks in self._preserved_hooks.items():
 
1256
            setattr(klass, 'hooks', hooks)
1852
1257
 
1853
1258
    def knownFailure(self, reason):
1854
 
        """Declare that this test fails for a known reason
1855
 
 
1856
 
        Tests that are known to fail should generally be using expectedFailure
1857
 
        with an appropriate reverse assertion if a change could cause the test
1858
 
        to start passing. Conversely if the test has no immediate prospect of
1859
 
        succeeding then using skip is more suitable.
1860
 
 
1861
 
        When this method is called while an exception is being handled, that
1862
 
        traceback will be used, otherwise a new exception will be thrown to
1863
 
        provide one but won't be reported.
1864
 
        """
1865
 
        self._add_reason(reason)
 
1259
        """This test has failed for some known reason."""
 
1260
        raise KnownFailure(reason)
 
1261
 
 
1262
    def run(self, result=None):
 
1263
        if result is None: result = self.defaultTestResult()
 
1264
        for feature in getattr(self, '_test_needs_features', []):
 
1265
            if not feature.available():
 
1266
                result.startTest(self)
 
1267
                if getattr(result, 'addNotSupported', None):
 
1268
                    result.addNotSupported(self, feature)
 
1269
                else:
 
1270
                    result.addSuccess(self)
 
1271
                result.stopTest(self)
 
1272
                return
1866
1273
        try:
1867
 
            exc_info = sys.exc_info()
1868
 
            if exc_info != (None, None, None):
1869
 
                self._report_traceback(exc_info)
1870
 
            else:
1871
 
                try:
1872
 
                    raise self.failureException(reason)
1873
 
                except self.failureException:
1874
 
                    exc_info = sys.exc_info()
1875
 
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
1876
 
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1274
            return unittest.TestCase.run(self, result)
1877
1275
        finally:
1878
 
            del exc_info
1879
 
 
1880
 
    def _suppress_log(self):
1881
 
        """Remove the log info from details."""
1882
 
        self.discardDetail('log')
1883
 
 
1884
 
    def _do_skip(self, result, reason):
1885
 
        self._suppress_log()
1886
 
        addSkip = getattr(result, 'addSkip', None)
1887
 
        if not callable(addSkip):
1888
 
            result.addSuccess(result)
1889
 
        else:
1890
 
            addSkip(self, reason)
1891
 
 
1892
 
    @staticmethod
1893
 
    def _do_known_failure(self, result, e):
1894
 
        self._suppress_log()
1895
 
        err = sys.exc_info()
1896
 
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1897
 
        if addExpectedFailure is not None:
1898
 
            addExpectedFailure(self, err)
1899
 
        else:
1900
 
            result.addSuccess(self)
1901
 
 
1902
 
    @staticmethod
1903
 
    def _do_not_applicable(self, result, e):
1904
 
        if not e.args:
1905
 
            reason = 'No reason given'
1906
 
        else:
1907
 
            reason = e.args[0]
1908
 
        self._suppress_log ()
1909
 
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1910
 
        if addNotApplicable is not None:
1911
 
            result.addNotApplicable(self, reason)
1912
 
        else:
1913
 
            self._do_skip(result, reason)
1914
 
 
1915
 
    @staticmethod
1916
 
    def _report_skip(self, result, err):
1917
 
        """Override the default _report_skip.
1918
 
 
1919
 
        We want to strip the 'log' detail. If we waint until _do_skip, it has
1920
 
        already been formatted into the 'reason' string, and we can't pull it
1921
 
        out again.
1922
 
        """
1923
 
        self._suppress_log()
1924
 
        super(TestCase, self)._report_skip(self, result, err)
1925
 
 
1926
 
    @staticmethod
1927
 
    def _report_expected_failure(self, result, err):
1928
 
        """Strip the log.
1929
 
 
1930
 
        See _report_skip for motivation.
1931
 
        """
1932
 
        self._suppress_log()
1933
 
        super(TestCase, self)._report_expected_failure(self, result, err)
1934
 
 
1935
 
    @staticmethod
1936
 
    def _do_unsupported_or_skip(self, result, e):
1937
 
        reason = e.args[0]
1938
 
        self._suppress_log()
1939
 
        addNotSupported = getattr(result, 'addNotSupported', None)
1940
 
        if addNotSupported is not None:
1941
 
            result.addNotSupported(self, reason)
1942
 
        else:
1943
 
            self._do_skip(result, reason)
 
1276
            saved_attrs = {}
 
1277
            absent_attr = object()
 
1278
            for attr_name in self.attrs_to_keep:
 
1279
                attr = getattr(self, attr_name, absent_attr)
 
1280
                if attr is not absent_attr:
 
1281
                    saved_attrs[attr_name] = attr
 
1282
            self.__dict__ = saved_attrs
 
1283
 
 
1284
    def tearDown(self):
 
1285
        self._runCleanups()
 
1286
        unittest.TestCase.tearDown(self)
1944
1287
 
1945
1288
    def time(self, callable, *args, **kwargs):
1946
1289
        """Run callable and accrue the time it takes to the benchmark time.
1947
 
 
 
1290
        
1948
1291
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
1949
1292
        this will cause lsprofile statistics to be gathered and stored in
1950
1293
        self._benchcalls.
1951
1294
        """
1952
1295
        if self._benchtime is None:
1953
 
            self.addDetail('benchtime', content.Content(content.ContentType(
1954
 
                "text", "plain"), lambda:[str(self._benchtime)]))
1955
1296
            self._benchtime = 0
1956
1297
        start = time.time()
1957
1298
        try:
1966
1307
        finally:
1967
1308
            self._benchtime += time.time() - start
1968
1309
 
 
1310
    def _runCleanups(self):
 
1311
        """Run registered cleanup functions. 
 
1312
 
 
1313
        This should only be called from TestCase.tearDown.
 
1314
        """
 
1315
        # TODO: Perhaps this should keep running cleanups even if 
 
1316
        # one of them fails?
 
1317
 
 
1318
        # Actually pop the cleanups from the list so tearDown running
 
1319
        # twice is safe (this happens for skipped tests).
 
1320
        while self._cleanups:
 
1321
            cleanup, args, kwargs = self._cleanups.pop()
 
1322
            cleanup(*args, **kwargs)
 
1323
 
1969
1324
    def log(self, *args):
1970
 
        trace.mutter(*args)
1971
 
 
1972
 
    def get_log(self):
1973
 
        """Get a unicode string containing the log from bzrlib.trace.
1974
 
 
1975
 
        Undecodable characters are replaced.
 
1325
        mutter(*args)
 
1326
 
 
1327
    def _get_log(self, keep_log_file=False):
 
1328
        """Get the log from bzrlib.trace calls from this test.
 
1329
 
 
1330
        :param keep_log_file: When True, if the log is still a file on disk
 
1331
            leave it as a file on disk. When False, if the log is still a file
 
1332
            on disk, the log file is deleted and the log preserved as
 
1333
            self._log_contents.
 
1334
        :return: A string containing the log.
1976
1335
        """
1977
 
        return u"".join(self.getDetails()['log'].iter_text())
 
1336
        # flush the log file, to get all content
 
1337
        import bzrlib.trace
 
1338
        bzrlib.trace._trace_file.flush()
 
1339
        if self._log_contents:
 
1340
            # XXX: this can hardly contain the content flushed above --vila
 
1341
            # 20080128
 
1342
            return self._log_contents
 
1343
        if self._log_file_name is not None:
 
1344
            logfile = open(self._log_file_name)
 
1345
            try:
 
1346
                log_contents = logfile.read()
 
1347
            finally:
 
1348
                logfile.close()
 
1349
            if not keep_log_file:
 
1350
                self._log_contents = log_contents
 
1351
                try:
 
1352
                    os.remove(self._log_file_name)
 
1353
                except OSError, e:
 
1354
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
 
1355
                        sys.stderr.write(('Unable to delete log file '
 
1356
                                             ' %r\n' % self._log_file_name))
 
1357
                    else:
 
1358
                        raise
 
1359
            return log_contents
 
1360
        else:
 
1361
            return "DELETED log file to reduce memory footprint"
1978
1362
 
1979
1363
    def requireFeature(self, feature):
1980
1364
        """This test requires a specific feature is available.
1997
1381
 
1998
1382
    def _run_bzr_core(self, args, retcode, encoding, stdin,
1999
1383
            working_dir):
2000
 
        # Clear chk_map page cache, because the contents are likely to mask
2001
 
        # locking errors.
2002
 
        chk_map.clear_cache()
2003
1384
        if encoding is None:
2004
 
            encoding = osutils.get_user_encoding()
 
1385
            encoding = bzrlib.user_encoding
2005
1386
        stdout = StringIOWrapper()
2006
1387
        stderr = StringIOWrapper()
2007
1388
        stdout.encoding = encoding
2009
1390
 
2010
1391
        self.log('run bzr: %r', args)
2011
1392
        # FIXME: don't call into logging here
2012
 
        handler = trace.EncodedStreamHandler(stderr, errors="replace",
2013
 
            level=logging.INFO)
 
1393
        handler = logging.StreamHandler(stderr)
 
1394
        handler.setLevel(logging.INFO)
2014
1395
        logger = logging.getLogger('')
2015
1396
        logger.addHandler(handler)
2016
1397
        old_ui_factory = ui.ui_factory
2022
1403
            os.chdir(working_dir)
2023
1404
 
2024
1405
        try:
2025
 
            try:
2026
 
                result = self.apply_redirected(
2027
 
                    ui.ui_factory.stdin,
2028
 
                    stdout, stderr,
2029
 
                    _mod_commands.run_bzr_catch_user_errors,
2030
 
                    args)
2031
 
            except KeyboardInterrupt:
2032
 
                # Reraise KeyboardInterrupt with contents of redirected stdout
2033
 
                # and stderr as arguments, for tests which are interested in
2034
 
                # stdout and stderr and are expecting the exception.
2035
 
                out = stdout.getvalue()
2036
 
                err = stderr.getvalue()
2037
 
                if out:
2038
 
                    self.log('output:\n%r', out)
2039
 
                if err:
2040
 
                    self.log('errors:\n%r', err)
2041
 
                raise KeyboardInterrupt(out, err)
 
1406
            result = self.apply_redirected(ui.ui_factory.stdin,
 
1407
                stdout, stderr,
 
1408
                bzrlib.commands.run_bzr_catch_user_errors,
 
1409
                args)
2042
1410
        finally:
2043
1411
            logger.removeHandler(handler)
2044
1412
            ui.ui_factory = old_ui_factory
2052
1420
        if err:
2053
1421
            self.log('errors:\n%r', err)
2054
1422
        if retcode is not None:
2055
 
            self.assertEqual(retcode, result,
 
1423
            self.assertEquals(retcode, result,
2056
1424
                              message='Unexpected return code')
2057
 
        return result, out, err
 
1425
        return out, err
2058
1426
 
2059
1427
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
2060
1428
                working_dir=None, error_regexes=[], output_encoding=None):
2065
1433
        passed in three ways:
2066
1434
 
2067
1435
        1- A list of strings, eg ["commit", "a"].  This is recommended
2068
 
        when the command contains whitespace or metacharacters, or
 
1436
        when the command contains whitespace or metacharacters, or 
2069
1437
        is built up at run time.
2070
1438
 
2071
 
        2- A single string, eg "add a".  This is the most convenient
 
1439
        2- A single string, eg "add a".  This is the most convenient 
2072
1440
        for hardcoded commands.
2073
1441
 
2074
1442
        This runs bzr through the interface that catches and reports
2089
1457
        :keyword error_regexes: A list of expected error messages.  If
2090
1458
            specified they must be seen in the error output of the command.
2091
1459
        """
2092
 
        retcode, out, err = self._run_bzr_autosplit(
 
1460
        out, err = self._run_bzr_autosplit(
2093
1461
            args=args,
2094
1462
            retcode=retcode,
2095
1463
            encoding=encoding,
2096
1464
            stdin=stdin,
2097
1465
            working_dir=working_dir,
2098
1466
            )
2099
 
        self.assertIsInstance(error_regexes, (list, tuple))
2100
1467
        for regex in error_regexes:
2101
1468
            self.assertContainsRe(err, regex)
2102
1469
        return out, err
2134
1501
    def run_bzr_subprocess(self, *args, **kwargs):
2135
1502
        """Run bzr in a subprocess for testing.
2136
1503
 
2137
 
        This starts a new Python interpreter and runs bzr in there.
 
1504
        This starts a new Python interpreter and runs bzr in there. 
2138
1505
        This should only be used for tests that have a justifiable need for
2139
1506
        this isolation: e.g. they are testing startup time, or signal
2140
 
        handling, or early startup code, etc.  Subprocess code can't be
 
1507
        handling, or early startup code, etc.  Subprocess code can't be 
2141
1508
        profiled or debugged so easily.
2142
1509
 
2143
1510
        :keyword retcode: The status code that is expected.  Defaults to 0.  If
2174
1541
    def start_bzr_subprocess(self, process_args, env_changes=None,
2175
1542
                             skip_if_plan_to_signal=False,
2176
1543
                             working_dir=None,
2177
 
                             allow_plugins=False, stderr=subprocess.PIPE):
 
1544
                             allow_plugins=False):
2178
1545
        """Start bzr in a subprocess for testing.
2179
1546
 
2180
1547
        This starts a new Python interpreter and runs bzr in there.
2189
1556
            variables. A value of None will unset the env variable.
2190
1557
            The values must be strings. The change will only occur in the
2191
1558
            child, so you don't need to fix the environment after running.
2192
 
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
2193
 
            doesn't support signalling subprocesses.
 
1559
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
 
1560
            is not available.
2194
1561
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
2195
 
        :param stderr: file to use for the subprocess's stderr.  Valid values
2196
 
            are those valid for the stderr argument of `subprocess.Popen`.
2197
 
            Default value is ``subprocess.PIPE``.
2198
1562
 
2199
1563
        :returns: Popen object for the started process.
2200
1564
        """
2201
1565
        if skip_if_plan_to_signal:
2202
 
            if os.name != "posix":
2203
 
                raise TestSkipped("Sending signals not supported")
 
1566
            if not getattr(os, 'kill', None):
 
1567
                raise TestSkipped("os.kill not available.")
2204
1568
 
2205
1569
        if env_changes is None:
2206
1570
            env_changes = {}
2207
 
        # Because $HOME is set to a tempdir for the context of a test, modules
2208
 
        # installed in the user dir will not be found unless $PYTHONUSERBASE
2209
 
        # gets set to the computed directory of this parent process.
2210
 
        if site.USER_BASE is not None:
2211
 
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
2212
1571
        old_env = {}
2213
1572
 
2214
1573
        def cleanup_environment():
2231
1590
            # so we will avoid using it on all platforms, just to
2232
1591
            # make sure the code path is used, and we don't break on win32
2233
1592
            cleanup_environment()
2234
 
            # Include the subprocess's log file in the test details, in case
2235
 
            # the test fails due to an error in the subprocess.
2236
 
            self._add_subprocess_log(trace._get_bzr_log_filename())
2237
1593
            command = [sys.executable]
2238
1594
            # frozen executables don't need the path to bzr
2239
1595
            if getattr(sys, "frozen", None) is None:
2241
1597
            if not allow_plugins:
2242
1598
                command.append('--no-plugins')
2243
1599
            command.extend(process_args)
2244
 
            process = self._popen(command, stdin=subprocess.PIPE,
2245
 
                                  stdout=subprocess.PIPE,
2246
 
                                  stderr=stderr)
 
1600
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
2247
1601
        finally:
2248
1602
            restore_environment()
2249
1603
            if cwd is not None:
2251
1605
 
2252
1606
        return process
2253
1607
 
2254
 
    def _add_subprocess_log(self, log_file_path):
2255
 
        if len(self._log_files) == 0:
2256
 
            # Register an addCleanup func.  We do this on the first call to
2257
 
            # _add_subprocess_log rather than in TestCase.setUp so that this
2258
 
            # addCleanup is registered after any cleanups for tempdirs that
2259
 
            # subclasses might create, which will probably remove the log file
2260
 
            # we want to read.
2261
 
            self.addCleanup(self._subprocess_log_cleanup)
2262
 
        # self._log_files is a set, so if a log file is reused we won't grab it
2263
 
        # twice.
2264
 
        self._log_files.add(log_file_path)
2265
 
 
2266
 
    def _subprocess_log_cleanup(self):
2267
 
        for count, log_file_path in enumerate(self._log_files):
2268
 
            # We use buffer_now=True to avoid holding the file open beyond
2269
 
            # the life of this function, which might interfere with e.g.
2270
 
            # cleaning tempdirs on Windows.
2271
 
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
2272
 
            #detail_content = content.content_from_file(
2273
 
            #    log_file_path, buffer_now=True)
2274
 
            with open(log_file_path, 'rb') as log_file:
2275
 
                log_file_bytes = log_file.read()
2276
 
            detail_content = content.Content(content.ContentType("text",
2277
 
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
2278
 
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
2279
 
                detail_content)
2280
 
 
2281
1608
    def _popen(self, *args, **kwargs):
2282
1609
        """Place a call to Popen.
2283
1610
 
2284
1611
        Allows tests to override this method to intercept the calls made to
2285
1612
        Popen for introspection.
2286
1613
        """
2287
 
        return subprocess.Popen(*args, **kwargs)
2288
 
 
2289
 
    def get_source_path(self):
2290
 
        """Return the path of the directory containing bzrlib."""
2291
 
        return os.path.dirname(os.path.dirname(bzrlib.__file__))
 
1614
        return Popen(*args, **kwargs)
2292
1615
 
2293
1616
    def get_bzr_path(self):
2294
1617
        """Return the path of the 'bzr' executable for this test suite."""
2295
 
        bzr_path = os.path.join(self.get_source_path(), "bzr")
 
1618
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
2296
1619
        if not os.path.isfile(bzr_path):
2297
1620
            # We are probably installed. Assume sys.argv is the right file
2298
1621
            bzr_path = sys.argv[0]
2320
1643
        if retcode is not None and retcode != process.returncode:
2321
1644
            if process_args is None:
2322
1645
                process_args = "(unknown args)"
2323
 
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
2324
 
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
 
1646
            mutter('Output of bzr %s:\n%s', process_args, out)
 
1647
            mutter('Error for bzr %s:\n%s', process_args, err)
2325
1648
            self.fail('Command bzr %s failed with retcode %s != %s'
2326
1649
                      % (process_args, retcode, process.returncode))
2327
1650
        return [out, err]
2328
1651
 
2329
 
    def check_tree_shape(self, tree, shape):
2330
 
        """Compare a tree to a list of expected names.
 
1652
    def check_inventory_shape(self, inv, shape):
 
1653
        """Compare an inventory to a list of expected names.
2331
1654
 
2332
1655
        Fail if they are not precisely equal.
2333
1656
        """
2334
1657
        extras = []
2335
1658
        shape = list(shape)             # copy
2336
 
        for path, ie in tree.iter_entries_by_dir():
 
1659
        for path, ie in inv.entries():
2337
1660
            name = path.replace('\\', '/')
2338
1661
            if ie.kind == 'directory':
2339
1662
                name = name + '/'
2340
 
            if name == "/":
2341
 
                pass # ignore root entry
2342
 
            elif name in shape:
 
1663
            if name in shape:
2343
1664
                shape.remove(name)
2344
1665
            else:
2345
1666
                extras.append(name)
2386
1707
 
2387
1708
        Tests that expect to provoke LockContention errors should call this.
2388
1709
        """
2389
 
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
1710
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
 
1711
        def resetTimeout():
 
1712
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
 
1713
        self.addCleanup(resetTimeout)
 
1714
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
2390
1715
 
2391
1716
    def make_utf8_encoded_stringio(self, encoding_type=None):
2392
1717
        """Return a StringIOWrapper instance, that will encode Unicode
2400
1725
        sio.encoding = output_encoding
2401
1726
        return sio
2402
1727
 
2403
 
    def disable_verb(self, verb):
2404
 
        """Disable a smart server verb for one test."""
2405
 
        from bzrlib.smart import request
2406
 
        request_handlers = request.request_handlers
2407
 
        orig_method = request_handlers.get(verb)
2408
 
        orig_info = request_handlers.get_info(verb)
2409
 
        request_handlers.remove(verb)
2410
 
        self.addCleanup(request_handlers.register, verb, orig_method,
2411
 
            info=orig_info)
2412
 
 
2413
 
 
2414
 
class CapturedCall(object):
2415
 
    """A helper for capturing smart server calls for easy debug analysis."""
2416
 
 
2417
 
    def __init__(self, params, prefix_length):
2418
 
        """Capture the call with params and skip prefix_length stack frames."""
2419
 
        self.call = params
2420
 
        import traceback
2421
 
        # The last 5 frames are the __init__, the hook frame, and 3 smart
2422
 
        # client frames. Beyond this we could get more clever, but this is good
2423
 
        # enough for now.
2424
 
        stack = traceback.extract_stack()[prefix_length:-5]
2425
 
        self.stack = ''.join(traceback.format_list(stack))
2426
 
 
2427
 
    def __str__(self):
2428
 
        return self.call.method
2429
 
 
2430
 
    def __repr__(self):
2431
 
        return self.call.method
2432
 
 
2433
 
    def stack(self):
2434
 
        return self.stack
2435
 
 
2436
1728
 
2437
1729
class TestCaseWithMemoryTransport(TestCase):
2438
1730
    """Common test class for tests that do not need disk resources.
2439
1731
 
2440
 
    Tests that need disk resources should derive from TestCaseInTempDir
2441
 
    orTestCaseWithTransport.
 
1732
    Tests that need disk resources should derive from TestCaseWithTransport.
2442
1733
 
2443
1734
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2444
1735
 
2445
 
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
 
1736
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
2446
1737
    a directory which does not exist. This serves to help ensure test isolation
2447
 
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
2448
 
    must exist. However, TestCaseWithMemoryTransport does not offer local file
2449
 
    defaults for the transport in tests, nor does it obey the command line
 
1738
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
 
1739
    must exist. However, TestCaseWithMemoryTransport does not offer local
 
1740
    file defaults for the transport in tests, nor does it obey the command line
2450
1741
    override, so tests that accidentally write to the common directory should
2451
1742
    be rare.
2452
1743
 
2453
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
2454
 
        ``.bzr`` directory that stops us ascending higher into the filesystem.
 
1744
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
 
1745
    a .bzr directory that stops us ascending higher into the filesystem.
2455
1746
    """
2456
1747
 
2457
1748
    TEST_ROOT = None
2459
1750
 
2460
1751
    def __init__(self, methodName='runTest'):
2461
1752
        # allow test parameterization after test construction and before test
2462
 
        # execution. Variables that the parameterizer sets need to be
 
1753
        # execution. Variables that the parameterizer sets need to be 
2463
1754
        # ones that are not set by setUp, or setUp will trash them.
2464
1755
        super(TestCaseWithMemoryTransport, self).__init__(methodName)
2465
1756
        self.vfs_transport_factory = default_transport
2467
1758
        self.transport_readonly_server = None
2468
1759
        self.__vfs_server = None
2469
1760
 
2470
 
    def setUp(self):
2471
 
        super(TestCaseWithMemoryTransport, self).setUp()
2472
 
 
2473
 
        def _add_disconnect_cleanup(transport):
2474
 
            """Schedule disconnection of given transport at test cleanup
2475
 
 
2476
 
            This needs to happen for all connected transports or leaks occur.
2477
 
 
2478
 
            Note reconnections may mean we call disconnect multiple times per
2479
 
            transport which is suboptimal but seems harmless.
2480
 
            """
2481
 
            self.addCleanup(transport.disconnect)
2482
 
 
2483
 
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
2484
 
            _add_disconnect_cleanup, None)
2485
 
 
2486
 
        self._make_test_root()
2487
 
        self.addCleanup(os.chdir, os.getcwdu())
2488
 
        self.makeAndChdirToTestDir()
2489
 
        self.overrideEnvironmentForTesting()
2490
 
        self.__readonly_server = None
2491
 
        self.__server = None
2492
 
        self.reduceLockdirTimeout()
2493
 
        # Each test may use its own config files even if the local config files
2494
 
        # don't actually exist. They'll rightly fail if they try to create them
2495
 
        # though.
2496
 
        self.overrideAttr(config, '_shared_stores', {})
2497
 
 
2498
1761
    def get_transport(self, relpath=None):
2499
1762
        """Return a writeable transport.
2500
1763
 
2501
1764
        This transport is for the test scratch space relative to
2502
1765
        "self._test_root"
2503
 
 
 
1766
        
2504
1767
        :param relpath: a path relative to the base url.
2505
1768
        """
2506
 
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
 
1769
        t = get_transport(self.get_url(relpath))
2507
1770
        self.assertFalse(t.is_readonly())
2508
1771
        return t
2509
1772
 
2510
1773
    def get_readonly_transport(self, relpath=None):
2511
1774
        """Return a readonly transport for the test scratch space
2512
 
 
 
1775
        
2513
1776
        This can be used to test that operations which should only need
2514
1777
        readonly access in fact do not try to write.
2515
1778
 
2516
1779
        :param relpath: a path relative to the base url.
2517
1780
        """
2518
 
        t = _mod_transport.get_transport_from_url(
2519
 
            self.get_readonly_url(relpath))
 
1781
        t = get_transport(self.get_readonly_url(relpath))
2520
1782
        self.assertTrue(t.is_readonly())
2521
1783
        return t
2522
1784
 
2535
1797
        if self.__readonly_server is None:
2536
1798
            if self.transport_readonly_server is None:
2537
1799
                # readonly decorator requested
2538
 
                self.__readonly_server = test_server.ReadonlyServer()
 
1800
                # bring up the server
 
1801
                self.__readonly_server = ReadonlyServer()
 
1802
                self.__readonly_server.setUp(self.get_vfs_only_server())
2539
1803
            else:
2540
 
                # explicit readonly transport.
2541
1804
                self.__readonly_server = self.create_transport_readonly_server()
2542
 
            self.start_server(self.__readonly_server,
2543
 
                self.get_vfs_only_server())
 
1805
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
1806
            self.addCleanup(self.__readonly_server.tearDown)
2544
1807
        return self.__readonly_server
2545
1808
 
2546
1809
    def get_readonly_url(self, relpath=None):
2547
1810
        """Get a URL for the readonly transport.
2548
1811
 
2549
 
        This will either be backed by '.' or a decorator to the transport
 
1812
        This will either be backed by '.' or a decorator to the transport 
2550
1813
        used by self.get_url()
2551
1814
        relpath provides for clients to get a path relative to the base url.
2552
1815
        These should only be downwards relative, not upwards.
2564
1827
        is no means to override it.
2565
1828
        """
2566
1829
        if self.__vfs_server is None:
2567
 
            self.__vfs_server = memory.MemoryServer()
2568
 
            self.start_server(self.__vfs_server)
 
1830
            self.__vfs_server = MemoryServer()
 
1831
            self.__vfs_server.setUp()
 
1832
            self.addCleanup(self.__vfs_server.tearDown)
2569
1833
        return self.__vfs_server
2570
1834
 
2571
1835
    def get_server(self):
2578
1842
        then the self.get_vfs_server is returned.
2579
1843
        """
2580
1844
        if self.__server is None:
2581
 
            if (self.transport_server is None or self.transport_server is
2582
 
                self.vfs_transport_factory):
2583
 
                self.__server = self.get_vfs_only_server()
 
1845
            if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
 
1846
                return self.get_vfs_only_server()
2584
1847
            else:
2585
1848
                # bring up a decorated means of access to the vfs only server.
2586
1849
                self.__server = self.transport_server()
2587
 
                self.start_server(self.__server, self.get_vfs_only_server())
 
1850
                try:
 
1851
                    self.__server.setUp(self.get_vfs_only_server())
 
1852
                except TypeError, e:
 
1853
                    # This should never happen; the try:Except here is to assist
 
1854
                    # developers having to update code rather than seeing an
 
1855
                    # uninformative TypeError.
 
1856
                    raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
 
1857
            self.addCleanup(self.__server.tearDown)
2588
1858
        return self.__server
2589
1859
 
2590
1860
    def _adjust_url(self, base, relpath):
2643
1913
        real branch.
2644
1914
        """
2645
1915
        root = TestCaseWithMemoryTransport.TEST_ROOT
2646
 
        try:
2647
 
            # Make sure we get a readable and accessible home for .bzr.log
2648
 
            # and/or config files, and not fallback to weird defaults (see
2649
 
            # http://pad.lv/825027).
2650
 
            self.assertIs(None, os.environ.get('BZR_HOME', None))
2651
 
            os.environ['BZR_HOME'] = root
2652
 
            wt = controldir.ControlDir.create_standalone_workingtree(root)
2653
 
            del os.environ['BZR_HOME']
2654
 
        except Exception, e:
2655
 
            self.fail("Fail to initialize the safety net: %r\n" % (e,))
2656
 
        # Hack for speed: remember the raw bytes of the dirstate file so that
2657
 
        # we don't need to re-open the wt to check it hasn't changed.
2658
 
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
2659
 
            wt.control_transport.get_bytes('dirstate'))
 
1916
        bzrdir.BzrDir.create_standalone_workingtree(root)
2660
1917
 
2661
1918
    def _check_safety_net(self):
2662
1919
        """Check that the safety .bzr directory have not been touched.
2665
1922
        propagating. This method ensures than a test did not leaked.
2666
1923
        """
2667
1924
        root = TestCaseWithMemoryTransport.TEST_ROOT
2668
 
        t = _mod_transport.get_transport_from_path(root)
2669
 
        self.permit_url(t.base)
2670
 
        if (t.get_bytes('.bzr/checkout/dirstate') != 
2671
 
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
 
1925
        wt = workingtree.WorkingTree.open(root)
 
1926
        last_rev = wt.last_revision()
 
1927
        if last_rev != 'null:':
2672
1928
            # The current test have modified the /bzr directory, we need to
2673
1929
            # recreate a new one or all the followng tests will fail.
2674
1930
            # If you need to inspect its content uncomment the following line
2675
1931
            # import pdb; pdb.set_trace()
2676
 
            _rmtree_temp_dir(root + '/.bzr', test_id=self.id())
 
1932
            _rmtree_temp_dir(root + '/.bzr')
2677
1933
            self._create_safety_net()
2678
1934
            raise AssertionError('%s/.bzr should not be modified' % root)
2679
1935
 
2680
1936
    def _make_test_root(self):
2681
1937
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
2682
 
            # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
2683
 
            root = osutils.realpath(osutils.mkdtemp(prefix='testbzr-',
2684
 
                                                    suffix='.tmp'))
 
1938
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
2685
1939
            TestCaseWithMemoryTransport.TEST_ROOT = root
2686
1940
 
2687
1941
            self._create_safety_net()
2690
1944
            # specifically told when all tests are finished.  This will do.
2691
1945
            atexit.register(_rmtree_temp_dir, root)
2692
1946
 
2693
 
        self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
2694
1947
        self.addCleanup(self._check_safety_net)
2695
1948
 
2696
1949
    def makeAndChdirToTestDir(self):
2697
1950
        """Create a temporary directories for this one test.
2698
 
 
 
1951
        
2699
1952
        This must set self.test_home_dir and self.test_dir and chdir to
2700
1953
        self.test_dir.
2701
 
 
 
1954
        
2702
1955
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
2703
1956
        """
2704
1957
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2705
1958
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2706
1959
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2707
 
        self.permit_dir(self.test_dir)
2708
 
 
2709
 
    def make_branch(self, relpath, format=None, name=None):
 
1960
        
 
1961
    def make_branch(self, relpath, format=None):
2710
1962
        """Create a branch on the transport at relpath."""
2711
1963
        repo = self.make_repository(relpath, format=format)
2712
 
        return repo.bzrdir.create_branch(append_revisions_only=False,
2713
 
                                         name=name)
2714
 
 
2715
 
    def get_default_format(self):
2716
 
        return 'default'
2717
 
 
2718
 
    def resolve_format(self, format):
2719
 
        """Resolve an object to a ControlDir format object.
2720
 
 
2721
 
        The initial format object can either already be
2722
 
        a ControlDirFormat, None (for the default format),
2723
 
        or a string with the name of the control dir format.
2724
 
 
2725
 
        :param format: Object to resolve
2726
 
        :return A ControlDirFormat instance
2727
 
        """
2728
 
        if format is None:
2729
 
            format = self.get_default_format()
2730
 
        if isinstance(format, basestring):
2731
 
            format = controldir.format_registry.make_bzrdir(format)
2732
 
        return format
 
1964
        return repo.bzrdir.create_branch()
2733
1965
 
2734
1966
    def make_bzrdir(self, relpath, format=None):
2735
1967
        try:
2736
1968
            # might be a relative or absolute path
2737
1969
            maybe_a_url = self.get_url(relpath)
2738
1970
            segments = maybe_a_url.rsplit('/', 1)
2739
 
            t = _mod_transport.get_transport(maybe_a_url)
 
1971
            t = get_transport(maybe_a_url)
2740
1972
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2741
1973
                t.ensure_base()
2742
 
            format = self.resolve_format(format)
 
1974
            if format is None:
 
1975
                format = 'default'
 
1976
            if isinstance(format, basestring):
 
1977
                format = bzrdir.format_registry.make_bzrdir(format)
2743
1978
            return format.initialize_on_transport(t)
2744
1979
        except errors.UninitializableFormat:
2745
1980
            raise TestSkipped("Format %s is not initializable." % format)
2746
1981
 
2747
 
    def make_repository(self, relpath, shared=None, format=None):
 
1982
    def make_repository(self, relpath, shared=False, format=None):
2748
1983
        """Create a repository on our default transport at relpath.
2749
 
 
 
1984
        
2750
1985
        Note that relpath must be a relative path, not a full url.
2751
1986
        """
2752
1987
        # FIXME: If you create a remoterepository this returns the underlying
2753
 
        # real format, which is incorrect.  Actually we should make sure that
 
1988
        # real format, which is incorrect.  Actually we should make sure that 
2754
1989
        # RemoteBzrDir returns a RemoteRepository.
2755
1990
        # maybe  mbp 20070410
2756
1991
        made_control = self.make_bzrdir(relpath, format=format)
2757
1992
        return made_control.create_repository(shared=shared)
2758
1993
 
2759
 
    def make_smart_server(self, path, backing_server=None):
2760
 
        if backing_server is None:
2761
 
            backing_server = self.get_server()
2762
 
        smart_server = test_server.SmartTCPServer_for_testing()
2763
 
        self.start_server(smart_server, backing_server)
2764
 
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
2765
 
                                                   ).clone(path)
2766
 
        return remote_transport
2767
 
 
2768
1994
    def make_branch_and_memory_tree(self, relpath, format=None):
2769
1995
        """Create a branch on the default transport and a MemoryTree for it."""
2770
1996
        b = self.make_branch(relpath, format=format)
2771
1997
        return memorytree.MemoryTree.create_on_branch(b)
2772
1998
 
2773
1999
    def make_branch_builder(self, relpath, format=None):
2774
 
        branch = self.make_branch(relpath, format=format)
2775
 
        return branchbuilder.BranchBuilder(branch=branch)
 
2000
        url = self.get_url(relpath)
 
2001
        tran = get_transport(url)
 
2002
        return branchbuilder.BranchBuilder(get_transport(url), format=format)
2776
2003
 
2777
2004
    def overrideEnvironmentForTesting(self):
2778
 
        test_home_dir = self.test_home_dir
2779
 
        if isinstance(test_home_dir, unicode):
2780
 
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2781
 
        self.overrideEnv('HOME', test_home_dir)
2782
 
        self.overrideEnv('BZR_HOME', test_home_dir)
2783
 
 
2784
 
    def setup_smart_server_with_call_log(self):
2785
 
        """Sets up a smart server as the transport server with a call log."""
2786
 
        self.transport_server = test_server.SmartTCPServer_for_testing
2787
 
        self.hpss_connections = []
2788
 
        self.hpss_calls = []
2789
 
        import traceback
2790
 
        # Skip the current stack down to the caller of
2791
 
        # setup_smart_server_with_call_log
2792
 
        prefix_length = len(traceback.extract_stack()) - 2
2793
 
        def capture_hpss_call(params):
2794
 
            self.hpss_calls.append(
2795
 
                CapturedCall(params, prefix_length))
2796
 
        def capture_connect(transport):
2797
 
            self.hpss_connections.append(transport)
2798
 
        client._SmartClient.hooks.install_named_hook(
2799
 
            'call', capture_hpss_call, None)
2800
 
        _mod_transport.Transport.hooks.install_named_hook(
2801
 
            'post_connect', capture_connect, None)
2802
 
 
2803
 
    def reset_smart_call_log(self):
2804
 
        self.hpss_calls = []
2805
 
        self.hpss_connections = []
2806
 
 
2807
 
 
 
2005
        os.environ['HOME'] = self.test_home_dir
 
2006
        os.environ['BZR_HOME'] = self.test_home_dir
 
2007
        
 
2008
    def setUp(self):
 
2009
        super(TestCaseWithMemoryTransport, self).setUp()
 
2010
        self._make_test_root()
 
2011
        _currentdir = os.getcwdu()
 
2012
        def _leaveDirectory():
 
2013
            os.chdir(_currentdir)
 
2014
        self.addCleanup(_leaveDirectory)
 
2015
        self.makeAndChdirToTestDir()
 
2016
        self.overrideEnvironmentForTesting()
 
2017
        self.__readonly_server = None
 
2018
        self.__server = None
 
2019
        self.reduceLockdirTimeout()
 
2020
 
 
2021
     
2808
2022
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2809
2023
    """Derived class that runs a test within a temporary directory.
2810
2024
 
2815
2029
    All test cases create their own directory within that.  If the
2816
2030
    tests complete successfully, the directory is removed.
2817
2031
 
2818
 
    :ivar test_base_dir: The path of the top-level directory for this
 
2032
    :ivar test_base_dir: The path of the top-level directory for this 
2819
2033
    test, which contains a home directory and a work directory.
2820
2034
 
2821
2035
    :ivar test_home_dir: An initially empty directory under test_base_dir
2827
2041
 
2828
2042
    OVERRIDE_PYTHON = 'python'
2829
2043
 
2830
 
    def setUp(self):
2831
 
        super(TestCaseInTempDir, self).setUp()
2832
 
        # Remove the protection set in isolated_environ, we have a proper
2833
 
        # access to disk resources now.
2834
 
        self.overrideEnv('BZR_LOG', None)
2835
 
 
2836
2044
    def check_file_contents(self, filename, expect):
2837
2045
        self.log("check contents of file %s" % filename)
2838
 
        f = file(filename)
2839
 
        try:
2840
 
            contents = f.read()
2841
 
        finally:
2842
 
            f.close()
 
2046
        contents = file(filename, 'r').read()
2843
2047
        if contents != expect:
2844
2048
            self.log("expected: %r" % expect)
2845
2049
            self.log("actually: %r" % contents)
2847
2051
 
2848
2052
    def _getTestDirPrefix(self):
2849
2053
        # create a directory within the top level test directory
2850
 
        if sys.platform in ('win32', 'cygwin'):
 
2054
        if sys.platform == 'win32':
2851
2055
            name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2852
2056
            # windows is likely to have path-length limits so use a short name
2853
2057
            name_prefix = name_prefix[-30:]
2857
2061
 
2858
2062
    def makeAndChdirToTestDir(self):
2859
2063
        """See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
2860
 
 
 
2064
        
2861
2065
        For TestCaseInTempDir we create a temporary directory based on the test
2862
2066
        name and then create two subdirs - test and home under it.
2863
2067
        """
2864
 
        name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
2865
 
            self._getTestDirPrefix())
 
2068
        name_prefix = osutils.pathjoin(self.TEST_ROOT, self._getTestDirPrefix())
2866
2069
        name = name_prefix
2867
2070
        for i in range(100):
2868
2071
            if os.path.exists(name):
2869
2072
                name = name_prefix + '_' + str(i)
2870
2073
            else:
2871
 
                # now create test and home directories within this dir
2872
 
                self.test_base_dir = name
2873
 
                self.addCleanup(self.deleteTestDir)
2874
 
                os.mkdir(self.test_base_dir)
 
2074
                os.mkdir(name)
2875
2075
                break
2876
 
        self.permit_dir(self.test_base_dir)
2877
 
        # 'sprouting' and 'init' of a branch both walk up the tree to find
2878
 
        # stacking policy to honour; create a bzr dir with an unshared
2879
 
        # repository (but not a branch - our code would be trying to escape
2880
 
        # then!) to stop them, and permit it to be read.
2881
 
        # control = controldir.ControlDir.create(self.test_base_dir)
2882
 
        # control.create_repository()
 
2076
        # now create test and home directories within this dir
 
2077
        self.test_base_dir = name
2883
2078
        self.test_home_dir = self.test_base_dir + '/home'
2884
2079
        os.mkdir(self.test_home_dir)
2885
2080
        self.test_dir = self.test_base_dir + '/work'
2891
2086
            f.write(self.id())
2892
2087
        finally:
2893
2088
            f.close()
 
2089
        self.addCleanup(self.deleteTestDir)
2894
2090
 
2895
2091
    def deleteTestDir(self):
2896
 
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2897
 
        _rmtree_temp_dir(self.test_base_dir, test_id=self.id())
 
2092
        os.chdir(self.TEST_ROOT)
 
2093
        _rmtree_temp_dir(self.test_base_dir)
2898
2094
 
2899
2095
    def build_tree(self, shape, line_endings='binary', transport=None):
2900
2096
        """Build a test tree according to a pattern.
2919
2115
                "a list or a tuple. Got %r instead" % (shape,))
2920
2116
        # It's OK to just create them using forward slashes on windows.
2921
2117
        if transport is None or transport.is_readonly():
2922
 
            transport = _mod_transport.get_transport_from_path(".")
 
2118
            transport = get_transport(".")
2923
2119
        for name in shape:
2924
 
            self.assertIsInstance(name, basestring)
 
2120
            self.assert_(isinstance(name, basestring))
2925
2121
            if name[-1] == '/':
2926
2122
                transport.mkdir(urlutils.escape(name[:-1]))
2927
2123
            else:
2935
2131
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2936
2132
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2937
2133
 
2938
 
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
 
2134
    def build_tree_contents(self, shape):
 
2135
        build_tree_contents(shape)
2939
2136
 
2940
2137
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2941
2138
        """Assert whether path or paths are in the WorkingTree"""
2969
2166
    ReadonlyTransportDecorator is used instead which allows the use of non disk
2970
2167
    based read write transports.
2971
2168
 
2972
 
    If an explicit class is provided for readonly access, that server and the
 
2169
    If an explicit class is provided for readonly access, that server and the 
2973
2170
    readwrite one must both define get_url() as resolving to os.getcwd().
2974
2171
    """
2975
2172
 
2976
 
    def setUp(self):
2977
 
        super(TestCaseWithTransport, self).setUp()
2978
 
        self.__vfs_server = None
2979
 
 
2980
2173
    def get_vfs_only_server(self):
2981
2174
        """See TestCaseWithMemoryTransport.
2982
2175
 
2985
2178
        """
2986
2179
        if self.__vfs_server is None:
2987
2180
            self.__vfs_server = self.vfs_transport_factory()
2988
 
            self.start_server(self.__vfs_server)
 
2181
            self.__vfs_server.setUp()
 
2182
            self.addCleanup(self.__vfs_server.tearDown)
2989
2183
        return self.__vfs_server
2990
2184
 
2991
2185
    def make_branch_and_tree(self, relpath, format=None):
2998
2192
        repository will also be accessed locally. Otherwise a lightweight
2999
2193
        checkout is created and returned.
3000
2194
 
3001
 
        We do this because we can't physically create a tree in the local
3002
 
        path, with a branch reference to the transport_factory url, and
3003
 
        a branch + repository in the vfs_transport, unless the vfs_transport
3004
 
        namespace is distinct from the local disk - the two branch objects
3005
 
        would collide. While we could construct a tree with its branch object
3006
 
        pointing at the transport_factory transport in memory, reopening it
3007
 
        would behaving unexpectedly, and has in the past caused testing bugs
3008
 
        when we tried to do it that way.
3009
 
 
3010
2195
        :param format: The BzrDirFormat.
3011
2196
        :returns: the WorkingTree.
3012
2197
        """
3014
2199
        # this obviously requires a format that supports branch references
3015
2200
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
3016
2201
        # RBC 20060208
3017
 
        format = self.resolve_format(format=format)
3018
 
        if not format.supports_workingtrees:
3019
 
            b = self.make_branch(relpath+'.branch', format=format)
3020
 
            return b.create_checkout(relpath, lightweight=True)
3021
2202
        b = self.make_branch(relpath, format=format)
3022
2203
        try:
3023
2204
            return b.bzrdir.create_workingtree()
3025
2206
            # We can only make working trees locally at the moment.  If the
3026
2207
            # transport can't support them, then we keep the non-disk-backed
3027
2208
            # branch and create a local checkout.
3028
 
            if self.vfs_transport_factory is test_server.LocalURLServer:
 
2209
            if self.vfs_transport_factory is LocalURLServer:
3029
2210
                # the branch is colocated on disk, we cannot create a checkout.
3030
2211
                # hopefully callers will expect this.
3031
 
                local_controldir = controldir.ControlDir.open(
3032
 
                    self.get_vfs_only_url(relpath))
 
2212
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
3033
2213
                wt = local_controldir.create_workingtree()
3034
2214
                if wt.branch._format != b._format:
3035
2215
                    wt._branch = b
3065
2245
        self.assertFalse(differences.has_changed(),
3066
2246
            "Trees %r and %r are different: %r" % (left, right, differences))
3067
2247
 
3068
 
    def disable_missing_extensions_warning(self):
3069
 
        """Some tests expect a precise stderr content.
3070
 
 
3071
 
        There is no point in forcing them to duplicate the extension related
3072
 
        warning.
3073
 
        """
3074
 
        config.GlobalStack().set('ignore_missing_extensions', True)
 
2248
    def setUp(self):
 
2249
        super(TestCaseWithTransport, self).setUp()
 
2250
        self.__vfs_server = None
3075
2251
 
3076
2252
 
3077
2253
class ChrootedTestCase(TestCaseWithTransport):
3082
2258
    for readonly urls.
3083
2259
 
3084
2260
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
3085
 
                       be used without needed to redo it when a different
 
2261
                       be used without needed to redo it when a different 
3086
2262
                       subclass is in use ?
3087
2263
    """
3088
2264
 
3089
2265
    def setUp(self):
3090
 
        from bzrlib.tests import http_server
3091
2266
        super(ChrootedTestCase, self).setUp()
3092
 
        if not self.vfs_transport_factory == memory.MemoryServer:
3093
 
            self.transport_readonly_server = http_server.HttpServer
 
2267
        if not self.vfs_transport_factory == MemoryServer:
 
2268
            self.transport_readonly_server = HttpServer
3094
2269
 
3095
2270
 
3096
2271
def condition_id_re(pattern):
3097
2272
    """Create a condition filter which performs a re check on a test's id.
3098
 
 
 
2273
    
3099
2274
    :param pattern: A regular expression string.
3100
2275
    :return: A callable that returns True if the re matches.
3101
2276
    """
3102
 
    filter_re = re.compile(pattern, 0)
 
2277
    filter_re = re.compile(pattern)
3103
2278
    def condition(test):
3104
2279
        test_id = test.id()
3105
2280
        return filter_re.search(test_id)
3108
2283
 
3109
2284
def condition_isinstance(klass_or_klass_list):
3110
2285
    """Create a condition filter which returns isinstance(param, klass).
3111
 
 
 
2286
    
3112
2287
    :return: A callable which when called with one parameter obj return the
3113
2288
        result of isinstance(obj, klass_or_klass_list).
3114
2289
    """
3119
2294
 
3120
2295
def condition_id_in_list(id_list):
3121
2296
    """Create a condition filter which verify that test's id in a list.
3122
 
 
 
2297
    
3123
2298
    :param id_list: A TestIdList object.
3124
2299
    :return: A callable that returns True if the test's id appears in the list.
3125
2300
    """
3130
2305
 
3131
2306
def condition_id_startswith(starts):
3132
2307
    """Create a condition filter verifying that test's id starts with a string.
3133
 
 
 
2308
    
3134
2309
    :param starts: A list of string.
3135
 
    :return: A callable that returns True if the test's id starts with one of
 
2310
    :return: A callable that returns True if the test's id starts with one of 
3136
2311
        the given strings.
3137
2312
    """
3138
2313
    def condition(test):
3161
2336
 
3162
2337
def filter_suite_by_condition(suite, condition):
3163
2338
    """Create a test suite by filtering another one.
3164
 
 
 
2339
    
3165
2340
    :param suite: The source suite.
3166
2341
    :param condition: A callable whose result evaluates True when called with a
3167
2342
        test case which should be included in the result.
3177
2352
 
3178
2353
def filter_suite_by_re(suite, pattern):
3179
2354
    """Create a test suite by filtering another one.
3180
 
 
 
2355
    
3181
2356
    :param suite:           the source suite
3182
2357
    :param pattern:         pattern that names must match
3183
2358
    :returns: the newly created suite
3235
2410
 
3236
2411
def randomize_suite(suite):
3237
2412
    """Return a new TestSuite with suite's tests in random order.
3238
 
 
 
2413
    
3239
2414
    The tests in the input suite are flattened into a single suite in order to
3240
2415
    accomplish this. Any nested TestSuites are removed to provide global
3241
2416
    randomness.
3247
2422
 
3248
2423
def split_suite_by_condition(suite, condition):
3249
2424
    """Split a test suite into two by a condition.
3250
 
 
 
2425
    
3251
2426
    :param suite: The suite to split.
3252
2427
    :param condition: The condition to match on. Tests that match this
3253
2428
        condition are returned in the first test suite, ones that do not match
3269
2444
 
3270
2445
def split_suite_by_re(suite, pattern):
3271
2446
    """Split a test suite into two by a regular expression.
3272
 
 
 
2447
    
3273
2448
    :param suite: The suite to split.
3274
2449
    :param pattern: A regular expression string. Test ids that match this
3275
2450
        pattern will be in the first test suite returned, and the others in the
3289
2464
              list_only=False,
3290
2465
              random_seed=None,
3291
2466
              exclude_pattern=None,
3292
 
              strict=False,
3293
 
              runner_class=None,
3294
 
              suite_decorators=None,
3295
 
              stream=None,
3296
 
              result_decorators=None,
3297
 
              ):
3298
 
    """Run a test suite for bzr selftest.
3299
 
 
3300
 
    :param runner_class: The class of runner to use. Must support the
3301
 
        constructor arguments passed by run_suite which are more than standard
3302
 
        python uses.
3303
 
    :return: A boolean indicating success.
3304
 
    """
 
2467
              strict=False):
3305
2468
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
3306
2469
    if verbose:
3307
2470
        verbosity = 2
3308
2471
    else:
3309
2472
        verbosity = 1
3310
 
    if runner_class is None:
3311
 
        runner_class = TextTestRunner
3312
 
    if stream is None:
3313
 
        stream = sys.stdout
3314
 
    runner = runner_class(stream=stream,
 
2473
    runner = TextTestRunner(stream=sys.stdout,
3315
2474
                            descriptions=0,
3316
2475
                            verbosity=verbosity,
3317
2476
                            bench_history=bench_history,
3318
 
                            strict=strict,
3319
 
                            result_decorators=result_decorators,
 
2477
                            list_only=list_only,
3320
2478
                            )
3321
2479
    runner.stop_on_failure=stop_on_failure
3322
 
    if isinstance(suite, unittest.TestSuite):
3323
 
        # Empty out _tests list of passed suite and populate new TestSuite
3324
 
        suite._tests[:], suite = [], TestSuite(suite)
3325
 
    # built in decorator factories:
3326
 
    decorators = [
3327
 
        random_order(random_seed, runner),
3328
 
        exclude_tests(exclude_pattern),
3329
 
        ]
3330
 
    if matching_tests_first:
3331
 
        decorators.append(tests_first(pattern))
 
2480
    # Initialise the random number generator and display the seed used.
 
2481
    # We convert the seed to a long to make it reuseable across invocations.
 
2482
    random_order = False
 
2483
    if random_seed is not None:
 
2484
        random_order = True
 
2485
        if random_seed == "now":
 
2486
            random_seed = long(time.time())
 
2487
        else:
 
2488
            # Convert the seed to a long if we can
 
2489
            try:
 
2490
                random_seed = long(random_seed)
 
2491
            except:
 
2492
                pass
 
2493
        runner.stream.writeln("Randomizing test order using seed %s\n" %
 
2494
            (random_seed))
 
2495
        random.seed(random_seed)
 
2496
    # Customise the list of tests if requested
 
2497
    if exclude_pattern is not None:
 
2498
        suite = exclude_tests_by_re(suite, exclude_pattern)
 
2499
    if random_order:
 
2500
        order_changer = randomize_suite
3332
2501
    else:
3333
 
        decorators.append(filter_tests(pattern))
3334
 
    if suite_decorators:
3335
 
        decorators.extend(suite_decorators)
3336
 
    # tell the result object how many tests will be running: (except if
3337
 
    # --parallel=fork is being used. Robert said he will provide a better
3338
 
    # progress design later -- vila 20090817)
3339
 
    if fork_decorator not in decorators:
3340
 
        decorators.append(CountingDecorator)
3341
 
    for decorator in decorators:
3342
 
        suite = decorator(suite)
3343
 
    if list_only:
3344
 
        # Done after test suite decoration to allow randomisation etc
3345
 
        # to take effect, though that is of marginal benefit.
3346
 
        if verbosity >= 2:
3347
 
            stream.write("Listing tests only ...\n")
3348
 
        for t in iter_suite_tests(suite):
3349
 
            stream.write("%s\n" % (t.id()))
3350
 
        return True
 
2502
        order_changer = preserve_input
 
2503
    if pattern != '.*' or random_order:
 
2504
        if matching_tests_first:
 
2505
            suites = map(order_changer, split_suite_by_re(suite, pattern))
 
2506
            suite = TestUtil.TestSuite(suites)
 
2507
        else:
 
2508
            suite = order_changer(filter_suite_by_re(suite, pattern))
 
2509
 
3351
2510
    result = runner.run(suite)
 
2511
 
3352
2512
    if strict:
3353
2513
        return result.wasStrictlySuccessful()
3354
 
    else:
3355
 
        return result.wasSuccessful()
3356
 
 
3357
 
 
3358
 
# A registry where get() returns a suite decorator.
3359
 
parallel_registry = registry.Registry()
3360
 
 
3361
 
 
3362
 
def fork_decorator(suite):
3363
 
    if getattr(os, "fork", None) is None:
3364
 
        raise errors.BzrCommandError("platform does not support fork,"
3365
 
            " try --parallel=subprocess instead.")
3366
 
    concurrency = osutils.local_concurrency()
3367
 
    if concurrency == 1:
3368
 
        return suite
3369
 
    from testtools import ConcurrentTestSuite
3370
 
    return ConcurrentTestSuite(suite, fork_for_tests)
3371
 
parallel_registry.register('fork', fork_decorator)
3372
 
 
3373
 
 
3374
 
def subprocess_decorator(suite):
3375
 
    concurrency = osutils.local_concurrency()
3376
 
    if concurrency == 1:
3377
 
        return suite
3378
 
    from testtools import ConcurrentTestSuite
3379
 
    return ConcurrentTestSuite(suite, reinvoke_for_tests)
3380
 
parallel_registry.register('subprocess', subprocess_decorator)
3381
 
 
3382
 
 
3383
 
def exclude_tests(exclude_pattern):
3384
 
    """Return a test suite decorator that excludes tests."""
3385
 
    if exclude_pattern is None:
3386
 
        return identity_decorator
3387
 
    def decorator(suite):
3388
 
        return ExcludeDecorator(suite, exclude_pattern)
3389
 
    return decorator
3390
 
 
3391
 
 
3392
 
def filter_tests(pattern):
3393
 
    if pattern == '.*':
3394
 
        return identity_decorator
3395
 
    def decorator(suite):
3396
 
        return FilterTestsDecorator(suite, pattern)
3397
 
    return decorator
3398
 
 
3399
 
 
3400
 
def random_order(random_seed, runner):
3401
 
    """Return a test suite decorator factory for randomising tests order.
3402
 
    
3403
 
    :param random_seed: now, a string which casts to a long, or a long.
3404
 
    :param runner: A test runner with a stream attribute to report on.
3405
 
    """
3406
 
    if random_seed is None:
3407
 
        return identity_decorator
3408
 
    def decorator(suite):
3409
 
        return RandomDecorator(suite, random_seed, runner.stream)
3410
 
    return decorator
3411
 
 
3412
 
 
3413
 
def tests_first(pattern):
3414
 
    if pattern == '.*':
3415
 
        return identity_decorator
3416
 
    def decorator(suite):
3417
 
        return TestFirstDecorator(suite, pattern)
3418
 
    return decorator
3419
 
 
3420
 
 
3421
 
def identity_decorator(suite):
3422
 
    """Return suite."""
3423
 
    return suite
3424
 
 
3425
 
 
3426
 
class TestDecorator(TestUtil.TestSuite):
3427
 
    """A decorator for TestCase/TestSuite objects.
3428
 
 
3429
 
    Contains rather than flattening suite passed on construction
3430
 
    """
3431
 
 
3432
 
    def __init__(self, suite=None):
3433
 
        super(TestDecorator, self).__init__()
3434
 
        if suite is not None:
3435
 
            self.addTest(suite)
3436
 
 
3437
 
    # Don't need subclass run method with suite emptying
3438
 
    run = unittest.TestSuite.run
3439
 
 
3440
 
 
3441
 
class CountingDecorator(TestDecorator):
3442
 
    """A decorator which calls result.progress(self.countTestCases)."""
3443
 
 
3444
 
    def run(self, result):
3445
 
        progress_method = getattr(result, 'progress', None)
3446
 
        if callable(progress_method):
3447
 
            progress_method(self.countTestCases(), SUBUNIT_SEEK_SET)
3448
 
        return super(CountingDecorator, self).run(result)
3449
 
 
3450
 
 
3451
 
class ExcludeDecorator(TestDecorator):
3452
 
    """A decorator which excludes test matching an exclude pattern."""
3453
 
 
3454
 
    def __init__(self, suite, exclude_pattern):
3455
 
        super(ExcludeDecorator, self).__init__(
3456
 
            exclude_tests_by_re(suite, exclude_pattern))
3457
 
 
3458
 
 
3459
 
class FilterTestsDecorator(TestDecorator):
3460
 
    """A decorator which filters tests to those matching a pattern."""
3461
 
 
3462
 
    def __init__(self, suite, pattern):
3463
 
        super(FilterTestsDecorator, self).__init__(
3464
 
            filter_suite_by_re(suite, pattern))
3465
 
 
3466
 
 
3467
 
class RandomDecorator(TestDecorator):
3468
 
    """A decorator which randomises the order of its tests."""
3469
 
 
3470
 
    def __init__(self, suite, random_seed, stream):
3471
 
        random_seed = self.actual_seed(random_seed)
3472
 
        stream.write("Randomizing test order using seed %s\n\n" %
3473
 
            (random_seed,))
3474
 
        # Initialise the random number generator.
3475
 
        random.seed(random_seed)
3476
 
        super(RandomDecorator, self).__init__(randomize_suite(suite))
3477
 
 
3478
 
    @staticmethod
3479
 
    def actual_seed(seed):
3480
 
        if seed == "now":
3481
 
            # We convert the seed to a long to make it reuseable across
3482
 
            # invocations (because the user can reenter it).
3483
 
            return long(time.time())
3484
 
        else:
3485
 
            # Convert the seed to a long if we can
3486
 
            try:
3487
 
                return long(seed)
3488
 
            except (TypeError, ValueError):
3489
 
                pass
3490
 
        return seed
3491
 
 
3492
 
 
3493
 
class TestFirstDecorator(TestDecorator):
3494
 
    """A decorator which moves named tests to the front."""
3495
 
 
3496
 
    def __init__(self, suite, pattern):
3497
 
        super(TestFirstDecorator, self).__init__()
3498
 
        self.addTests(split_suite_by_re(suite, pattern))
3499
 
 
3500
 
 
3501
 
def partition_tests(suite, count):
3502
 
    """Partition suite into count lists of tests."""
3503
 
    # This just assigns tests in a round-robin fashion.  On one hand this
3504
 
    # splits up blocks of related tests that might run faster if they shared
3505
 
    # resources, but on the other it avoids assigning blocks of slow tests to
3506
 
    # just one partition.  So the slowest partition shouldn't be much slower
3507
 
    # than the fastest.
3508
 
    partitions = [list() for i in range(count)]
3509
 
    tests = iter_suite_tests(suite)
3510
 
    for partition, test in itertools.izip(itertools.cycle(partitions), tests):
3511
 
        partition.append(test)
3512
 
    return partitions
3513
 
 
3514
 
 
3515
 
def workaround_zealous_crypto_random():
3516
 
    """Crypto.Random want to help us being secure, but we don't care here.
3517
 
 
3518
 
    This workaround some test failure related to the sftp server. Once paramiko
3519
 
    stop using the controversial API in Crypto.Random, we may get rid of it.
3520
 
    """
3521
 
    try:
3522
 
        from Crypto.Random import atfork
3523
 
        atfork()
3524
 
    except ImportError:
3525
 
        pass
3526
 
 
3527
 
 
3528
 
def fork_for_tests(suite):
3529
 
    """Take suite and start up one runner per CPU by forking()
3530
 
 
3531
 
    :return: An iterable of TestCase-like objects which can each have
3532
 
        run(result) called on them to feed tests to result.
3533
 
    """
3534
 
    concurrency = osutils.local_concurrency()
3535
 
    result = []
3536
 
    from subunit import ProtocolTestCase
3537
 
    from subunit.test_results import AutoTimingTestResultDecorator
3538
 
    class TestInOtherProcess(ProtocolTestCase):
3539
 
        # Should be in subunit, I think. RBC.
3540
 
        def __init__(self, stream, pid):
3541
 
            ProtocolTestCase.__init__(self, stream)
3542
 
            self.pid = pid
3543
 
 
3544
 
        def run(self, result):
3545
 
            try:
3546
 
                ProtocolTestCase.run(self, result)
3547
 
            finally:
3548
 
                pid, status = os.waitpid(self.pid, 0)
3549
 
            # GZ 2011-10-18: If status is nonzero, should report to the result
3550
 
            #                that something went wrong.
3551
 
 
3552
 
    test_blocks = partition_tests(suite, concurrency)
3553
 
    # Clear the tests from the original suite so it doesn't keep them alive
3554
 
    suite._tests[:] = []
3555
 
    for process_tests in test_blocks:
3556
 
        process_suite = TestUtil.TestSuite(process_tests)
3557
 
        # Also clear each split list so new suite has only reference
3558
 
        process_tests[:] = []
3559
 
        c2pread, c2pwrite = os.pipe()
3560
 
        pid = os.fork()
3561
 
        if pid == 0:
3562
 
            try:
3563
 
                stream = os.fdopen(c2pwrite, 'wb', 1)
3564
 
                workaround_zealous_crypto_random()
3565
 
                os.close(c2pread)
3566
 
                # Leave stderr and stdout open so we can see test noise
3567
 
                # Close stdin so that the child goes away if it decides to
3568
 
                # read from stdin (otherwise its a roulette to see what
3569
 
                # child actually gets keystrokes for pdb etc).
3570
 
                sys.stdin.close()
3571
 
                subunit_result = AutoTimingTestResultDecorator(
3572
 
                    SubUnitBzrProtocolClient(stream))
3573
 
                process_suite.run(subunit_result)
3574
 
            except:
3575
 
                # Try and report traceback on stream, but exit with error even
3576
 
                # if stream couldn't be created or something else goes wrong.
3577
 
                # The traceback is formatted to a string and written in one go
3578
 
                # to avoid interleaving lines from multiple failing children.
3579
 
                try:
3580
 
                    stream.write(traceback.format_exc())
3581
 
                finally:
3582
 
                    os._exit(1)
3583
 
            os._exit(0)
3584
 
        else:
3585
 
            os.close(c2pwrite)
3586
 
            stream = os.fdopen(c2pread, 'rb', 1)
3587
 
            test = TestInOtherProcess(stream, pid)
3588
 
            result.append(test)
3589
 
    return result
3590
 
 
3591
 
 
3592
 
def reinvoke_for_tests(suite):
3593
 
    """Take suite and start up one runner per CPU using subprocess().
3594
 
 
3595
 
    :return: An iterable of TestCase-like objects which can each have
3596
 
        run(result) called on them to feed tests to result.
3597
 
    """
3598
 
    concurrency = osutils.local_concurrency()
3599
 
    result = []
3600
 
    from subunit import ProtocolTestCase
3601
 
    class TestInSubprocess(ProtocolTestCase):
3602
 
        def __init__(self, process, name):
3603
 
            ProtocolTestCase.__init__(self, process.stdout)
3604
 
            self.process = process
3605
 
            self.process.stdin.close()
3606
 
            self.name = name
3607
 
 
3608
 
        def run(self, result):
3609
 
            try:
3610
 
                ProtocolTestCase.run(self, result)
3611
 
            finally:
3612
 
                self.process.wait()
3613
 
                os.unlink(self.name)
3614
 
            # print "pid %d finished" % finished_process
3615
 
    test_blocks = partition_tests(suite, concurrency)
3616
 
    for process_tests in test_blocks:
3617
 
        # ugly; currently reimplement rather than reuses TestCase methods.
3618
 
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
3619
 
        if not os.path.isfile(bzr_path):
3620
 
            # We are probably installed. Assume sys.argv is the right file
3621
 
            bzr_path = sys.argv[0]
3622
 
        bzr_path = [bzr_path]
3623
 
        if sys.platform == "win32":
3624
 
            # if we're on windows, we can't execute the bzr script directly
3625
 
            bzr_path = [sys.executable] + bzr_path
3626
 
        fd, test_list_file_name = tempfile.mkstemp()
3627
 
        test_list_file = os.fdopen(fd, 'wb', 1)
3628
 
        for test in process_tests:
3629
 
            test_list_file.write(test.id() + '\n')
3630
 
        test_list_file.close()
3631
 
        try:
3632
 
            argv = bzr_path + ['selftest', '--load-list', test_list_file_name,
3633
 
                '--subunit']
3634
 
            if '--no-plugins' in sys.argv:
3635
 
                argv.append('--no-plugins')
3636
 
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
3637
 
            # noise on stderr it can interrupt the subunit protocol.
3638
 
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
3639
 
                                      stdout=subprocess.PIPE,
3640
 
                                      stderr=subprocess.PIPE,
3641
 
                                      bufsize=1)
3642
 
            test = TestInSubprocess(process, test_list_file_name)
3643
 
            result.append(test)
3644
 
        except:
3645
 
            os.unlink(test_list_file_name)
3646
 
            raise
3647
 
    return result
3648
 
 
3649
 
 
3650
 
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3651
 
    """Generate profiling data for all activity between start and success.
3652
 
    
3653
 
    The profile data is appended to the test's _benchcalls attribute and can
3654
 
    be accessed by the forwarded-to TestResult.
3655
 
 
3656
 
    While it might be cleaner do accumulate this in stopTest, addSuccess is
3657
 
    where our existing output support for lsprof is, and this class aims to
3658
 
    fit in with that: while it could be moved it's not necessary to accomplish
3659
 
    test profiling, nor would it be dramatically cleaner.
3660
 
    """
3661
 
 
3662
 
    def startTest(self, test):
3663
 
        self.profiler = bzrlib.lsprof.BzrProfiler()
3664
 
        # Prevent deadlocks in tests that use lsprof: those tests will
3665
 
        # unavoidably fail.
3666
 
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3667
 
        self.profiler.start()
3668
 
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3669
 
 
3670
 
    def addSuccess(self, test):
3671
 
        stats = self.profiler.stop()
3672
 
        try:
3673
 
            calls = test._benchcalls
3674
 
        except AttributeError:
3675
 
            test._benchcalls = []
3676
 
            calls = test._benchcalls
3677
 
        calls.append(((test.id(), "", ""), stats))
3678
 
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3679
 
 
3680
 
    def stopTest(self, test):
3681
 
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3682
 
        self.profiler = None
 
2514
 
 
2515
    return result.wasSuccessful()
3683
2516
 
3684
2517
 
3685
2518
# Controlled by "bzr selftest -E=..." option
3686
 
# Currently supported:
3687
 
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
3688
 
#                           preserves any flags supplied at the command line.
3689
 
#   -Edisable_lock_checks   Turns errors in mismatched locks into simple prints
3690
 
#                           rather than failing tests. And no longer raise
3691
 
#                           LockContention when fctnl locks are not being used
3692
 
#                           with proper exclusion rules.
3693
 
#   -Ethreads               Will display thread ident at creation/join time to
3694
 
#                           help track thread leaks
3695
 
#   -Euncollected_cases     Display the identity of any test cases that weren't
3696
 
#                           deallocated after being completed.
3697
 
#   -Econfig_stats          Will collect statistics using addDetail
3698
2519
selftest_debug_flags = set()
3699
2520
 
3700
2521
 
3711
2532
             load_list=None,
3712
2533
             debug_flags=None,
3713
2534
             starting_with=None,
3714
 
             runner_class=None,
3715
 
             suite_decorators=None,
3716
 
             stream=None,
3717
 
             lsprof_tests=False,
3718
2535
             ):
3719
2536
    """Run the whole test suite under the enhanced runner"""
3720
2537
    # XXX: Very ugly way to do this...
3737
2554
            keep_only = None
3738
2555
        else:
3739
2556
            keep_only = load_test_id_list(load_list)
3740
 
        if starting_with:
3741
 
            starting_with = [test_prefix_alias_registry.resolve_alias(start)
3742
 
                             for start in starting_with]
3743
2557
        if test_suite_factory is None:
3744
 
            # Reduce loading time by loading modules based on the starting_with
3745
 
            # patterns.
3746
2558
            suite = test_suite(keep_only, starting_with)
3747
2559
        else:
3748
2560
            suite = test_suite_factory()
3749
 
        if starting_with:
3750
 
            # But always filter as requested.
3751
 
            suite = filter_suite_by_id_startswith(suite, starting_with)
3752
 
        result_decorators = []
3753
 
        if lsprof_tests:
3754
 
            result_decorators.append(ProfileResult)
3755
2561
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3756
2562
                     stop_on_failure=stop_on_failure,
3757
2563
                     transport=transport,
3761
2567
                     list_only=list_only,
3762
2568
                     random_seed=random_seed,
3763
2569
                     exclude_pattern=exclude_pattern,
3764
 
                     strict=strict,
3765
 
                     runner_class=runner_class,
3766
 
                     suite_decorators=suite_decorators,
3767
 
                     stream=stream,
3768
 
                     result_decorators=result_decorators,
3769
 
                     )
 
2570
                     strict=strict)
3770
2571
    finally:
3771
2572
        default_transport = old_transport
3772
2573
        selftest_debug_flags = old_debug_flags
3799
2600
    """Warns about tests not appearing or appearing more than once.
3800
2601
 
3801
2602
    :param test_suite: A TestSuite object.
3802
 
    :param test_id_list: The list of test ids that should be found in
 
2603
    :param test_id_list: The list of test ids that should be found in 
3803
2604
         test_suite.
3804
2605
 
3805
2606
    :return: (absents, duplicates) absents is a list containing the test found
3806
2607
        in id_list but not in test_suite, duplicates is a list containing the
3807
 
        tests found multiple times in test_suite.
 
2608
        test found multiple times in test_suite.
3808
2609
 
3809
2610
    When using a prefined test id list, it may occurs that some tests do not
3810
2611
    exist anymore or that some tests use the same id. This function warns the
3894
2695
                key, obj, help=help, info=info, override_existing=False)
3895
2696
        except KeyError:
3896
2697
            actual = self.get(key)
3897
 
            trace.note(
3898
 
                'Test prefix alias %s is already used for %s, ignoring %s'
3899
 
                % (key, actual, obj))
 
2698
            note('Test prefix alias %s is already used for %s, ignoring %s'
 
2699
                 % (key, actual, obj))
3900
2700
 
3901
2701
    def resolve_alias(self, id_start):
3902
2702
        """Replace the alias by the prefix in the given string.
3920
2720
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3921
2721
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3922
2722
 
3923
 
# Obvious highest levels prefixes, feel free to add your own via a plugin
 
2723
# Obvious higest levels prefixes, feel free to add your own via a plugin
3924
2724
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3925
2725
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3926
2726
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3928
2728
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3929
2729
 
3930
2730
 
3931
 
def _test_suite_testmod_names():
3932
 
    """Return the standard list of test module names to test."""
3933
 
    return [
3934
 
        'bzrlib.doc',
3935
 
        'bzrlib.tests.blackbox',
3936
 
        'bzrlib.tests.commands',
3937
 
        'bzrlib.tests.per_branch',
3938
 
        'bzrlib.tests.per_bzrdir',
3939
 
        'bzrlib.tests.per_controldir',
3940
 
        'bzrlib.tests.per_controldir_colo',
3941
 
        'bzrlib.tests.per_foreign_vcs',
3942
 
        'bzrlib.tests.per_interrepository',
3943
 
        'bzrlib.tests.per_intertree',
3944
 
        'bzrlib.tests.per_inventory',
3945
 
        'bzrlib.tests.per_interbranch',
3946
 
        'bzrlib.tests.per_lock',
3947
 
        'bzrlib.tests.per_merger',
3948
 
        'bzrlib.tests.per_transport',
3949
 
        'bzrlib.tests.per_tree',
3950
 
        'bzrlib.tests.per_pack_repository',
3951
 
        'bzrlib.tests.per_repository',
3952
 
        'bzrlib.tests.per_repository_chk',
3953
 
        'bzrlib.tests.per_repository_reference',
3954
 
        'bzrlib.tests.per_repository_vf',
3955
 
        'bzrlib.tests.per_uifactory',
3956
 
        'bzrlib.tests.per_versionedfile',
3957
 
        'bzrlib.tests.per_workingtree',
3958
 
        'bzrlib.tests.test__annotator',
3959
 
        'bzrlib.tests.test__bencode',
3960
 
        'bzrlib.tests.test__btree_serializer',
3961
 
        'bzrlib.tests.test__chk_map',
3962
 
        'bzrlib.tests.test__dirstate_helpers',
3963
 
        'bzrlib.tests.test__groupcompress',
3964
 
        'bzrlib.tests.test__known_graph',
3965
 
        'bzrlib.tests.test__rio',
3966
 
        'bzrlib.tests.test__simple_set',
3967
 
        'bzrlib.tests.test__static_tuple',
3968
 
        'bzrlib.tests.test__walkdirs_win32',
3969
 
        'bzrlib.tests.test_ancestry',
3970
 
        'bzrlib.tests.test_annotate',
3971
 
        'bzrlib.tests.test_api',
3972
 
        'bzrlib.tests.test_atomicfile',
3973
 
        'bzrlib.tests.test_bad_files',
3974
 
        'bzrlib.tests.test_bisect_multi',
3975
 
        'bzrlib.tests.test_branch',
3976
 
        'bzrlib.tests.test_branchbuilder',
3977
 
        'bzrlib.tests.test_btree_index',
3978
 
        'bzrlib.tests.test_bugtracker',
3979
 
        'bzrlib.tests.test_bundle',
3980
 
        'bzrlib.tests.test_bzrdir',
3981
 
        'bzrlib.tests.test__chunks_to_lines',
3982
 
        'bzrlib.tests.test_cache_utf8',
3983
 
        'bzrlib.tests.test_chk_map',
3984
 
        'bzrlib.tests.test_chk_serializer',
3985
 
        'bzrlib.tests.test_chunk_writer',
3986
 
        'bzrlib.tests.test_clean_tree',
3987
 
        'bzrlib.tests.test_cleanup',
3988
 
        'bzrlib.tests.test_cmdline',
3989
 
        'bzrlib.tests.test_commands',
3990
 
        'bzrlib.tests.test_commit',
3991
 
        'bzrlib.tests.test_commit_merge',
3992
 
        'bzrlib.tests.test_config',
3993
 
        'bzrlib.tests.test_conflicts',
3994
 
        'bzrlib.tests.test_controldir',
3995
 
        'bzrlib.tests.test_counted_lock',
3996
 
        'bzrlib.tests.test_crash',
3997
 
        'bzrlib.tests.test_decorators',
3998
 
        'bzrlib.tests.test_delta',
3999
 
        'bzrlib.tests.test_debug',
4000
 
        'bzrlib.tests.test_diff',
4001
 
        'bzrlib.tests.test_directory_service',
4002
 
        'bzrlib.tests.test_dirstate',
4003
 
        'bzrlib.tests.test_email_message',
4004
 
        'bzrlib.tests.test_eol_filters',
4005
 
        'bzrlib.tests.test_errors',
4006
 
        'bzrlib.tests.test_estimate_compressed_size',
4007
 
        'bzrlib.tests.test_export',
4008
 
        'bzrlib.tests.test_export_pot',
4009
 
        'bzrlib.tests.test_extract',
4010
 
        'bzrlib.tests.test_features',
4011
 
        'bzrlib.tests.test_fetch',
4012
 
        'bzrlib.tests.test_fixtures',
4013
 
        'bzrlib.tests.test_fifo_cache',
4014
 
        'bzrlib.tests.test_filters',
4015
 
        'bzrlib.tests.test_filter_tree',
4016
 
        'bzrlib.tests.test_ftp_transport',
4017
 
        'bzrlib.tests.test_foreign',
4018
 
        'bzrlib.tests.test_generate_docs',
4019
 
        'bzrlib.tests.test_generate_ids',
4020
 
        'bzrlib.tests.test_globbing',
4021
 
        'bzrlib.tests.test_gpg',
4022
 
        'bzrlib.tests.test_graph',
4023
 
        'bzrlib.tests.test_groupcompress',
4024
 
        'bzrlib.tests.test_hashcache',
4025
 
        'bzrlib.tests.test_help',
4026
 
        'bzrlib.tests.test_hooks',
4027
 
        'bzrlib.tests.test_http',
4028
 
        'bzrlib.tests.test_http_response',
4029
 
        'bzrlib.tests.test_https_ca_bundle',
4030
 
        'bzrlib.tests.test_https_urllib',
4031
 
        'bzrlib.tests.test_i18n',
4032
 
        'bzrlib.tests.test_identitymap',
4033
 
        'bzrlib.tests.test_ignores',
4034
 
        'bzrlib.tests.test_index',
4035
 
        'bzrlib.tests.test_import_tariff',
4036
 
        'bzrlib.tests.test_info',
4037
 
        'bzrlib.tests.test_inv',
4038
 
        'bzrlib.tests.test_inventory_delta',
4039
 
        'bzrlib.tests.test_knit',
4040
 
        'bzrlib.tests.test_lazy_import',
4041
 
        'bzrlib.tests.test_lazy_regex',
4042
 
        'bzrlib.tests.test_library_state',
4043
 
        'bzrlib.tests.test_lock',
4044
 
        'bzrlib.tests.test_lockable_files',
4045
 
        'bzrlib.tests.test_lockdir',
4046
 
        'bzrlib.tests.test_log',
4047
 
        'bzrlib.tests.test_lru_cache',
4048
 
        'bzrlib.tests.test_lsprof',
4049
 
        'bzrlib.tests.test_mail_client',
4050
 
        'bzrlib.tests.test_matchers',
4051
 
        'bzrlib.tests.test_memorytree',
4052
 
        'bzrlib.tests.test_merge',
4053
 
        'bzrlib.tests.test_merge3',
4054
 
        'bzrlib.tests.test_merge_core',
4055
 
        'bzrlib.tests.test_merge_directive',
4056
 
        'bzrlib.tests.test_mergetools',
4057
 
        'bzrlib.tests.test_missing',
4058
 
        'bzrlib.tests.test_msgeditor',
4059
 
        'bzrlib.tests.test_multiparent',
4060
 
        'bzrlib.tests.test_mutabletree',
4061
 
        'bzrlib.tests.test_nonascii',
4062
 
        'bzrlib.tests.test_options',
4063
 
        'bzrlib.tests.test_osutils',
4064
 
        'bzrlib.tests.test_osutils_encodings',
4065
 
        'bzrlib.tests.test_pack',
4066
 
        'bzrlib.tests.test_patch',
4067
 
        'bzrlib.tests.test_patches',
4068
 
        'bzrlib.tests.test_permissions',
4069
 
        'bzrlib.tests.test_plugins',
4070
 
        'bzrlib.tests.test_progress',
4071
 
        'bzrlib.tests.test_pyutils',
4072
 
        'bzrlib.tests.test_read_bundle',
4073
 
        'bzrlib.tests.test_reconcile',
4074
 
        'bzrlib.tests.test_reconfigure',
4075
 
        'bzrlib.tests.test_registry',
4076
 
        'bzrlib.tests.test_remote',
4077
 
        'bzrlib.tests.test_rename_map',
4078
 
        'bzrlib.tests.test_repository',
4079
 
        'bzrlib.tests.test_revert',
4080
 
        'bzrlib.tests.test_revision',
4081
 
        'bzrlib.tests.test_revisionspec',
4082
 
        'bzrlib.tests.test_revisiontree',
4083
 
        'bzrlib.tests.test_rio',
4084
 
        'bzrlib.tests.test_rules',
4085
 
        'bzrlib.tests.test_url_policy_open',
4086
 
        'bzrlib.tests.test_sampler',
4087
 
        'bzrlib.tests.test_scenarios',
4088
 
        'bzrlib.tests.test_script',
4089
 
        'bzrlib.tests.test_selftest',
4090
 
        'bzrlib.tests.test_serializer',
4091
 
        'bzrlib.tests.test_setup',
4092
 
        'bzrlib.tests.test_sftp_transport',
4093
 
        'bzrlib.tests.test_shelf',
4094
 
        'bzrlib.tests.test_shelf_ui',
4095
 
        'bzrlib.tests.test_smart',
4096
 
        'bzrlib.tests.test_smart_add',
4097
 
        'bzrlib.tests.test_smart_request',
4098
 
        'bzrlib.tests.test_smart_signals',
4099
 
        'bzrlib.tests.test_smart_transport',
4100
 
        'bzrlib.tests.test_smtp_connection',
4101
 
        'bzrlib.tests.test_source',
4102
 
        'bzrlib.tests.test_ssh_transport',
4103
 
        'bzrlib.tests.test_status',
4104
 
        'bzrlib.tests.test_store',
4105
 
        'bzrlib.tests.test_strace',
4106
 
        'bzrlib.tests.test_subsume',
4107
 
        'bzrlib.tests.test_switch',
4108
 
        'bzrlib.tests.test_symbol_versioning',
4109
 
        'bzrlib.tests.test_tag',
4110
 
        'bzrlib.tests.test_test_server',
4111
 
        'bzrlib.tests.test_testament',
4112
 
        'bzrlib.tests.test_textfile',
4113
 
        'bzrlib.tests.test_textmerge',
4114
 
        'bzrlib.tests.test_cethread',
4115
 
        'bzrlib.tests.test_timestamp',
4116
 
        'bzrlib.tests.test_trace',
4117
 
        'bzrlib.tests.test_transactions',
4118
 
        'bzrlib.tests.test_transform',
4119
 
        'bzrlib.tests.test_transport',
4120
 
        'bzrlib.tests.test_transport_log',
4121
 
        'bzrlib.tests.test_tree',
4122
 
        'bzrlib.tests.test_treebuilder',
4123
 
        'bzrlib.tests.test_treeshape',
4124
 
        'bzrlib.tests.test_tsort',
4125
 
        'bzrlib.tests.test_tuned_gzip',
4126
 
        'bzrlib.tests.test_ui',
4127
 
        'bzrlib.tests.test_uncommit',
4128
 
        'bzrlib.tests.test_upgrade',
4129
 
        'bzrlib.tests.test_upgrade_stacked',
4130
 
        'bzrlib.tests.test_urlutils',
4131
 
        'bzrlib.tests.test_utextwrap',
4132
 
        'bzrlib.tests.test_version',
4133
 
        'bzrlib.tests.test_version_info',
4134
 
        'bzrlib.tests.test_versionedfile',
4135
 
        'bzrlib.tests.test_vf_search',
4136
 
        'bzrlib.tests.test_weave',
4137
 
        'bzrlib.tests.test_whitebox',
4138
 
        'bzrlib.tests.test_win32utils',
4139
 
        'bzrlib.tests.test_workingtree',
4140
 
        'bzrlib.tests.test_workingtree_4',
4141
 
        'bzrlib.tests.test_wsgi',
4142
 
        'bzrlib.tests.test_xml',
4143
 
        ]
4144
 
 
4145
 
 
4146
 
def _test_suite_modules_to_doctest():
4147
 
    """Return the list of modules to doctest."""
4148
 
    if __doc__ is None:
4149
 
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
4150
 
        return []
4151
 
    return [
4152
 
        'bzrlib',
4153
 
        'bzrlib.branchbuilder',
4154
 
        'bzrlib.decorators',
4155
 
        'bzrlib.inventory',
4156
 
        'bzrlib.iterablefile',
4157
 
        'bzrlib.lockdir',
4158
 
        'bzrlib.merge3',
4159
 
        'bzrlib.option',
4160
 
        'bzrlib.pyutils',
4161
 
        'bzrlib.symbol_versioning',
4162
 
        'bzrlib.tests',
4163
 
        'bzrlib.tests.fixtures',
4164
 
        'bzrlib.timestamp',
4165
 
        'bzrlib.transport.http',
4166
 
        'bzrlib.version_info_formats.format_custom',
4167
 
        ]
4168
 
 
4169
 
 
4170
2731
def test_suite(keep_only=None, starting_with=None):
4171
2732
    """Build and return TestSuite for the whole of bzrlib.
4172
2733
 
4178
2739
    This function can be replaced if you need to change the default test
4179
2740
    suite on a global basis, but it is not encouraged.
4180
2741
    """
 
2742
    testmod_names = [
 
2743
                   'bzrlib.doc',
 
2744
                   'bzrlib.util.tests.test_bencode',
 
2745
                   'bzrlib.tests.blackbox',
 
2746
                   'bzrlib.tests.branch_implementations',
 
2747
                   'bzrlib.tests.bzrdir_implementations',
 
2748
                   'bzrlib.tests.commands',
 
2749
                   'bzrlib.tests.inventory_implementations',
 
2750
                   'bzrlib.tests.interrepository_implementations',
 
2751
                   'bzrlib.tests.intertree_implementations',
 
2752
                   'bzrlib.tests.per_lock',
 
2753
                   'bzrlib.tests.repository_implementations',
 
2754
                   'bzrlib.tests.test__dirstate_helpers',
 
2755
                   'bzrlib.tests.test_ancestry',
 
2756
                   'bzrlib.tests.test_annotate',
 
2757
                   'bzrlib.tests.test_api',
 
2758
                   'bzrlib.tests.test_atomicfile',
 
2759
                   'bzrlib.tests.test_bad_files',
 
2760
                   'bzrlib.tests.test_bisect_multi',
 
2761
                   'bzrlib.tests.test_branch',
 
2762
                   'bzrlib.tests.test_branchbuilder',
 
2763
                   'bzrlib.tests.test_btree_index',
 
2764
                   'bzrlib.tests.test_bugtracker',
 
2765
                   'bzrlib.tests.test_bundle',
 
2766
                   'bzrlib.tests.test_bzrdir',
 
2767
                   'bzrlib.tests.test_cache_utf8',
 
2768
                   'bzrlib.tests.test_chunk_writer',
 
2769
                   'bzrlib.tests.test_commands',
 
2770
                   'bzrlib.tests.test_commit',
 
2771
                   'bzrlib.tests.test_commit_merge',
 
2772
                   'bzrlib.tests.test_config',
 
2773
                   'bzrlib.tests.test_conflicts',
 
2774
                   'bzrlib.tests.test_counted_lock',
 
2775
                   'bzrlib.tests.test_decorators',
 
2776
                   'bzrlib.tests.test_delta',
 
2777
                   'bzrlib.tests.test_deprecated_graph',
 
2778
                   'bzrlib.tests.test_diff',
 
2779
                   'bzrlib.tests.test_dirstate',
 
2780
                   'bzrlib.tests.test_directory_service',
 
2781
                   'bzrlib.tests.test_email_message',
 
2782
                   'bzrlib.tests.test_errors',
 
2783
                   'bzrlib.tests.test_extract',
 
2784
                   'bzrlib.tests.test_fetch',
 
2785
                   'bzrlib.tests.test_ftp_transport',
 
2786
                   'bzrlib.tests.test_generate_docs',
 
2787
                   'bzrlib.tests.test_generate_ids',
 
2788
                   'bzrlib.tests.test_globbing',
 
2789
                   'bzrlib.tests.test_gpg',
 
2790
                   'bzrlib.tests.test_graph',
 
2791
                   'bzrlib.tests.test_hashcache',
 
2792
                   'bzrlib.tests.test_help',
 
2793
                   'bzrlib.tests.test_hooks',
 
2794
                   'bzrlib.tests.test_http',
 
2795
                   'bzrlib.tests.test_http_implementations',
 
2796
                   'bzrlib.tests.test_http_response',
 
2797
                   'bzrlib.tests.test_https_ca_bundle',
 
2798
                   'bzrlib.tests.test_identitymap',
 
2799
                   'bzrlib.tests.test_ignores',
 
2800
                   'bzrlib.tests.test_index',
 
2801
                   'bzrlib.tests.test_info',
 
2802
                   'bzrlib.tests.test_inv',
 
2803
                   'bzrlib.tests.test_knit',
 
2804
                   'bzrlib.tests.test_lazy_import',
 
2805
                   'bzrlib.tests.test_lazy_regex',
 
2806
                   'bzrlib.tests.test_lockdir',
 
2807
                   'bzrlib.tests.test_lockable_files',
 
2808
                   'bzrlib.tests.test_log',
 
2809
                   'bzrlib.tests.test_lsprof',
 
2810
                   'bzrlib.tests.test_lru_cache',
 
2811
                   'bzrlib.tests.test_mail_client',
 
2812
                   'bzrlib.tests.test_memorytree',
 
2813
                   'bzrlib.tests.test_merge',
 
2814
                   'bzrlib.tests.test_merge3',
 
2815
                   'bzrlib.tests.test_merge_core',
 
2816
                   'bzrlib.tests.test_merge_directive',
 
2817
                   'bzrlib.tests.test_missing',
 
2818
                   'bzrlib.tests.test_msgeditor',
 
2819
                   'bzrlib.tests.test_multiparent',
 
2820
                   'bzrlib.tests.test_mutabletree',
 
2821
                   'bzrlib.tests.test_nonascii',
 
2822
                   'bzrlib.tests.test_options',
 
2823
                   'bzrlib.tests.test_osutils',
 
2824
                   'bzrlib.tests.test_osutils_encodings',
 
2825
                   'bzrlib.tests.test_pack',
 
2826
                   'bzrlib.tests.test_pack_repository',
 
2827
                   'bzrlib.tests.test_patch',
 
2828
                   'bzrlib.tests.test_patches',
 
2829
                   'bzrlib.tests.test_permissions',
 
2830
                   'bzrlib.tests.test_plugins',
 
2831
                   'bzrlib.tests.test_progress',
 
2832
                   'bzrlib.tests.test_read_bundle',
 
2833
                   'bzrlib.tests.test_reconfigure',
 
2834
                   'bzrlib.tests.test_reconcile',
 
2835
                   'bzrlib.tests.test_registry',
 
2836
                   'bzrlib.tests.test_remote',
 
2837
                   'bzrlib.tests.test_repository',
 
2838
                   'bzrlib.tests.per_repository_reference',
 
2839
                   'bzrlib.tests.test_revert',
 
2840
                   'bzrlib.tests.test_revision',
 
2841
                   'bzrlib.tests.test_revisionspec',
 
2842
                   'bzrlib.tests.test_revisiontree',
 
2843
                   'bzrlib.tests.test_rio',
 
2844
                   'bzrlib.tests.test_rules',
 
2845
                   'bzrlib.tests.test_sampler',
 
2846
                   'bzrlib.tests.test_selftest',
 
2847
                   'bzrlib.tests.test_setup',
 
2848
                   'bzrlib.tests.test_sftp_transport',
 
2849
                   'bzrlib.tests.test_smart',
 
2850
                   'bzrlib.tests.test_smart_add',
 
2851
                   'bzrlib.tests.test_smart_transport',
 
2852
                   'bzrlib.tests.test_smtp_connection',
 
2853
                   'bzrlib.tests.test_source',
 
2854
                   'bzrlib.tests.test_ssh_transport',
 
2855
                   'bzrlib.tests.test_status',
 
2856
                   'bzrlib.tests.test_store',
 
2857
                   'bzrlib.tests.test_strace',
 
2858
                   'bzrlib.tests.test_subsume',
 
2859
                   'bzrlib.tests.test_switch',
 
2860
                   'bzrlib.tests.test_symbol_versioning',
 
2861
                   'bzrlib.tests.test_tag',
 
2862
                   'bzrlib.tests.test_testament',
 
2863
                   'bzrlib.tests.test_textfile',
 
2864
                   'bzrlib.tests.test_textmerge',
 
2865
                   'bzrlib.tests.test_timestamp',
 
2866
                   'bzrlib.tests.test_trace',
 
2867
                   'bzrlib.tests.test_transactions',
 
2868
                   'bzrlib.tests.test_transform',
 
2869
                   'bzrlib.tests.test_transport',
 
2870
                   'bzrlib.tests.test_transport_implementations',
 
2871
                   'bzrlib.tests.test_transport_log',
 
2872
                   'bzrlib.tests.test_tree',
 
2873
                   'bzrlib.tests.test_treebuilder',
 
2874
                   'bzrlib.tests.test_tsort',
 
2875
                   'bzrlib.tests.test_tuned_gzip',
 
2876
                   'bzrlib.tests.test_ui',
 
2877
                   'bzrlib.tests.test_uncommit',
 
2878
                   'bzrlib.tests.test_upgrade',
 
2879
                   'bzrlib.tests.test_upgrade_stacked',
 
2880
                   'bzrlib.tests.test_urlutils',
 
2881
                   'bzrlib.tests.test_versionedfile',
 
2882
                   'bzrlib.tests.test_version',
 
2883
                   'bzrlib.tests.test_version_info',
 
2884
                   'bzrlib.tests.test__walkdirs_win32',
 
2885
                   'bzrlib.tests.test_weave',
 
2886
                   'bzrlib.tests.test_whitebox',
 
2887
                   'bzrlib.tests.test_win32utils',
 
2888
                   'bzrlib.tests.test_workingtree',
 
2889
                   'bzrlib.tests.test_workingtree_4',
 
2890
                   'bzrlib.tests.test_wsgi',
 
2891
                   'bzrlib.tests.test_xml',
 
2892
                   'bzrlib.tests.tree_implementations',
 
2893
                   'bzrlib.tests.workingtree_implementations',
 
2894
                   ]
4181
2895
 
4182
2896
    loader = TestUtil.TestLoader()
4183
2897
 
4184
 
    if keep_only is not None:
4185
 
        id_filter = TestIdList(keep_only)
4186
2898
    if starting_with:
 
2899
        starting_with = [test_prefix_alias_registry.resolve_alias(start)
 
2900
                         for start in starting_with]
4187
2901
        # We take precedence over keep_only because *at loading time* using
4188
2902
        # both options means we will load less tests for the same final result.
4189
2903
        def interesting_module(name):
4199
2913
        loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
4200
2914
 
4201
2915
    elif keep_only is not None:
 
2916
        id_filter = TestIdList(keep_only)
4202
2917
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
4203
2918
        def interesting_module(name):
4204
2919
            return id_filter.refers_to(name)
4212
2927
    suite = loader.suiteClass()
4213
2928
 
4214
2929
    # modules building their suite with loadTestsFromModuleNames
4215
 
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
4216
 
 
4217
 
    for mod in _test_suite_modules_to_doctest():
 
2930
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
2931
 
 
2932
    modules_to_doctest = [
 
2933
        'bzrlib',
 
2934
        'bzrlib.errors',
 
2935
        'bzrlib.export',
 
2936
        'bzrlib.inventory',
 
2937
        'bzrlib.iterablefile',
 
2938
        'bzrlib.lockdir',
 
2939
        'bzrlib.merge3',
 
2940
        'bzrlib.option',
 
2941
        'bzrlib.store',
 
2942
        'bzrlib.symbol_versioning',
 
2943
        'bzrlib.tests',
 
2944
        'bzrlib.timestamp',
 
2945
        'bzrlib.version_info_formats.format_custom',
 
2946
        ]
 
2947
 
 
2948
    for mod in modules_to_doctest:
4218
2949
        if not interesting_module(mod):
4219
2950
            # No tests to keep here, move along
4220
2951
            continue
4221
2952
        try:
4222
 
            # note that this really does mean "report only" -- doctest
4223
 
            # still runs the rest of the examples
4224
 
            doc_suite = IsolatedDocTestSuite(
4225
 
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
2953
            doc_suite = doctest.DocTestSuite(mod)
4226
2954
        except ValueError, e:
4227
2955
            print '**failed to get doctest for: %s\n%s' % (mod, e)
4228
2956
            raise
4229
 
        if len(doc_suite._tests) == 0:
4230
 
            raise errors.BzrError("no doctests found in %s" % (mod,))
4231
2957
        suite.addTest(doc_suite)
4232
2958
 
4233
2959
    default_encoding = sys.getdefaultencoding()
4234
 
    for name, plugin in _mod_plugin.plugins().items():
 
2960
    for name, plugin in bzrlib.plugin.plugins().items():
4235
2961
        if not interesting_module(plugin.module.__name__):
4236
2962
            continue
4237
2963
        plugin_suite = plugin.test_suite()
4243
2969
        if plugin_suite is not None:
4244
2970
            suite.addTest(plugin_suite)
4245
2971
        if default_encoding != sys.getdefaultencoding():
4246
 
            trace.warning(
 
2972
            bzrlib.trace.warning(
4247
2973
                'Plugin "%s" tried to reset default encoding to: %s', name,
4248
2974
                sys.getdefaultencoding())
4249
2975
            reload(sys)
4250
2976
            sys.setdefaultencoding(default_encoding)
4251
2977
 
 
2978
    if starting_with:
 
2979
        suite = filter_suite_by_id_startswith(suite, starting_with)
 
2980
 
4252
2981
    if keep_only is not None:
4253
2982
        # Now that the referred modules have loaded their tests, keep only the
4254
2983
        # requested ones.
4264
2993
            # Some tests mentioned in the list are not in the test suite. The
4265
2994
            # list may be out of date, report to the tester.
4266
2995
            for id in not_found:
4267
 
                trace.warning('"%s" not found in the test suite', id)
 
2996
                bzrlib.trace.warning('"%s" not found in the test suite', id)
4268
2997
        for id in duplicates:
4269
 
            trace.warning('"%s" is used as an id by several tests', id)
 
2998
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
4270
2999
 
4271
3000
    return suite
4272
3001
 
4273
3002
 
4274
 
def multiply_scenarios(*scenarios):
4275
 
    """Multiply two or more iterables of scenarios.
4276
 
 
4277
 
    It is safe to pass scenario generators or iterators.
4278
 
 
4279
 
    :returns: A list of compound scenarios: the cross-product of all 
4280
 
        scenarios, with the names concatenated and the parameters
4281
 
        merged together.
 
3003
def multiply_tests_from_modules(module_name_list, scenario_iter, loader=None):
 
3004
    """Adapt all tests in some given modules to given scenarios.
 
3005
 
 
3006
    This is the recommended public interface for test parameterization.
 
3007
    Typically the test_suite() method for a per-implementation test
 
3008
    suite will call multiply_tests_from_modules and return the 
 
3009
    result.
 
3010
 
 
3011
    :param module_name_list: List of fully-qualified names of test
 
3012
        modules.
 
3013
    :param scenario_iter: Iterable of pairs of (scenario_name, 
 
3014
        scenario_param_dict).
 
3015
    :param loader: If provided, will be used instead of a new 
 
3016
        bzrlib.tests.TestLoader() instance.
 
3017
 
 
3018
    This returns a new TestSuite containing the cross product of
 
3019
    all the tests in all the modules, each repeated for each scenario.
 
3020
    Each test is adapted by adding the scenario name at the end 
 
3021
    of its name, and updating the test object's __dict__ with the
 
3022
    scenario_param_dict.
 
3023
 
 
3024
    >>> r = multiply_tests_from_modules(
 
3025
    ...     ['bzrlib.tests.test_sampler'],
 
3026
    ...     [('one', dict(param=1)), 
 
3027
    ...      ('two', dict(param=2))])
 
3028
    >>> tests = list(iter_suite_tests(r))
 
3029
    >>> len(tests)
 
3030
    2
 
3031
    >>> tests[0].id()
 
3032
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
 
3033
    >>> tests[0].param
 
3034
    1
 
3035
    >>> tests[1].param
 
3036
    2
4282
3037
    """
4283
 
    return reduce(_multiply_two_scenarios, map(list, scenarios))
4284
 
 
4285
 
 
4286
 
def _multiply_two_scenarios(scenarios_left, scenarios_right):
 
3038
    # XXX: Isn't load_tests() a better way to provide the same functionality
 
3039
    # without forcing a predefined TestScenarioApplier ? --vila 080215
 
3040
    if loader is None:
 
3041
        loader = TestUtil.TestLoader()
 
3042
 
 
3043
    suite = loader.suiteClass()
 
3044
 
 
3045
    adapter = TestScenarioApplier()
 
3046
    adapter.scenarios = list(scenario_iter)
 
3047
    adapt_modules(module_name_list, adapter, loader, suite)
 
3048
    return suite
 
3049
 
 
3050
 
 
3051
def multiply_scenarios(scenarios_left, scenarios_right):
4287
3052
    """Multiply two sets of scenarios.
4288
3053
 
4289
3054
    :returns: the cartesian product of the two sets of scenarios, that is
4297
3062
        for right_name, right_dict in scenarios_right]
4298
3063
 
4299
3064
 
4300
 
def multiply_tests(tests, scenarios, result):
4301
 
    """Multiply tests_list by scenarios into result.
4302
 
 
4303
 
    This is the core workhorse for test parameterisation.
4304
 
 
4305
 
    Typically the load_tests() method for a per-implementation test suite will
4306
 
    call multiply_tests and return the result.
4307
 
 
4308
 
    :param tests: The tests to parameterise.
4309
 
    :param scenarios: The scenarios to apply: pairs of (scenario_name,
4310
 
        scenario_param_dict).
4311
 
    :param result: A TestSuite to add created tests to.
4312
 
 
4313
 
    This returns the passed in result TestSuite with the cross product of all
4314
 
    the tests repeated once for each scenario.  Each test is adapted by adding
4315
 
    the scenario name at the end of its id(), and updating the test object's
4316
 
    __dict__ with the scenario_param_dict.
4317
 
 
4318
 
    >>> import bzrlib.tests.test_sampler
4319
 
    >>> r = multiply_tests(
4320
 
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
4321
 
    ...     [('one', dict(param=1)),
4322
 
    ...      ('two', dict(param=2))],
4323
 
    ...     TestUtil.TestSuite())
4324
 
    >>> tests = list(iter_suite_tests(r))
4325
 
    >>> len(tests)
4326
 
    2
4327
 
    >>> tests[0].id()
4328
 
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
4329
 
    >>> tests[0].param
4330
 
    1
4331
 
    >>> tests[1].param
4332
 
    2
4333
 
    """
4334
 
    for test in iter_suite_tests(tests):
4335
 
        apply_scenarios(test, scenarios, result)
4336
 
    return result
4337
 
 
4338
 
 
4339
 
def apply_scenarios(test, scenarios, result):
4340
 
    """Apply the scenarios in scenarios to test and add to result.
4341
 
 
4342
 
    :param test: The test to apply scenarios to.
4343
 
    :param scenarios: An iterable of scenarios to apply to test.
4344
 
    :return: result
4345
 
    :seealso: apply_scenario
4346
 
    """
4347
 
    for scenario in scenarios:
4348
 
        result.addTest(apply_scenario(test, scenario))
4349
 
    return result
4350
 
 
4351
 
 
4352
 
def apply_scenario(test, scenario):
4353
 
    """Copy test and apply scenario to it.
4354
 
 
4355
 
    :param test: A test to adapt.
4356
 
    :param scenario: A tuple describing the scenario.
4357
 
        The first element of the tuple is the new test id.
4358
 
        The second element is a dict containing attributes to set on the
4359
 
        test.
4360
 
    :return: The adapted test.
4361
 
    """
4362
 
    new_id = "%s(%s)" % (test.id(), scenario[0])
4363
 
    new_test = clone_test(test, new_id)
4364
 
    for name, value in scenario[1].items():
4365
 
        setattr(new_test, name, value)
4366
 
    return new_test
4367
 
 
4368
 
 
4369
 
def clone_test(test, new_id):
4370
 
    """Clone a test giving it a new id.
4371
 
 
4372
 
    :param test: The test to clone.
4373
 
    :param new_id: The id to assign to it.
4374
 
    :return: The new test.
4375
 
    """
4376
 
    new_test = copy.copy(test)
4377
 
    new_test.id = lambda: new_id
4378
 
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
4379
 
    # causes cloned tests to share the 'details' dict.  This makes it hard to
4380
 
    # read the test output for parameterized tests, because tracebacks will be
4381
 
    # associated with irrelevant tests.
4382
 
    try:
4383
 
        details = new_test._TestCase__details
4384
 
    except AttributeError:
4385
 
        # must be a different version of testtools than expected.  Do nothing.
4386
 
        pass
4387
 
    else:
4388
 
        # Reset the '__details' dict.
4389
 
        new_test._TestCase__details = {}
4390
 
    return new_test
4391
 
 
4392
 
 
4393
 
def permute_tests_for_extension(standard_tests, loader, py_module_name,
4394
 
                                ext_module_name):
4395
 
    """Helper for permutating tests against an extension module.
4396
 
 
4397
 
    This is meant to be used inside a modules 'load_tests()' function. It will
4398
 
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
4399
 
    against both implementations. Setting 'test.module' to the appropriate
4400
 
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
4401
 
 
4402
 
    :param standard_tests: A test suite to permute
4403
 
    :param loader: A TestLoader
4404
 
    :param py_module_name: The python path to a python module that can always
4405
 
        be loaded, and will be considered the 'python' implementation. (eg
4406
 
        'bzrlib._chk_map_py')
4407
 
    :param ext_module_name: The python path to an extension module. If the
4408
 
        module cannot be loaded, a single test will be added, which notes that
4409
 
        the module is not available. If it can be loaded, all standard_tests
4410
 
        will be run against that module.
4411
 
    :return: (suite, feature) suite is a test-suite that has all the permuted
4412
 
        tests. feature is the Feature object that can be used to determine if
4413
 
        the module is available.
4414
 
    """
4415
 
 
4416
 
    from bzrlib.tests.features import ModuleAvailableFeature
4417
 
    py_module = pyutils.get_named_object(py_module_name)
4418
 
    scenarios = [
4419
 
        ('python', {'module': py_module}),
4420
 
    ]
4421
 
    suite = loader.suiteClass()
4422
 
    feature = ModuleAvailableFeature(ext_module_name)
4423
 
    if feature.available():
4424
 
        scenarios.append(('C', {'module': feature.module}))
4425
 
    else:
4426
 
        # the compiled module isn't available, so we add a failing test
4427
 
        class FailWithoutFeature(TestCase):
4428
 
            def test_fail(self):
4429
 
                self.requireFeature(feature)
4430
 
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
4431
 
    result = multiply_tests(standard_tests, scenarios, suite)
4432
 
    return result, feature
4433
 
 
4434
 
 
4435
 
def _rmtree_temp_dir(dirname, test_id=None):
 
3065
 
 
3066
def adapt_modules(mods_list, adapter, loader, suite):
 
3067
    """Adapt the modules in mods_list using adapter and add to suite."""
 
3068
    tests = loader.loadTestsFromModuleNames(mods_list)
 
3069
    adapt_tests(tests, adapter, suite)
 
3070
 
 
3071
 
 
3072
def adapt_tests(tests_list, adapter, suite):
 
3073
    """Adapt the tests in tests_list using adapter and add to suite."""
 
3074
    for test in iter_suite_tests(tests_list):
 
3075
        suite.addTests(adapter.adapt(test))
 
3076
 
 
3077
 
 
3078
def _rmtree_temp_dir(dirname):
4436
3079
    # If LANG=C we probably have created some bogus paths
4437
3080
    # which rmtree(unicode) will fail to delete
4438
3081
    # so make sure we are using rmtree(str) to delete everything
4447
3090
    try:
4448
3091
        osutils.rmtree(dirname)
4449
3092
    except OSError, e:
4450
 
        # We don't want to fail here because some useful display will be lost
4451
 
        # otherwise. Polluting the tmp dir is bad, but not giving all the
4452
 
        # possible info to the test runner is even worse.
4453
 
        if test_id != None:
4454
 
            ui.ui_factory.clear_term()
4455
 
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
4456
 
        # Ugly, but the last thing we want here is fail, so bear with it.
4457
 
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
4458
 
                                    ).encode('ascii', 'replace')
4459
 
        sys.stderr.write('Unable to remove testing dir %s\n%s'
4460
 
                         % (os.path.basename(dirname), printable_e))
 
3093
        if sys.platform == 'win32' and e.errno == errno.EACCES:
 
3094
            sys.stderr.write(('Permission denied: '
 
3095
                                 'unable to remove testing dir '
 
3096
                                 '%s\n' % os.path.basename(dirname)))
 
3097
        else:
 
3098
            raise
 
3099
 
 
3100
 
 
3101
class Feature(object):
 
3102
    """An operating system Feature."""
 
3103
 
 
3104
    def __init__(self):
 
3105
        self._available = None
 
3106
 
 
3107
    def available(self):
 
3108
        """Is the feature available?
 
3109
 
 
3110
        :return: True if the feature is available.
 
3111
        """
 
3112
        if self._available is None:
 
3113
            self._available = self._probe()
 
3114
        return self._available
 
3115
 
 
3116
    def _probe(self):
 
3117
        """Implement this method in concrete features.
 
3118
 
 
3119
        :return: True if the feature is available.
 
3120
        """
 
3121
        raise NotImplementedError
 
3122
 
 
3123
    def __str__(self):
 
3124
        if getattr(self, 'feature_name', None):
 
3125
            return self.feature_name()
 
3126
        return self.__class__.__name__
 
3127
 
 
3128
 
 
3129
class _SymlinkFeature(Feature):
 
3130
 
 
3131
    def _probe(self):
 
3132
        return osutils.has_symlinks()
 
3133
 
 
3134
    def feature_name(self):
 
3135
        return 'symlinks'
 
3136
 
 
3137
SymlinkFeature = _SymlinkFeature()
 
3138
 
 
3139
 
 
3140
class _HardlinkFeature(Feature):
 
3141
 
 
3142
    def _probe(self):
 
3143
        return osutils.has_hardlinks()
 
3144
 
 
3145
    def feature_name(self):
 
3146
        return 'hardlinks'
 
3147
 
 
3148
HardlinkFeature = _HardlinkFeature()
 
3149
 
 
3150
 
 
3151
class _OsFifoFeature(Feature):
 
3152
 
 
3153
    def _probe(self):
 
3154
        return getattr(os, 'mkfifo', None)
 
3155
 
 
3156
    def feature_name(self):
 
3157
        return 'filesystem fifos'
 
3158
 
 
3159
OsFifoFeature = _OsFifoFeature()
 
3160
 
 
3161
 
 
3162
class _UnicodeFilenameFeature(Feature):
 
3163
    """Does the filesystem support Unicode filenames?"""
 
3164
 
 
3165
    def _probe(self):
 
3166
        try:
 
3167
            # Check for character combinations unlikely to be covered by any
 
3168
            # single non-unicode encoding. We use the characters
 
3169
            # - greek small letter alpha (U+03B1) and
 
3170
            # - braille pattern dots-123456 (U+283F).
 
3171
            os.stat(u'\u03b1\u283f')
 
3172
        except UnicodeEncodeError:
 
3173
            return False
 
3174
        except (IOError, OSError):
 
3175
            # The filesystem allows the Unicode filename but the file doesn't
 
3176
            # exist.
 
3177
            return True
 
3178
        else:
 
3179
            # The filesystem allows the Unicode filename and the file exists,
 
3180
            # for some reason.
 
3181
            return True
 
3182
 
 
3183
UnicodeFilenameFeature = _UnicodeFilenameFeature()
 
3184
 
 
3185
 
 
3186
class TestScenarioApplier(object):
 
3187
    """A tool to apply scenarios to tests."""
 
3188
 
 
3189
    def adapt(self, test):
 
3190
        """Return a TestSuite containing a copy of test for each scenario."""
 
3191
        result = unittest.TestSuite()
 
3192
        for scenario in self.scenarios:
 
3193
            result.addTest(self.adapt_test_to_scenario(test, scenario))
 
3194
        return result
 
3195
 
 
3196
    def adapt_test_to_scenario(self, test, scenario):
 
3197
        """Copy test and apply scenario to it.
 
3198
 
 
3199
        :param test: A test to adapt.
 
3200
        :param scenario: A tuple describing the scenarion.
 
3201
            The first element of the tuple is the new test id.
 
3202
            The second element is a dict containing attributes to set on the
 
3203
            test.
 
3204
        :return: The adapted test.
 
3205
        """
 
3206
        from copy import deepcopy
 
3207
        new_test = deepcopy(test)
 
3208
        for name, value in scenario[1].items():
 
3209
            setattr(new_test, name, value)
 
3210
        new_id = "%s(%s)" % (new_test.id(), scenario[0])
 
3211
        new_test.id = lambda: new_id
 
3212
        return new_test
4461
3213
 
4462
3214
 
4463
3215
def probe_unicode_in_user_encoding():
4469
3221
    possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
4470
3222
    for uni_val in possible_vals:
4471
3223
        try:
4472
 
            str_val = uni_val.encode(osutils.get_user_encoding())
 
3224
            str_val = uni_val.encode(bzrlib.user_encoding)
4473
3225
        except UnicodeEncodeError:
4474
3226
            # Try a different character
4475
3227
            pass
4493
3245
    return None
4494
3246
 
4495
3247
 
4496
 
# Only define SubUnitBzrRunner if subunit is available.
4497
 
try:
4498
 
    from subunit import TestProtocolClient
4499
 
    from subunit.test_results import AutoTimingTestResultDecorator
4500
 
    class SubUnitBzrProtocolClient(TestProtocolClient):
4501
 
 
4502
 
        def stopTest(self, test):
4503
 
            super(SubUnitBzrProtocolClient, self).stopTest(test)
4504
 
            _clear__type_equality_funcs(test)
4505
 
 
4506
 
        def addSuccess(self, test, details=None):
4507
 
            # The subunit client always includes the details in the subunit
4508
 
            # stream, but we don't want to include it in ours.
4509
 
            if details is not None and 'log' in details:
4510
 
                del details['log']
4511
 
            return super(SubUnitBzrProtocolClient, self).addSuccess(
4512
 
                test, details)
4513
 
 
4514
 
    class SubUnitBzrRunner(TextTestRunner):
4515
 
        def run(self, test):
4516
 
            result = AutoTimingTestResultDecorator(
4517
 
                SubUnitBzrProtocolClient(self.stream))
4518
 
            test.run(result)
4519
 
            return result
4520
 
except ImportError:
4521
 
    pass
4522
 
 
4523
 
 
4524
 
# API compatibility for old plugins; see bug 892622.
4525
 
for name in [
4526
 
    'Feature',
4527
 
    'HTTPServerFeature', 
4528
 
    'ModuleAvailableFeature',
4529
 
    'HTTPSServerFeature', 'SymlinkFeature', 'HardlinkFeature',
4530
 
    'OsFifoFeature', 'UnicodeFilenameFeature',
4531
 
    'ByteStringNamedFilesystem', 'UTF8Filesystem',
4532
 
    'BreakinFeature', 'CaseInsCasePresFilenameFeature',
4533
 
    'CaseInsensitiveFilesystemFeature', 'case_sensitive_filesystem_feature',
4534
 
    'posix_permissions_feature',
4535
 
    ]:
4536
 
    globals()[name] = _CompatabilityThunkFeature(
4537
 
        symbol_versioning.deprecated_in((2, 5, 0)),
4538
 
        'bzrlib.tests', name,
4539
 
        name, 'bzrlib.tests.features')
4540
 
 
4541
 
 
4542
 
for (old_name, new_name) in [
4543
 
    ('UnicodeFilename', 'UnicodeFilenameFeature'),
4544
 
    ]:
4545
 
    globals()[name] = _CompatabilityThunkFeature(
4546
 
        symbol_versioning.deprecated_in((2, 5, 0)),
4547
 
        'bzrlib.tests', old_name,
4548
 
        new_name, 'bzrlib.tests.features')
 
3248
class _FTPServerFeature(Feature):
 
3249
    """Some tests want an FTP Server, check if one is available.
 
3250
 
 
3251
    Right now, the only way this is available is if 'medusa' is installed.
 
3252
    http://www.amk.ca/python/code/medusa.html
 
3253
    """
 
3254
 
 
3255
    def _probe(self):
 
3256
        try:
 
3257
            import bzrlib.tests.ftp_server
 
3258
            return True
 
3259
        except ImportError:
 
3260
            return False
 
3261
 
 
3262
    def feature_name(self):
 
3263
        return 'FTPServer'
 
3264
 
 
3265
FTPServerFeature = _FTPServerFeature()
 
3266
 
 
3267
 
 
3268
class _UnicodeFilename(Feature):
 
3269
    """Does the filesystem support Unicode filenames?"""
 
3270
 
 
3271
    def _probe(self):
 
3272
        try:
 
3273
            os.stat(u'\u03b1')
 
3274
        except UnicodeEncodeError:
 
3275
            return False
 
3276
        except (IOError, OSError):
 
3277
            # The filesystem allows the Unicode filename but the file doesn't
 
3278
            # exist.
 
3279
            return True
 
3280
        else:
 
3281
            # The filesystem allows the Unicode filename and the file exists,
 
3282
            # for some reason.
 
3283
            return True
 
3284
 
 
3285
UnicodeFilename = _UnicodeFilename()
 
3286
 
 
3287
 
 
3288
class _UTF8Filesystem(Feature):
 
3289
    """Is the filesystem UTF-8?"""
 
3290
 
 
3291
    def _probe(self):
 
3292
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
 
3293
            return True
 
3294
        return False
 
3295
 
 
3296
UTF8Filesystem = _UTF8Filesystem()
 
3297
 
 
3298
 
 
3299
class _CaseInsensitiveFilesystemFeature(Feature):
 
3300
    """Check if underlying filesystem is case-insensitive
 
3301
    (e.g. on Windows, Cygwin, MacOS)
 
3302
    """
 
3303
 
 
3304
    def _probe(self):
 
3305
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
 
3306
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
 
3307
            TestCaseWithMemoryTransport.TEST_ROOT = root
 
3308
        else:
 
3309
            root = TestCaseWithMemoryTransport.TEST_ROOT
 
3310
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
 
3311
            dir=root)
 
3312
        name_a = osutils.pathjoin(tdir, 'a')
 
3313
        name_A = osutils.pathjoin(tdir, 'A')
 
3314
        os.mkdir(name_a)
 
3315
        result = osutils.isdir(name_A)
 
3316
        _rmtree_temp_dir(tdir)
 
3317
        return result
 
3318
 
 
3319
    def feature_name(self):
 
3320
        return 'case-insensitive filesystem'
 
3321
 
 
3322
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()