~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Lukáš Lalinský
  • Date: 2008-08-23 13:06:24 UTC
  • mto: (3650.1.1 bzr.ab.integration)
  • mto: This revision was merged to the branch mainline in revision 3651.
  • Revision ID: lalinsky@gmail.com-20080823130624-rvbasutb8urxkamy
Add a test

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
 
    registry,
81
 
    symbol_versioning,
82
 
    trace,
83
 
    transport as _mod_transport,
84
61
    workingtree,
85
62
    )
 
63
import bzrlib.branch
 
64
import bzrlib.commands
 
65
import bzrlib.timestamp
 
66
import bzrlib.export
 
67
import bzrlib.inventory
 
68
import bzrlib.iterablefile
 
69
import bzrlib.lockdir
86
70
try:
87
71
    import bzrlib.lsprof
88
72
except ImportError:
89
73
    # lsprof not available
90
74
    pass
91
 
from bzrlib.smart import client, request
92
 
from bzrlib.transport import (
93
 
    memory,
94
 
    pathfilter,
95
 
    )
 
75
from bzrlib.merge import merge_inner
 
76
import bzrlib.merge3
 
77
import bzrlib.plugin
 
78
import bzrlib.store
 
79
from bzrlib import symbol_versioning
96
80
from bzrlib.symbol_versioning import (
 
81
    DEPRECATED_PARAMETER,
97
82
    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
 
83
    deprecated_method,
 
84
    deprecated_passed,
 
85
    )
 
86
import bzrlib.trace
 
87
from bzrlib.transport import get_transport
 
88
import bzrlib.transport
 
89
from bzrlib.transport.local import LocalURLServer
 
90
from bzrlib.transport.memory import MemoryServer
 
91
from bzrlib.transport.readonly import ReadonlyServer
 
92
from bzrlib.trace import mutter, note
 
93
from bzrlib.tests import TestUtil
 
94
from bzrlib.tests.http_server import HttpServer
 
95
from bzrlib.tests.TestUtil import (
 
96
                          TestSuite,
 
97
                          TestLoader,
 
98
                          )
 
99
from bzrlib.tests.treeshape import build_tree_contents
 
100
import bzrlib.version_info_formats.format_custom
 
101
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
109
102
 
110
103
# Mark this python module as being part of the implementation
111
104
# of unittest: this gives us better tracebacks where the last
112
105
# shown frame is the test code, not our assertXYZ.
113
106
__unittest = 1
114
107
 
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):
 
108
default_transport = LocalURLServer
 
109
 
 
110
 
 
111
class ExtendedTestResult(unittest._TextTestResult):
244
112
    """Accepts, reports and accumulates the results of running tests.
245
113
 
246
114
    Compared to the unittest version this class adds support for
249
117
    different types of display.
250
118
 
251
119
    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
 
120
    addFailure or addError classes.  These in turn may redirect to a more
253
121
    specific case for the special test results supported by our extended
254
122
    tests.
255
123
 
257
125
    """
258
126
 
259
127
    stop_early = False
260
 
 
 
128
    
261
129
    def __init__(self, stream, descriptions, verbosity,
262
130
                 bench_history=None,
263
 
                 strict=False,
 
131
                 num_tests=None,
264
132
                 ):
265
133
        """Construct new TestResult.
266
134
 
267
135
        :param bench_history: Optionally, a writable file object to accumulate
268
136
            benchmark results.
269
137
        """
270
 
        testtools.TextTestResult.__init__(self, stream)
 
138
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
271
139
        if bench_history is not None:
272
140
            from bzrlib.version import _get_bzr_source_tree
273
141
            src_tree = _get_bzr_source_tree()
284
152
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
285
153
        self._bench_history = bench_history
286
154
        self.ui = ui.ui_factory
287
 
        self.num_tests = 0
 
155
        self.num_tests = num_tests
288
156
        self.error_count = 0
289
157
        self.failure_count = 0
290
158
        self.known_failure_count = 0
293
161
        self.unsupported = {}
294
162
        self.count = 0
295
163
        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):
 
164
    
 
165
    def _extractBenchmarkTime(self, testCase):
358
166
        """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
167
        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
 
 
 
168
    
372
169
    def _elapsedTestTimeString(self):
373
170
        """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))
 
171
        return self._formatTime(time.time() - self._start_time)
376
172
 
377
173
    def _testTimeString(self, testCase):
378
174
        benchmark_time = self._extractBenchmarkTime(testCase)
379
175
        if benchmark_time is not None:
380
 
            return self._formatTime(benchmark_time) + "*"
 
176
            return "%s/%s" % (
 
177
                self._formatTime(benchmark_time),
 
178
                self._elapsedTestTimeString())
381
179
        else:
382
 
            return self._elapsedTestTimeString()
 
180
            return "           %s" % self._elapsedTestTimeString()
383
181
 
384
182
    def _formatTime(self, seconds):
385
183
        """Format seconds as milliseconds with leading spaces."""
389
187
 
390
188
    def _shortened_test_description(self, test):
391
189
        what = test.id()
392
 
        what = re.sub(r'^bzrlib\.tests\.', '', what)
 
190
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
393
191
        return what
394
192
 
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
193
    def startTest(self, test):
404
 
        super(ExtendedTestResult, self).startTest(test)
405
 
        if self.count == 0:
406
 
            self.startTests()
407
 
        self.count += 1
 
194
        unittest.TestResult.startTest(self, test)
408
195
        self.report_test_start(test)
409
196
        test.number = self.count
410
197
        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
198
 
448
199
    def _recordTestStartTime(self):
449
200
        """Record that a test has started."""
450
 
        self._start_datetime = self._now()
 
201
        self._start_time = time.time()
 
202
 
 
203
    def _cleanupLogFile(self, test):
 
204
        # We can only do this if we have one of our TestCases, not if
 
205
        # we have a doctest.
 
206
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
 
207
        if setKeepLogfile is not None:
 
208
            setKeepLogfile()
451
209
 
452
210
    def addError(self, test, err):
453
211
        """Tell result that test finished with an error.
455
213
        Called from the TestCase run() method when the test
456
214
        fails with an unexpected error.
457
215
        """
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()
 
216
        self._testConcluded(test)
 
217
        if isinstance(err[1], TestSkipped):
 
218
            return self._addSkipped(test, err)
 
219
        elif isinstance(err[1], UnavailableFeature):
 
220
            return self.addNotSupported(test, err[1].args[0])
 
221
        else:
 
222
            unittest.TestResult.addError(self, test, err)
 
223
            self.error_count += 1
 
224
            self.report_error(test, err)
 
225
            if self.stop_early:
 
226
                self.stop()
 
227
            self._cleanupLogFile(test)
464
228
 
465
229
    def addFailure(self, test, err):
466
230
        """Tell result that test failed.
468
232
        Called from the TestCase run() method when the test
469
233
        fails because e.g. an assert() method failed.
470
234
        """
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()
 
235
        self._testConcluded(test)
 
236
        if isinstance(err[1], KnownFailure):
 
237
            return self._addKnownFailure(test, err)
 
238
        else:
 
239
            unittest.TestResult.addFailure(self, test, err)
 
240
            self.failure_count += 1
 
241
            self.report_failure(test, err)
 
242
            if self.stop_early:
 
243
                self.stop()
 
244
            self._cleanupLogFile(test)
477
245
 
478
 
    def addSuccess(self, test, details=None):
 
246
    def addSuccess(self, test):
479
247
        """Tell result that test completed successfully.
480
248
 
481
249
        Called from the TestCase run()
482
250
        """
 
251
        self._testConcluded(test)
483
252
        if self._bench_history is not None:
484
 
            benchmark_time = self._extractBenchmarkTime(test, details)
 
253
            benchmark_time = self._extractBenchmarkTime(test)
485
254
            if benchmark_time is not None:
486
255
                self._bench_history.write("%s %s\n" % (
487
256
                    self._formatTime(benchmark_time),
488
257
                    test.id()))
489
258
        self.report_success(test)
490
 
        super(ExtendedTestResult, self).addSuccess(test)
 
259
        self._cleanupLogFile(test)
 
260
        unittest.TestResult.addSuccess(self, test)
491
261
        test._log_contents = ''
492
262
 
493
 
    def addExpectedFailure(self, test, err):
 
263
    def _testConcluded(self, test):
 
264
        """Common code when a test has finished.
 
265
 
 
266
        Called regardless of whether it succeded, failed, etc.
 
267
        """
 
268
        pass
 
269
 
 
270
    def _addKnownFailure(self, test, err):
494
271
        self.known_failure_count += 1
495
272
        self.report_known_failure(test, err)
496
273
 
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
274
    def addNotSupported(self, test, feature):
511
275
        """The test will not be run because of a missing feature.
512
276
        """
513
277
        # this can be called in two different ways: it may be that the
514
 
        # test started running, and then raised (through requireFeature)
 
278
        # test started running, and then raised (through addError) 
515
279
        # 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.
 
280
        # while probing for features before running the tests; in that
 
281
        # case we will see startTest and stopTest, but the test will never
 
282
        # actually run.
519
283
        self.unsupported.setdefault(str(feature), 0)
520
284
        self.unsupported[str(feature)] += 1
521
285
        self.report_unsupported(test, feature)
522
286
 
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()
 
287
    def _addSkipped(self, test, skip_excinfo):
 
288
        if isinstance(skip_excinfo[1], TestNotApplicable):
 
289
            self.not_applicable_count += 1
 
290
            self.report_not_applicable(test, skip_excinfo)
 
291
        else:
 
292
            self.skip_count += 1
 
293
            self.report_skip(test, skip_excinfo)
 
294
        try:
 
295
            test.tearDown()
 
296
        except KeyboardInterrupt:
 
297
            raise
 
298
        except:
 
299
            self.addError(test, test._exc_info())
 
300
        else:
 
301
            # seems best to treat this as success from point-of-view of unittest
 
302
            # -- it actually does nothing so it barely matters :)
 
303
            unittest.TestResult.addSuccess(self, test)
 
304
            test._log_contents = ''
 
305
 
 
306
    def printErrorList(self, flavour, errors):
 
307
        for test, err in errors:
 
308
            self.stream.writeln(self.separator1)
 
309
            self.stream.write("%s: " % flavour)
 
310
            self.stream.writeln(self.getDescription(test))
 
311
            if getattr(test, '_get_log', None) is not None:
 
312
                self.stream.write('\n')
 
313
                self.stream.write(
 
314
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
 
315
                self.stream.write('\n')
 
316
                self.stream.write(test._get_log())
 
317
                self.stream.write('\n')
 
318
                self.stream.write(
 
319
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
 
320
                self.stream.write('\n')
 
321
            self.stream.writeln(self.separator2)
 
322
            self.stream.writeln("%s" % err)
 
323
 
 
324
    def finished(self):
 
325
        pass
 
326
 
 
327
    def report_cleaning_up(self):
 
328
        pass
585
329
 
586
330
    def report_success(self, test):
587
331
        pass
597
341
 
598
342
    def __init__(self, stream, descriptions, verbosity,
599
343
                 bench_history=None,
 
344
                 num_tests=None,
600
345
                 pb=None,
601
 
                 strict=None,
602
346
                 ):
603
347
        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()
 
348
            bench_history, num_tests)
 
349
        if pb is None:
 
350
            self.pb = self.ui.nested_progress_bar()
 
351
            self._supplied_pb = False
 
352
        else:
 
353
            self.pb = pb
 
354
            self._supplied_pb = True
610
355
        self.pb.show_pct = False
611
356
        self.pb.show_spinner = False
612
357
        self.pb.show_eta = False,
613
358
        self.pb.show_count = False
614
359
        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))
 
360
 
 
361
    def report_starting(self):
 
362
        self.pb.update('[test 0/%d] starting...' % (self.num_tests))
627
363
 
628
364
    def _progress_prefix_text(self):
629
365
        # the longer this text, the less space we have to show the test
635
371
        ##     a += ', %d skip' % self.skip_count
636
372
        ## if self.known_failure_count:
637
373
        ##     a += '+%dX' % self.known_failure_count
638
 
        if self.num_tests:
 
374
        if self.num_tests is not None:
639
375
            a +='/%d' % self.num_tests
640
376
        a += ' in '
641
377
        runtime = time.time() - self._overall_start_time
643
379
            a += '%dm%ds' % (runtime / 60, runtime % 60)
644
380
        else:
645
381
            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)
 
382
        if self.error_count:
 
383
            a += ', %d err' % self.error_count
 
384
        if self.failure_count:
 
385
            a += ', %d fail' % self.failure_count
 
386
        if self.unsupported:
 
387
            a += ', %d missing' % len(self.unsupported)
651
388
        a += ']'
652
389
        return a
653
390
 
654
391
    def report_test_start(self, test):
 
392
        self.count += 1
655
393
        self.pb.update(
656
394
                self._progress_prefix_text()
657
 
                + ' '
 
395
                + ' ' 
658
396
                + self._shortened_test_description(test))
659
397
 
660
398
    def _test_description(self, test):
661
399
        return self._shortened_test_description(test)
662
400
 
663
401
    def report_error(self, test, err):
664
 
        self.stream.write('ERROR: %s\n    %s\n' % (
 
402
        self.pb.note('ERROR: %s\n    %s\n', 
665
403
            self._test_description(test),
666
404
            err[1],
667
 
            ))
 
405
            )
668
406
 
669
407
    def report_failure(self, test, err):
670
 
        self.stream.write('FAIL: %s\n    %s\n' % (
 
408
        self.pb.note('FAIL: %s\n    %s\n', 
671
409
            self._test_description(test),
672
410
            err[1],
673
 
            ))
 
411
            )
674
412
 
675
413
    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):
 
414
        self.pb.note('XFAIL: %s\n%s\n',
 
415
            self._test_description(test), err[1])
 
416
 
 
417
    def report_skip(self, test, skip_excinfo):
 
418
        pass
 
419
 
 
420
    def report_not_applicable(self, test, skip_excinfo):
689
421
        pass
690
422
 
691
423
    def report_unsupported(self, test, feature):
692
424
        """test cannot be run because feature is missing."""
 
425
                  
 
426
    def report_cleaning_up(self):
 
427
        self.pb.update('cleaning up...')
 
428
 
 
429
    def finished(self):
 
430
        if not self._supplied_pb:
 
431
            self.pb.finished()
693
432
 
694
433
 
695
434
class VerboseTestResult(ExtendedTestResult):
703
442
            result = a_string
704
443
        return result.ljust(final_width)
705
444
 
706
 
    def report_tests_starting(self):
 
445
    def report_starting(self):
707
446
        self.stream.write('running %d tests...\n' % self.num_tests)
708
 
        super(VerboseTestResult, self).report_tests_starting()
709
447
 
710
448
    def report_test_start(self, test):
 
449
        self.count += 1
711
450
        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)
 
451
        # width needs space for 6 char status, plus 1 for slash, plus 2 10-char
 
452
        # numbers, plus a trailing blank
 
453
        # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
 
454
        self.stream.write(self._ellipsize_to_right(name,
 
455
                          osutils.terminal_width()-30))
721
456
        self.stream.flush()
722
457
 
723
458
    def _error_summary(self, err):
725
460
        return '%s%s' % (indent, err[1])
726
461
 
727
462
    def report_error(self, test, err):
728
 
        self.stream.write('ERROR %s\n%s\n'
 
463
        self.stream.writeln('ERROR %s\n%s'
729
464
                % (self._testTimeString(test),
730
465
                   self._error_summary(err)))
731
466
 
732
467
    def report_failure(self, test, err):
733
 
        self.stream.write(' FAIL %s\n%s\n'
 
468
        self.stream.writeln(' FAIL %s\n%s'
734
469
                % (self._testTimeString(test),
735
470
                   self._error_summary(err)))
736
471
 
737
472
    def report_known_failure(self, test, err):
738
 
        self.stream.write('XFAIL %s\n%s\n'
 
473
        self.stream.writeln('XFAIL %s\n%s'
739
474
                % (self._testTimeString(test),
740
475
                   self._error_summary(err)))
741
476
 
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
477
    def report_success(self, test):
749
 
        self.stream.write('   OK %s\n' % self._testTimeString(test))
 
478
        self.stream.writeln('   OK %s' % self._testTimeString(test))
750
479
        for bench_called, stats in getattr(test, '_benchcalls', []):
751
 
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
 
480
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
752
481
            stats.pprint(file=self.stream)
753
482
        # flush the stream so that we get smooth output. This verbose mode is
754
483
        # used to show the output in PQM.
755
484
        self.stream.flush()
756
485
 
757
 
    def report_skip(self, test, reason):
758
 
        self.stream.write(' SKIP %s\n%s\n'
759
 
                % (self._testTimeString(test), reason))
 
486
    def report_skip(self, test, skip_excinfo):
 
487
        self.stream.writeln(' SKIP %s\n%s'
 
488
                % (self._testTimeString(test),
 
489
                   self._error_summary(skip_excinfo)))
760
490
 
761
 
    def report_not_applicable(self, test, reason):
762
 
        self.stream.write('  N/A %s\n    %s\n'
763
 
                % (self._testTimeString(test), reason))
 
491
    def report_not_applicable(self, test, skip_excinfo):
 
492
        self.stream.writeln('  N/A %s\n%s'
 
493
                % (self._testTimeString(test),
 
494
                   self._error_summary(skip_excinfo)))
764
495
 
765
496
    def report_unsupported(self, test, feature):
766
497
        """test cannot be run because feature is missing."""
767
 
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
 
498
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
768
499
                %(self._testTimeString(test), feature))
769
500
 
770
501
 
776
507
                 descriptions=0,
777
508
                 verbosity=1,
778
509
                 bench_history=None,
779
 
                 strict=False,
780
 
                 result_decorators=None,
 
510
                 list_only=False
781
511
                 ):
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
 
512
        self.stream = unittest._WritelnDecorator(stream)
806
513
        self.descriptions = descriptions
807
514
        self.verbosity = verbosity
808
515
        self._bench_history = bench_history
809
 
        self._strict = strict
810
 
        self._result_decorators = result_decorators or []
 
516
        self.list_only = list_only
811
517
 
812
518
    def run(self, test):
813
519
        "Run the given test case or test suite."
 
520
        startTime = time.time()
814
521
        if self.verbosity == 1:
815
522
            result_class = TextTestResult
816
523
        elif self.verbosity >= 2:
817
524
            result_class = VerboseTestResult
818
 
        original_result = result_class(self.stream,
 
525
        result = result_class(self.stream,
819
526
                              self.descriptions,
820
527
                              self.verbosity,
821
528
                              bench_history=self._bench_history,
822
 
                              strict=self._strict,
 
529
                              num_tests=test.countTestCases(),
823
530
                              )
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:
 
531
        result.stop_early = self.stop_on_failure
 
532
        result.report_starting()
 
533
        if self.list_only:
 
534
            if self.verbosity >= 2:
 
535
                self.stream.writeln("Listing tests only ...\n")
 
536
            run = 0
 
537
            for t in iter_suite_tests(test):
 
538
                self.stream.writeln("%s" % (t.id()))
 
539
                run += 1
 
540
            actionTaken = "Listed"
 
541
        else: 
832
542
            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
 
543
            run = result.testsRun
 
544
            actionTaken = "Ran"
 
545
        stopTime = time.time()
 
546
        timeTaken = stopTime - startTime
 
547
        result.printErrors()
 
548
        self.stream.writeln(result.separator2)
 
549
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
550
                            run, run != 1 and "s" or "", timeTaken))
 
551
        self.stream.writeln()
 
552
        if not result.wasSuccessful():
 
553
            self.stream.write("FAILED (")
 
554
            failed, errored = map(len, (result.failures, result.errors))
 
555
            if failed:
 
556
                self.stream.write("failures=%d" % failed)
 
557
            if errored:
 
558
                if failed: self.stream.write(", ")
 
559
                self.stream.write("errors=%d" % errored)
 
560
            if result.known_failure_count:
 
561
                if failed or errored: self.stream.write(", ")
 
562
                self.stream.write("known_failure_count=%d" %
 
563
                    result.known_failure_count)
 
564
            self.stream.writeln(")")
 
565
        else:
 
566
            if result.known_failure_count:
 
567
                self.stream.writeln("OK (known_failures=%d)" %
 
568
                    result.known_failure_count)
 
569
            else:
 
570
                self.stream.writeln("OK")
 
571
        if result.skip_count > 0:
 
572
            skipped = result.skip_count
 
573
            self.stream.writeln('%d test%s skipped' %
 
574
                                (skipped, skipped != 1 and "s" or ""))
 
575
        if result.unsupported:
 
576
            for feature, count in sorted(result.unsupported.items()):
 
577
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
578
                    (feature, count))
 
579
        result.finished()
 
580
        return result
838
581
 
839
582
 
840
583
def iter_suite_tests(suite):
841
584
    """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:
 
585
    for item in suite._tests:
 
586
        if isinstance(item, unittest.TestCase):
 
587
            yield item
 
588
        elif isinstance(item, unittest.TestSuite):
846
589
            for r in iter_suite_tests(item):
847
590
                yield r
848
 
    else:
849
 
        raise Exception('unknown type %r for object %r'
850
 
                        % (type(suite), suite))
851
 
 
852
 
 
853
 
TestSkipped = testtools.testcase.TestSkipped
 
591
        else:
 
592
            raise Exception('unknown object %r inside test suite %r'
 
593
                            % (item, suite))
 
594
 
 
595
 
 
596
class TestSkipped(Exception):
 
597
    """Indicates that a test was intentionally skipped, rather than failing."""
854
598
 
855
599
 
856
600
class TestNotApplicable(TestSkipped):
857
601
    """A test is not applicable to the situation where it was run.
858
602
 
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
 
603
    This is only normally raised by parameterized tests, if they find that 
 
604
    the instance they're constructed upon does not support one aspect 
861
605
    of its interface.
862
606
    """
863
607
 
864
608
 
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
 
609
class KnownFailure(AssertionError):
 
610
    """Indicates that a test failed in a precisely expected manner.
 
611
 
 
612
    Such failures dont block the whole test suite from passing because they are
 
613
    indicators of partially completed code or of future work. We have an
 
614
    explicit error for them so that we can ensure that they are always visible:
 
615
    KnownFailures are always shown in the output of bzr selftest.
 
616
    """
882
617
 
883
618
 
884
619
class UnavailableFeature(Exception):
885
620
    """A feature required for this test was not available.
886
621
 
887
 
    This can be considered a specialised form of SkippedTest.
888
 
 
889
622
    The feature should be used to construct the exception.
890
623
    """
891
624
 
892
625
 
 
626
class CommandFailed(Exception):
 
627
    pass
 
628
 
 
629
 
893
630
class StringIOWrapper(object):
894
631
    """A wrapper around cStringIO which just adds an encoding attribute.
895
 
 
 
632
    
896
633
    Internally we can check sys.stdout to see what the output encoding
897
634
    should be. However, cStringIO has no encoding attribute that we can
898
635
    set. So we wrap it instead.
916
653
            return setattr(self._cstring, name, val)
917
654
 
918
655
 
919
 
class TestUIFactory(TextUIFactory):
 
656
class TestUIFactory(ui.CLIUIFactory):
920
657
    """A UI Factory for testing.
921
658
 
922
659
    Hide the progress bar but emit note()s.
923
660
    Redirect stdin.
924
661
    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
662
    """
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
663
 
937
 
    def __init__(self, stdout=None, stderr=None, stdin=None):
 
664
    def __init__(self,
 
665
                 stdout=None,
 
666
                 stderr=None,
 
667
                 stdin=None):
 
668
        super(TestUIFactory, self).__init__()
938
669
        if stdin is not None:
939
670
            # We use a StringIOWrapper to be able to test various
940
671
            # encodings, but the user is still responsible to
941
672
            # encode the string and to set the encoding attribute
942
673
            # of StringIOWrapper.
943
 
            stdin = StringIOWrapper(stdin)
944
 
        super(TestUIFactory, self).__init__(stdin, stdout, stderr)
945
 
 
946
 
    def get_non_echoed_password(self):
 
674
            self.stdin = StringIOWrapper(stdin)
 
675
        if stdout is None:
 
676
            self.stdout = sys.stdout
 
677
        else:
 
678
            self.stdout = stdout
 
679
        if stderr is None:
 
680
            self.stderr = sys.stderr
 
681
        else:
 
682
            self.stderr = stderr
 
683
 
 
684
    def clear(self):
 
685
        """See progress.ProgressBar.clear()."""
 
686
 
 
687
    def clear_term(self):
 
688
        """See progress.ProgressBar.clear_term()."""
 
689
 
 
690
    def clear_term(self):
 
691
        """See progress.ProgressBar.clear_term()."""
 
692
 
 
693
    def finished(self):
 
694
        """See progress.ProgressBar.finished()."""
 
695
 
 
696
    def note(self, fmt_string, *args, **kwargs):
 
697
        """See progress.ProgressBar.note()."""
 
698
        self.stdout.write((fmt_string + "\n") % args)
 
699
 
 
700
    def progress_bar(self):
 
701
        return self
 
702
 
 
703
    def nested_progress_bar(self):
 
704
        return self
 
705
 
 
706
    def update(self, message, count=None, total=None):
 
707
        """See progress.ProgressBar.update()."""
 
708
 
 
709
    def get_non_echoed_password(self, prompt):
947
710
        """Get password from stdin without trying to handle the echo mode"""
 
711
        if prompt:
 
712
            self.stdout.write(prompt.encode(self.stdout.encoding, 'replace'))
948
713
        password = self.stdin.readline()
949
714
        if not password:
950
715
            raise EOFError
952
717
            password = password[:-1]
953
718
        return password
954
719
 
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):
 
720
 
 
721
def _report_leaked_threads():
 
722
    bzrlib.trace.warning('%s is leaking threads among %d leaking tests',
 
723
                         TestCase._first_thread_leaker_id,
 
724
                         TestCase._leaking_threads_tests)
 
725
 
 
726
 
 
727
class TestCase(unittest.TestCase):
979
728
    """Base class for bzr unit tests.
980
 
 
981
 
    Tests that need access to disk resources should subclass
 
729
    
 
730
    Tests that need access to disk resources should subclass 
982
731
    TestCaseInTempDir not TestCase.
983
732
 
984
733
    Error and debug log messages are redirected from their usual
986
735
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
987
736
    so that it can also capture file IO.  When the test completes this file
988
737
    is read into memory and removed from disk.
989
 
 
 
738
       
990
739
    There are also convenience functions to invoke bzr's command-line
991
740
    routine, and to build and check bzr trees.
992
 
 
 
741
   
993
742
    In addition to the usual method of overriding tearDown(), this class also
994
 
    allows subclasses to register cleanup functions via addCleanup, which are
 
743
    allows subclasses to register functions into the _cleanups list, which is
995
744
    run in order as the object is torn down.  It's less likely this will be
996
745
    accidentally overlooked.
997
746
    """
998
747
 
999
 
    _log_file = None
 
748
    _active_threads = None
 
749
    _leaking_threads_tests = 0
 
750
    _first_thread_leaker_id = None
 
751
    _log_file_name = None
 
752
    _log_contents = ''
 
753
    _keep_log_file = False
1000
754
    # record lsprof data when performing benchmark calls.
1001
755
    _gather_lsprof_in_benchmarks = False
 
756
    attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
 
757
                     '_log_contents', '_log_file_name', '_benchtime',
 
758
                     '_TestCase__testMethodName')
1002
759
 
1003
760
    def __init__(self, methodName='testMethod'):
1004
761
        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))
 
762
        self._cleanups = []
1010
763
 
1011
764
    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)
 
765
        unittest.TestCase.setUp(self)
1024
766
        self._cleanEnvironment()
1025
 
 
1026
 
        if bzrlib.global_state is not None:
1027
 
            self.overrideAttr(bzrlib.global_state, 'cmdline_overrides',
1028
 
                              config.CommandLineStore())
1029
 
 
1030
767
        self._silenceUI()
1031
768
        self._startLogFile()
1032
769
        self._benchcalls = []
1033
770
        self._benchtime = None
1034
771
        self._clear_hooks()
1035
 
        self._track_transports()
1036
 
        self._track_locks()
1037
772
        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,))
 
773
        TestCase._active_threads = threading.activeCount()
 
774
        self.addCleanup(self._check_leaked_threads)
 
775
 
 
776
    def _check_leaked_threads(self):
 
777
        active = threading.activeCount()
 
778
        leaked_threads = active - TestCase._active_threads
 
779
        TestCase._active_threads = active
 
780
        if leaked_threads:
 
781
            TestCase._leaking_threads_tests += 1
 
782
            if TestCase._first_thread_leaker_id is None:
 
783
                TestCase._first_thread_leaker_id = self.id()
 
784
                # we're not specifically told when all tests are finished.
 
785
                # This will do. We use a function to avoid keeping a reference
 
786
                # to a TestCase object.
 
787
                atexit.register(_report_leaked_threads)
1118
788
 
1119
789
    def _clear_debug_flags(self):
1120
790
        """Prevent externally set debug flags affecting tests.
1121
 
 
 
791
        
1122
792
        Tests that want to use debug flags can just set them in the
1123
793
        debug_flags set during setup/teardown.
1124
794
        """
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
795
        if 'allow_debug' not in selftest_debug_flags:
 
796
            self._preserved_debug_flags = set(debug.debug_flags)
1128
797
            debug.debug_flags.clear()
1129
 
        if 'disable_lock_checks' not in selftest_debug_flags:
1130
 
            debug.debug_flags.add('strict_locks')
 
798
            self.addCleanup(self._restore_debug_flags)
1131
799
 
1132
800
    def _clear_hooks(self):
1133
801
        # 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 = {}
 
802
        import bzrlib.branch
 
803
        import bzrlib.smart.server
 
804
        self._preserved_hooks = {
 
805
            bzrlib.branch.Branch: bzrlib.branch.Branch.hooks,
 
806
            bzrlib.mutabletree.MutableTree: bzrlib.mutabletree.MutableTree.hooks,
 
807
            bzrlib.smart.server.SmartTCPServer: bzrlib.smart.server.SmartTCPServer.hooks,
 
808
            }
1141
809
        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
 
810
        # reset all hooks to an empty instance of the appropriate type
 
811
        bzrlib.branch.Branch.hooks = bzrlib.branch.BranchHooks()
 
812
        bzrlib.smart.server.SmartTCPServer.hooks = bzrlib.smart.server.SmartServerHooks()
1155
813
 
1156
814
    def _silenceUI(self):
1157
815
        """Turn off UI for duration of test"""
1158
816
        # 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.")
 
817
        saved = ui.ui_factory
 
818
        def _restore():
 
819
            ui.ui_factory = saved
 
820
        ui.ui_factory = ui.SilentUIFactory()
 
821
        self.addCleanup(_restore)
1342
822
 
1343
823
    def _ndiff_strings(self, a, b):
1344
824
        """Return ndiff between two strings containing lines.
1345
 
 
 
825
        
1346
826
        A trailing newline is added if missing to make the strings
1347
827
        print properly."""
1348
828
        if b and b[-1] != '\n':
1362
842
        except UnicodeError, e:
1363
843
            # If we can't compare without getting a UnicodeError, then
1364
844
            # obviously they are different
1365
 
            trace.mutter('UnicodeError: %s', e)
 
845
            mutter('UnicodeError: %s', e)
1366
846
        if message:
1367
847
            message += '\n'
1368
848
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1369
849
            % (message,
1370
 
               pprint.pformat(a), pprint.pformat(b)))
 
850
               pformat(a), pformat(b)))
1371
851
 
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
852
    assertEquals = assertEqual
1375
853
 
1376
854
    def assertEqualDiff(self, a, b, message=None):
1377
855
        """Assert two texts are equal, if not raise an exception.
1378
 
 
1379
 
        This is intended for use with multi-line strings where it can
 
856
        
 
857
        This is intended for use with multi-line strings where it can 
1380
858
        be hard to find the differences by eye.
1381
859
        """
1382
 
        # TODO: perhaps override assertEqual to call this for strings?
 
860
        # TODO: perhaps override assertEquals to call this for strings?
1383
861
        if a == b:
1384
862
            return
1385
863
        if message is None:
1386
864
            message = "texts not equal:\n"
 
865
        if a == b + '\n':
 
866
            message = 'first string is missing a final newline.\n'
1387
867
        if a + '\n' == b:
1388
 
            message = 'first string is missing a final newline.\n'
1389
 
        if a == b + '\n':
1390
868
            message = 'second string is missing a final newline.\n'
1391
869
        raise AssertionError(message +
1392
870
                             self._ndiff_strings(a, b))
1393
 
 
 
871
        
1394
872
    def assertEqualMode(self, mode, mode_test):
1395
873
        self.assertEqual(mode, mode_test,
1396
874
                         'mode mismatch %o != %o' % (mode, mode_test))
1397
875
 
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
876
    def assertPositive(self, val):
1453
877
        """Assert that val is greater than 0."""
1454
878
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
1466
890
        if not s.endswith(suffix):
1467
891
            raise AssertionError('string %r does not end with %r' % (s, suffix))
1468
892
 
1469
 
    def assertContainsRe(self, haystack, needle_re, flags=0):
 
893
    def assertContainsRe(self, haystack, needle_re):
1470
894
        """Assert that a contains something matching a regular expression."""
1471
 
        if not re.search(needle_re, haystack, flags):
 
895
        if not re.search(needle_re, haystack):
1472
896
            if '\n' in haystack or len(haystack) > 60:
1473
897
                # a long string, format it in a more readable way
1474
898
                raise AssertionError(
1478
902
                raise AssertionError('pattern "%s" not found in "%s"'
1479
903
                        % (needle_re, haystack))
1480
904
 
1481
 
    def assertNotContainsRe(self, haystack, needle_re, flags=0):
 
905
    def assertNotContainsRe(self, haystack, needle_re):
1482
906
        """Assert that a does not match a regular expression"""
1483
 
        if re.search(needle_re, haystack, flags):
 
907
        if re.search(needle_re, haystack):
1484
908
            raise AssertionError('pattern "%s" found in "%s"'
1485
909
                    % (needle_re, haystack))
1486
910
 
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
911
    def assertSubset(self, sublist, superlist):
1496
912
        """Assert that every entry in sublist is present in superlist."""
1497
913
        missing = set(sublist) - set(superlist)
1501
917
 
1502
918
    def assertListRaises(self, excClass, func, *args, **kwargs):
1503
919
        """Fail unless excClass is raised when the iterator from func is used.
1504
 
 
 
920
        
1505
921
        Many functions can return generators this makes sure
1506
922
        to wrap them in a list() call to make sure the whole generator
1507
923
        is run, and that the proper exception is raised.
1554
970
                raise AssertionError("%r is %r." % (left, right))
1555
971
 
1556
972
    def assertTransportMode(self, transport, path, mode):
1557
 
        """Fail if a path does not have mode "mode".
1558
 
 
 
973
        """Fail if a path does not have mode mode.
 
974
        
1559
975
        If modes are not supported on this transport, the assertion is ignored.
1560
976
        """
1561
977
        if not transport._can_roundtrip_unix_modebits():
1563
979
        path_stat = transport.stat(path)
1564
980
        actual_mode = stat.S_IMODE(path_stat.st_mode)
1565
981
        self.assertEqual(mode, actual_mode,
1566
 
                         'mode of %r incorrect (%s != %s)'
1567
 
                         % (path, oct(mode), oct(actual_mode)))
 
982
            'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
1568
983
 
1569
984
    def assertIsSameRealPath(self, path1, path2):
1570
985
        """Fail if path1 and path2 points to different files"""
1572
987
                         osutils.realpath(path2),
1573
988
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1574
989
 
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
 
        """
 
990
    def assertIsInstance(self, obj, kls):
 
991
        """Fail if obj is not an instance of kls"""
1580
992
        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)
 
993
            self.fail("%r is an instance of %s rather than %s" % (
 
994
                obj, obj.__class__, kls))
 
995
 
 
996
    def expectFailure(self, reason, assertion, *args, **kwargs):
 
997
        """Invoke a test, expecting it to fail for the given reason.
 
998
 
 
999
        This is for assertions that ought to succeed, but currently fail.
 
1000
        (The failure is *expected* but not *wanted*.)  Please be very precise
 
1001
        about the failure you're expecting.  If a new bug is introduced,
 
1002
        AssertionError should be raised, not KnownFailure.
 
1003
 
 
1004
        Frequently, expectFailure should be followed by an opposite assertion.
 
1005
        See example below.
 
1006
 
 
1007
        Intended to be used with a callable that raises AssertionError as the
 
1008
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
 
1009
 
 
1010
        Raises KnownFailure if the test fails.  Raises AssertionError if the
 
1011
        test succeeds.
 
1012
 
 
1013
        example usage::
 
1014
 
 
1015
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
 
1016
                             dynamic_val)
 
1017
          self.assertEqual(42, dynamic_val)
 
1018
 
 
1019
          This means that a dynamic_val of 54 will cause the test to raise
 
1020
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
 
1021
          only a dynamic_val of 42 will allow the test to pass.  Anything other
 
1022
          than 54 or 42 will cause an AssertionError.
 
1023
        """
 
1024
        try:
 
1025
            assertion(*args, **kwargs)
 
1026
        except AssertionError:
 
1027
            raise KnownFailure(reason)
 
1028
        else:
 
1029
            self.fail('Unexpected success.  Should have failed: %s' % reason)
1586
1030
 
1587
1031
    def assertFileEqual(self, content, path):
1588
1032
        """Fail if path does not contain 'content'."""
1589
 
        self.assertPathExists(path)
 
1033
        self.failUnlessExists(path)
1590
1034
        f = file(path, 'rb')
1591
1035
        try:
1592
1036
            s = f.read()
1594
1038
            f.close()
1595
1039
        self.assertEqualDiff(content, s)
1596
1040
 
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
1041
    def failUnlessExists(self, path):
1607
 
        return self.assertPathExists(path)
1608
 
 
1609
 
    def assertPathExists(self, path):
1610
1042
        """Fail unless path or paths, which may be abs or relative, exist."""
1611
1043
        if not isinstance(path, basestring):
1612
1044
            for p in path:
1613
 
                self.assertPathExists(p)
 
1045
                self.failUnlessExists(p)
1614
1046
        else:
1615
 
            self.assertTrue(osutils.lexists(path),
1616
 
                path + " does not exist")
 
1047
            self.failUnless(osutils.lexists(path),path+" does not exist")
1617
1048
 
1618
 
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1619
1049
    def failIfExists(self, path):
1620
 
        return self.assertPathDoesNotExist(path)
1621
 
 
1622
 
    def assertPathDoesNotExist(self, path):
1623
1050
        """Fail if path or paths, which may be abs or relative, exist."""
1624
1051
        if not isinstance(path, basestring):
1625
1052
            for p in path:
1626
 
                self.assertPathDoesNotExist(p)
 
1053
                self.failIfExists(p)
1627
1054
        else:
1628
 
            self.assertFalse(osutils.lexists(path),
1629
 
                path + " exists")
 
1055
            self.failIf(osutils.lexists(path),path+" exists")
1630
1056
 
1631
1057
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1632
1058
        """A helper for callDeprecated and applyDeprecated.
1658
1084
        not other callers that go direct to the warning module.
1659
1085
 
1660
1086
        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)::
 
1087
        this::
1663
1088
 
1664
1089
            self.assertRaises(errors.ReservedId,
1665
1090
                self.applyDeprecated,
1705
1130
        # warnings.  It's the easiest way to insulate ourselves from -Werror,
1706
1131
        # though.  -- Andrew, 20071062
1707
1132
        wlist = []
1708
 
        def _catcher(message, category, filename, lineno, file=None, line=None):
 
1133
        def _catcher(message, category, filename, lineno, file=None):
1709
1134
            # despite the name, 'message' is normally(?) a Warning subclass
1710
1135
            # instance
1711
1136
            wlist.append(message)
1723
1148
    def callDeprecated(self, expected, callable, *args, **kwargs):
1724
1149
        """Assert that a callable is deprecated in a particular way.
1725
1150
 
1726
 
        This is a very precise test for unusual requirements. The
 
1151
        This is a very precise test for unusual requirements. The 
1727
1152
        applyDeprecated helper function is probably more suited for most tests
1728
1153
        as it allows you to simply specify the deprecation format being used
1729
1154
        and will ensure that that is issued for the function being called.
1743
1168
        return result
1744
1169
 
1745
1170
    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)
 
1171
        """Send bzr and test log messages to a temporary file.
 
1172
 
 
1173
        The file is removed as the test is torn down.
 
1174
        """
 
1175
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
 
1176
        self._log_file = os.fdopen(fileno, 'w+')
 
1177
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
 
1178
        self._log_file_name = name
1756
1179
        self.addCleanup(self._finishLogFile)
1757
1180
 
1758
1181
    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
 
1182
        """Finished with the log file.
 
1183
 
 
1184
        Close the file and delete it, unless setKeepLogfile was called.
 
1185
        """
 
1186
        if self._log_file is None:
 
1187
            return
 
1188
        bzrlib.trace.pop_log_file(self._log_memento)
 
1189
        self._log_file.close()
 
1190
        self._log_file = None
 
1191
        if not self._keep_log_file:
 
1192
            os.remove(self._log_file_name)
 
1193
            self._log_file_name = None
 
1194
 
 
1195
    def setKeepLogfile(self):
 
1196
        """Make the logfile not be deleted when _finishLogFile is called."""
 
1197
        self._keep_log_file = True
 
1198
 
 
1199
    def addCleanup(self, callable, *args, **kwargs):
 
1200
        """Arrange to run a callable when this case is torn down.
 
1201
 
 
1202
        Callables are run in the reverse of the order they are registered, 
 
1203
        ie last-in first-out.
 
1204
        """
 
1205
        self._cleanups.append((callable, args, kwargs))
1841
1206
 
1842
1207
    def _cleanEnvironment(self):
1843
 
        for name, value in isolated_environ.iteritems():
1844
 
            self.overrideEnv(name, value)
 
1208
        new_env = {
 
1209
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
 
1210
            'HOME': os.getcwd(),
 
1211
            'APPDATA': None,  # bzr now use Win32 API and don't rely on APPDATA
 
1212
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
1213
            'BZR_EMAIL': None,
 
1214
            'BZREMAIL': None, # may still be present in the environment
 
1215
            'EMAIL': None,
 
1216
            'BZR_PROGRESS_BAR': None,
 
1217
            'BZR_LOG': None,
 
1218
            # SSH Agent
 
1219
            'SSH_AUTH_SOCK': None,
 
1220
            # Proxies
 
1221
            'http_proxy': None,
 
1222
            'HTTP_PROXY': None,
 
1223
            'https_proxy': None,
 
1224
            'HTTPS_PROXY': None,
 
1225
            'no_proxy': None,
 
1226
            'NO_PROXY': None,
 
1227
            'all_proxy': None,
 
1228
            'ALL_PROXY': None,
 
1229
            # Nobody cares about these ones AFAIK. So far at
 
1230
            # least. If you do (care), please update this comment
 
1231
            # -- vila 20061212
 
1232
            'ftp_proxy': None,
 
1233
            'FTP_PROXY': None,
 
1234
            'BZR_REMOTE_PATH': None,
 
1235
        }
 
1236
        self.__old_env = {}
 
1237
        self.addCleanup(self._restoreEnvironment)
 
1238
        for name, value in new_env.iteritems():
 
1239
            self._captureVar(name, value)
 
1240
 
 
1241
    def _captureVar(self, name, newvalue):
 
1242
        """Set an environment variable, and reset it when finished."""
 
1243
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
 
1244
 
 
1245
    def _restore_debug_flags(self):
 
1246
        debug.debug_flags.clear()
 
1247
        debug.debug_flags.update(self._preserved_debug_flags)
 
1248
 
 
1249
    def _restoreEnvironment(self):
 
1250
        for name, value in self.__old_env.iteritems():
 
1251
            osutils.set_or_unset_env(name, value)
1845
1252
 
1846
1253
    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()
 
1254
        for klass, hooks in self._preserved_hooks.items():
 
1255
            setattr(klass, 'hooks', hooks)
1852
1256
 
1853
1257
    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)
 
1258
        """This test has failed for some known reason."""
 
1259
        raise KnownFailure(reason)
 
1260
 
 
1261
    def run(self, result=None):
 
1262
        if result is None: result = self.defaultTestResult()
 
1263
        for feature in getattr(self, '_test_needs_features', []):
 
1264
            if not feature.available():
 
1265
                result.startTest(self)
 
1266
                if getattr(result, 'addNotSupported', None):
 
1267
                    result.addNotSupported(self, feature)
 
1268
                else:
 
1269
                    result.addSuccess(self)
 
1270
                result.stopTest(self)
 
1271
                return
1866
1272
        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)
 
1273
            return unittest.TestCase.run(self, result)
1877
1274
        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)
 
1275
            saved_attrs = {}
 
1276
            absent_attr = object()
 
1277
            for attr_name in self.attrs_to_keep:
 
1278
                attr = getattr(self, attr_name, absent_attr)
 
1279
                if attr is not absent_attr:
 
1280
                    saved_attrs[attr_name] = attr
 
1281
            self.__dict__ = saved_attrs
 
1282
 
 
1283
    def tearDown(self):
 
1284
        self._runCleanups()
 
1285
        unittest.TestCase.tearDown(self)
1944
1286
 
1945
1287
    def time(self, callable, *args, **kwargs):
1946
1288
        """Run callable and accrue the time it takes to the benchmark time.
1947
 
 
 
1289
        
1948
1290
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
1949
1291
        this will cause lsprofile statistics to be gathered and stored in
1950
1292
        self._benchcalls.
1951
1293
        """
1952
1294
        if self._benchtime is None:
1953
 
            self.addDetail('benchtime', content.Content(content.ContentType(
1954
 
                "text", "plain"), lambda:[str(self._benchtime)]))
1955
1295
            self._benchtime = 0
1956
1296
        start = time.time()
1957
1297
        try:
1966
1306
        finally:
1967
1307
            self._benchtime += time.time() - start
1968
1308
 
 
1309
    def _runCleanups(self):
 
1310
        """Run registered cleanup functions. 
 
1311
 
 
1312
        This should only be called from TestCase.tearDown.
 
1313
        """
 
1314
        # TODO: Perhaps this should keep running cleanups even if 
 
1315
        # one of them fails?
 
1316
 
 
1317
        # Actually pop the cleanups from the list so tearDown running
 
1318
        # twice is safe (this happens for skipped tests).
 
1319
        while self._cleanups:
 
1320
            cleanup, args, kwargs = self._cleanups.pop()
 
1321
            cleanup(*args, **kwargs)
 
1322
 
1969
1323
    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.
 
1324
        mutter(*args)
 
1325
 
 
1326
    def _get_log(self, keep_log_file=False):
 
1327
        """Get the log from bzrlib.trace calls from this test.
 
1328
 
 
1329
        :param keep_log_file: When True, if the log is still a file on disk
 
1330
            leave it as a file on disk. When False, if the log is still a file
 
1331
            on disk, the log file is deleted and the log preserved as
 
1332
            self._log_contents.
 
1333
        :return: A string containing the log.
1976
1334
        """
1977
 
        return u"".join(self.getDetails()['log'].iter_text())
 
1335
        # flush the log file, to get all content
 
1336
        import bzrlib.trace
 
1337
        bzrlib.trace._trace_file.flush()
 
1338
        if self._log_contents:
 
1339
            # XXX: this can hardly contain the content flushed above --vila
 
1340
            # 20080128
 
1341
            return self._log_contents
 
1342
        if self._log_file_name is not None:
 
1343
            logfile = open(self._log_file_name)
 
1344
            try:
 
1345
                log_contents = logfile.read()
 
1346
            finally:
 
1347
                logfile.close()
 
1348
            if not keep_log_file:
 
1349
                self._log_contents = log_contents
 
1350
                try:
 
1351
                    os.remove(self._log_file_name)
 
1352
                except OSError, e:
 
1353
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
 
1354
                        sys.stderr.write(('Unable to delete log file '
 
1355
                                             ' %r\n' % self._log_file_name))
 
1356
                    else:
 
1357
                        raise
 
1358
            return log_contents
 
1359
        else:
 
1360
            return "DELETED log file to reduce memory footprint"
1978
1361
 
1979
1362
    def requireFeature(self, feature):
1980
1363
        """This test requires a specific feature is available.
1997
1380
 
1998
1381
    def _run_bzr_core(self, args, retcode, encoding, stdin,
1999
1382
            working_dir):
2000
 
        # Clear chk_map page cache, because the contents are likely to mask
2001
 
        # locking errors.
2002
 
        chk_map.clear_cache()
2003
1383
        if encoding is None:
2004
 
            encoding = osutils.get_user_encoding()
 
1384
            encoding = bzrlib.user_encoding
2005
1385
        stdout = StringIOWrapper()
2006
1386
        stderr = StringIOWrapper()
2007
1387
        stdout.encoding = encoding
2009
1389
 
2010
1390
        self.log('run bzr: %r', args)
2011
1391
        # FIXME: don't call into logging here
2012
 
        handler = trace.EncodedStreamHandler(stderr, errors="replace",
2013
 
            level=logging.INFO)
 
1392
        handler = logging.StreamHandler(stderr)
 
1393
        handler.setLevel(logging.INFO)
2014
1394
        logger = logging.getLogger('')
2015
1395
        logger.addHandler(handler)
2016
1396
        old_ui_factory = ui.ui_factory
2022
1402
            os.chdir(working_dir)
2023
1403
 
2024
1404
        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)
 
1405
            result = self.apply_redirected(ui.ui_factory.stdin,
 
1406
                stdout, stderr,
 
1407
                bzrlib.commands.run_bzr_catch_user_errors,
 
1408
                args)
2042
1409
        finally:
2043
1410
            logger.removeHandler(handler)
2044
1411
            ui.ui_factory = old_ui_factory
2052
1419
        if err:
2053
1420
            self.log('errors:\n%r', err)
2054
1421
        if retcode is not None:
2055
 
            self.assertEqual(retcode, result,
 
1422
            self.assertEquals(retcode, result,
2056
1423
                              message='Unexpected return code')
2057
 
        return result, out, err
 
1424
        return out, err
2058
1425
 
2059
1426
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
2060
1427
                working_dir=None, error_regexes=[], output_encoding=None):
2065
1432
        passed in three ways:
2066
1433
 
2067
1434
        1- A list of strings, eg ["commit", "a"].  This is recommended
2068
 
        when the command contains whitespace or metacharacters, or
 
1435
        when the command contains whitespace or metacharacters, or 
2069
1436
        is built up at run time.
2070
1437
 
2071
 
        2- A single string, eg "add a".  This is the most convenient
 
1438
        2- A single string, eg "add a".  This is the most convenient 
2072
1439
        for hardcoded commands.
2073
1440
 
2074
1441
        This runs bzr through the interface that catches and reports
2089
1456
        :keyword error_regexes: A list of expected error messages.  If
2090
1457
            specified they must be seen in the error output of the command.
2091
1458
        """
2092
 
        retcode, out, err = self._run_bzr_autosplit(
 
1459
        out, err = self._run_bzr_autosplit(
2093
1460
            args=args,
2094
1461
            retcode=retcode,
2095
1462
            encoding=encoding,
2096
1463
            stdin=stdin,
2097
1464
            working_dir=working_dir,
2098
1465
            )
2099
 
        self.assertIsInstance(error_regexes, (list, tuple))
2100
1466
        for regex in error_regexes:
2101
1467
            self.assertContainsRe(err, regex)
2102
1468
        return out, err
2134
1500
    def run_bzr_subprocess(self, *args, **kwargs):
2135
1501
        """Run bzr in a subprocess for testing.
2136
1502
 
2137
 
        This starts a new Python interpreter and runs bzr in there.
 
1503
        This starts a new Python interpreter and runs bzr in there. 
2138
1504
        This should only be used for tests that have a justifiable need for
2139
1505
        this isolation: e.g. they are testing startup time, or signal
2140
 
        handling, or early startup code, etc.  Subprocess code can't be
 
1506
        handling, or early startup code, etc.  Subprocess code can't be 
2141
1507
        profiled or debugged so easily.
2142
1508
 
2143
1509
        :keyword retcode: The status code that is expected.  Defaults to 0.  If
2174
1540
    def start_bzr_subprocess(self, process_args, env_changes=None,
2175
1541
                             skip_if_plan_to_signal=False,
2176
1542
                             working_dir=None,
2177
 
                             allow_plugins=False, stderr=subprocess.PIPE):
 
1543
                             allow_plugins=False):
2178
1544
        """Start bzr in a subprocess for testing.
2179
1545
 
2180
1546
        This starts a new Python interpreter and runs bzr in there.
2189
1555
            variables. A value of None will unset the env variable.
2190
1556
            The values must be strings. The change will only occur in the
2191
1557
            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.
 
1558
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
 
1559
            is not available.
2194
1560
        :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
1561
 
2199
1562
        :returns: Popen object for the started process.
2200
1563
        """
2201
1564
        if skip_if_plan_to_signal:
2202
 
            if os.name != "posix":
2203
 
                raise TestSkipped("Sending signals not supported")
 
1565
            if not getattr(os, 'kill', None):
 
1566
                raise TestSkipped("os.kill not available.")
2204
1567
 
2205
1568
        if env_changes is None:
2206
1569
            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
1570
        old_env = {}
2213
1571
 
2214
1572
        def cleanup_environment():
2231
1589
            # so we will avoid using it on all platforms, just to
2232
1590
            # make sure the code path is used, and we don't break on win32
2233
1591
            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
1592
            command = [sys.executable]
2238
1593
            # frozen executables don't need the path to bzr
2239
1594
            if getattr(sys, "frozen", None) is None:
2241
1596
            if not allow_plugins:
2242
1597
                command.append('--no-plugins')
2243
1598
            command.extend(process_args)
2244
 
            process = self._popen(command, stdin=subprocess.PIPE,
2245
 
                                  stdout=subprocess.PIPE,
2246
 
                                  stderr=stderr)
 
1599
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
2247
1600
        finally:
2248
1601
            restore_environment()
2249
1602
            if cwd is not None:
2251
1604
 
2252
1605
        return process
2253
1606
 
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
1607
    def _popen(self, *args, **kwargs):
2282
1608
        """Place a call to Popen.
2283
1609
 
2284
1610
        Allows tests to override this method to intercept the calls made to
2285
1611
        Popen for introspection.
2286
1612
        """
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__))
 
1613
        return Popen(*args, **kwargs)
2292
1614
 
2293
1615
    def get_bzr_path(self):
2294
1616
        """Return the path of the 'bzr' executable for this test suite."""
2295
 
        bzr_path = os.path.join(self.get_source_path(), "bzr")
 
1617
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
2296
1618
        if not os.path.isfile(bzr_path):
2297
1619
            # We are probably installed. Assume sys.argv is the right file
2298
1620
            bzr_path = sys.argv[0]
2320
1642
        if retcode is not None and retcode != process.returncode:
2321
1643
            if process_args is None:
2322
1644
                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)
 
1645
            mutter('Output of bzr %s:\n%s', process_args, out)
 
1646
            mutter('Error for bzr %s:\n%s', process_args, err)
2325
1647
            self.fail('Command bzr %s failed with retcode %s != %s'
2326
1648
                      % (process_args, retcode, process.returncode))
2327
1649
        return [out, err]
2328
1650
 
2329
 
    def check_tree_shape(self, tree, shape):
2330
 
        """Compare a tree to a list of expected names.
 
1651
    def check_inventory_shape(self, inv, shape):
 
1652
        """Compare an inventory to a list of expected names.
2331
1653
 
2332
1654
        Fail if they are not precisely equal.
2333
1655
        """
2334
1656
        extras = []
2335
1657
        shape = list(shape)             # copy
2336
 
        for path, ie in tree.iter_entries_by_dir():
 
1658
        for path, ie in inv.entries():
2337
1659
            name = path.replace('\\', '/')
2338
1660
            if ie.kind == 'directory':
2339
1661
                name = name + '/'
2340
 
            if name == "/":
2341
 
                pass # ignore root entry
2342
 
            elif name in shape:
 
1662
            if name in shape:
2343
1663
                shape.remove(name)
2344
1664
            else:
2345
1665
                extras.append(name)
2386
1706
 
2387
1707
        Tests that expect to provoke LockContention errors should call this.
2388
1708
        """
2389
 
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
1709
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
 
1710
        def resetTimeout():
 
1711
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
 
1712
        self.addCleanup(resetTimeout)
 
1713
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
2390
1714
 
2391
1715
    def make_utf8_encoded_stringio(self, encoding_type=None):
2392
1716
        """Return a StringIOWrapper instance, that will encode Unicode
2400
1724
        sio.encoding = output_encoding
2401
1725
        return sio
2402
1726
 
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
1727
 
2437
1728
class TestCaseWithMemoryTransport(TestCase):
2438
1729
    """Common test class for tests that do not need disk resources.
2439
1730
 
2440
 
    Tests that need disk resources should derive from TestCaseInTempDir
2441
 
    orTestCaseWithTransport.
 
1731
    Tests that need disk resources should derive from TestCaseWithTransport.
2442
1732
 
2443
1733
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2444
1734
 
2445
 
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
 
1735
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
2446
1736
    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
 
1737
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
 
1738
    must exist. However, TestCaseWithMemoryTransport does not offer local
 
1739
    file defaults for the transport in tests, nor does it obey the command line
2450
1740
    override, so tests that accidentally write to the common directory should
2451
1741
    be rare.
2452
1742
 
2453
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
2454
 
        ``.bzr`` directory that stops us ascending higher into the filesystem.
 
1743
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
 
1744
    a .bzr directory that stops us ascending higher into the filesystem.
2455
1745
    """
2456
1746
 
2457
1747
    TEST_ROOT = None
2459
1749
 
2460
1750
    def __init__(self, methodName='runTest'):
2461
1751
        # allow test parameterization after test construction and before test
2462
 
        # execution. Variables that the parameterizer sets need to be
 
1752
        # execution. Variables that the parameterizer sets need to be 
2463
1753
        # ones that are not set by setUp, or setUp will trash them.
2464
1754
        super(TestCaseWithMemoryTransport, self).__init__(methodName)
2465
1755
        self.vfs_transport_factory = default_transport
2467
1757
        self.transport_readonly_server = None
2468
1758
        self.__vfs_server = None
2469
1759
 
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
1760
    def get_transport(self, relpath=None):
2499
1761
        """Return a writeable transport.
2500
1762
 
2501
1763
        This transport is for the test scratch space relative to
2502
1764
        "self._test_root"
2503
 
 
 
1765
        
2504
1766
        :param relpath: a path relative to the base url.
2505
1767
        """
2506
 
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
 
1768
        t = get_transport(self.get_url(relpath))
2507
1769
        self.assertFalse(t.is_readonly())
2508
1770
        return t
2509
1771
 
2510
1772
    def get_readonly_transport(self, relpath=None):
2511
1773
        """Return a readonly transport for the test scratch space
2512
 
 
 
1774
        
2513
1775
        This can be used to test that operations which should only need
2514
1776
        readonly access in fact do not try to write.
2515
1777
 
2516
1778
        :param relpath: a path relative to the base url.
2517
1779
        """
2518
 
        t = _mod_transport.get_transport_from_url(
2519
 
            self.get_readonly_url(relpath))
 
1780
        t = get_transport(self.get_readonly_url(relpath))
2520
1781
        self.assertTrue(t.is_readonly())
2521
1782
        return t
2522
1783
 
2535
1796
        if self.__readonly_server is None:
2536
1797
            if self.transport_readonly_server is None:
2537
1798
                # readonly decorator requested
2538
 
                self.__readonly_server = test_server.ReadonlyServer()
 
1799
                # bring up the server
 
1800
                self.__readonly_server = ReadonlyServer()
 
1801
                self.__readonly_server.setUp(self.get_vfs_only_server())
2539
1802
            else:
2540
 
                # explicit readonly transport.
2541
1803
                self.__readonly_server = self.create_transport_readonly_server()
2542
 
            self.start_server(self.__readonly_server,
2543
 
                self.get_vfs_only_server())
 
1804
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
1805
            self.addCleanup(self.__readonly_server.tearDown)
2544
1806
        return self.__readonly_server
2545
1807
 
2546
1808
    def get_readonly_url(self, relpath=None):
2547
1809
        """Get a URL for the readonly transport.
2548
1810
 
2549
 
        This will either be backed by '.' or a decorator to the transport
 
1811
        This will either be backed by '.' or a decorator to the transport 
2550
1812
        used by self.get_url()
2551
1813
        relpath provides for clients to get a path relative to the base url.
2552
1814
        These should only be downwards relative, not upwards.
2564
1826
        is no means to override it.
2565
1827
        """
2566
1828
        if self.__vfs_server is None:
2567
 
            self.__vfs_server = memory.MemoryServer()
2568
 
            self.start_server(self.__vfs_server)
 
1829
            self.__vfs_server = MemoryServer()
 
1830
            self.__vfs_server.setUp()
 
1831
            self.addCleanup(self.__vfs_server.tearDown)
2569
1832
        return self.__vfs_server
2570
1833
 
2571
1834
    def get_server(self):
2578
1841
        then the self.get_vfs_server is returned.
2579
1842
        """
2580
1843
        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()
 
1844
            if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
 
1845
                return self.get_vfs_only_server()
2584
1846
            else:
2585
1847
                # bring up a decorated means of access to the vfs only server.
2586
1848
                self.__server = self.transport_server()
2587
 
                self.start_server(self.__server, self.get_vfs_only_server())
 
1849
                try:
 
1850
                    self.__server.setUp(self.get_vfs_only_server())
 
1851
                except TypeError, e:
 
1852
                    # This should never happen; the try:Except here is to assist
 
1853
                    # developers having to update code rather than seeing an
 
1854
                    # uninformative TypeError.
 
1855
                    raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
 
1856
            self.addCleanup(self.__server.tearDown)
2588
1857
        return self.__server
2589
1858
 
2590
1859
    def _adjust_url(self, base, relpath):
2643
1912
        real branch.
2644
1913
        """
2645
1914
        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'))
 
1915
        bzrdir.BzrDir.create_standalone_workingtree(root)
2660
1916
 
2661
1917
    def _check_safety_net(self):
2662
1918
        """Check that the safety .bzr directory have not been touched.
2665
1921
        propagating. This method ensures than a test did not leaked.
2666
1922
        """
2667
1923
        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):
 
1924
        wt = workingtree.WorkingTree.open(root)
 
1925
        last_rev = wt.last_revision()
 
1926
        if last_rev != 'null:':
2672
1927
            # The current test have modified the /bzr directory, we need to
2673
1928
            # recreate a new one or all the followng tests will fail.
2674
1929
            # If you need to inspect its content uncomment the following line
2675
1930
            # import pdb; pdb.set_trace()
2676
 
            _rmtree_temp_dir(root + '/.bzr', test_id=self.id())
 
1931
            _rmtree_temp_dir(root + '/.bzr')
2677
1932
            self._create_safety_net()
2678
1933
            raise AssertionError('%s/.bzr should not be modified' % root)
2679
1934
 
2680
1935
    def _make_test_root(self):
2681
1936
        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'))
 
1937
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
2685
1938
            TestCaseWithMemoryTransport.TEST_ROOT = root
2686
1939
 
2687
1940
            self._create_safety_net()
2690
1943
            # specifically told when all tests are finished.  This will do.
2691
1944
            atexit.register(_rmtree_temp_dir, root)
2692
1945
 
2693
 
        self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
2694
1946
        self.addCleanup(self._check_safety_net)
2695
1947
 
2696
1948
    def makeAndChdirToTestDir(self):
2697
1949
        """Create a temporary directories for this one test.
2698
 
 
 
1950
        
2699
1951
        This must set self.test_home_dir and self.test_dir and chdir to
2700
1952
        self.test_dir.
2701
 
 
 
1953
        
2702
1954
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
2703
1955
        """
2704
1956
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2705
1957
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2706
1958
        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):
 
1959
        
 
1960
    def make_branch(self, relpath, format=None):
2710
1961
        """Create a branch on the transport at relpath."""
2711
1962
        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
 
1963
        return repo.bzrdir.create_branch()
2733
1964
 
2734
1965
    def make_bzrdir(self, relpath, format=None):
2735
1966
        try:
2736
1967
            # might be a relative or absolute path
2737
1968
            maybe_a_url = self.get_url(relpath)
2738
1969
            segments = maybe_a_url.rsplit('/', 1)
2739
 
            t = _mod_transport.get_transport(maybe_a_url)
 
1970
            t = get_transport(maybe_a_url)
2740
1971
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2741
1972
                t.ensure_base()
2742
 
            format = self.resolve_format(format)
 
1973
            if format is None:
 
1974
                format = 'default'
 
1975
            if isinstance(format, basestring):
 
1976
                format = bzrdir.format_registry.make_bzrdir(format)
2743
1977
            return format.initialize_on_transport(t)
2744
1978
        except errors.UninitializableFormat:
2745
1979
            raise TestSkipped("Format %s is not initializable." % format)
2746
1980
 
2747
 
    def make_repository(self, relpath, shared=None, format=None):
 
1981
    def make_repository(self, relpath, shared=False, format=None):
2748
1982
        """Create a repository on our default transport at relpath.
2749
 
 
 
1983
        
2750
1984
        Note that relpath must be a relative path, not a full url.
2751
1985
        """
2752
1986
        # FIXME: If you create a remoterepository this returns the underlying
2753
 
        # real format, which is incorrect.  Actually we should make sure that
 
1987
        # real format, which is incorrect.  Actually we should make sure that 
2754
1988
        # RemoteBzrDir returns a RemoteRepository.
2755
1989
        # maybe  mbp 20070410
2756
1990
        made_control = self.make_bzrdir(relpath, format=format)
2757
1991
        return made_control.create_repository(shared=shared)
2758
1992
 
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
1993
    def make_branch_and_memory_tree(self, relpath, format=None):
2769
1994
        """Create a branch on the default transport and a MemoryTree for it."""
2770
1995
        b = self.make_branch(relpath, format=format)
2771
1996
        return memorytree.MemoryTree.create_on_branch(b)
2772
1997
 
2773
1998
    def make_branch_builder(self, relpath, format=None):
2774
 
        branch = self.make_branch(relpath, format=format)
2775
 
        return branchbuilder.BranchBuilder(branch=branch)
 
1999
        url = self.get_url(relpath)
 
2000
        tran = get_transport(url)
 
2001
        return branchbuilder.BranchBuilder(get_transport(url), format=format)
2776
2002
 
2777
2003
    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
 
 
 
2004
        os.environ['HOME'] = self.test_home_dir
 
2005
        os.environ['BZR_HOME'] = self.test_home_dir
 
2006
        
 
2007
    def setUp(self):
 
2008
        super(TestCaseWithMemoryTransport, self).setUp()
 
2009
        self._make_test_root()
 
2010
        _currentdir = os.getcwdu()
 
2011
        def _leaveDirectory():
 
2012
            os.chdir(_currentdir)
 
2013
        self.addCleanup(_leaveDirectory)
 
2014
        self.makeAndChdirToTestDir()
 
2015
        self.overrideEnvironmentForTesting()
 
2016
        self.__readonly_server = None
 
2017
        self.__server = None
 
2018
        self.reduceLockdirTimeout()
 
2019
 
 
2020
     
2808
2021
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2809
2022
    """Derived class that runs a test within a temporary directory.
2810
2023
 
2815
2028
    All test cases create their own directory within that.  If the
2816
2029
    tests complete successfully, the directory is removed.
2817
2030
 
2818
 
    :ivar test_base_dir: The path of the top-level directory for this
 
2031
    :ivar test_base_dir: The path of the top-level directory for this 
2819
2032
    test, which contains a home directory and a work directory.
2820
2033
 
2821
2034
    :ivar test_home_dir: An initially empty directory under test_base_dir
2827
2040
 
2828
2041
    OVERRIDE_PYTHON = 'python'
2829
2042
 
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
2043
    def check_file_contents(self, filename, expect):
2837
2044
        self.log("check contents of file %s" % filename)
2838
 
        f = file(filename)
2839
 
        try:
2840
 
            contents = f.read()
2841
 
        finally:
2842
 
            f.close()
 
2045
        contents = file(filename, 'r').read()
2843
2046
        if contents != expect:
2844
2047
            self.log("expected: %r" % expect)
2845
2048
            self.log("actually: %r" % contents)
2847
2050
 
2848
2051
    def _getTestDirPrefix(self):
2849
2052
        # create a directory within the top level test directory
2850
 
        if sys.platform in ('win32', 'cygwin'):
 
2053
        if sys.platform == 'win32':
2851
2054
            name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2852
2055
            # windows is likely to have path-length limits so use a short name
2853
2056
            name_prefix = name_prefix[-30:]
2857
2060
 
2858
2061
    def makeAndChdirToTestDir(self):
2859
2062
        """See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
2860
 
 
 
2063
        
2861
2064
        For TestCaseInTempDir we create a temporary directory based on the test
2862
2065
        name and then create two subdirs - test and home under it.
2863
2066
        """
2864
 
        name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
2865
 
            self._getTestDirPrefix())
 
2067
        name_prefix = os.path.join(self.TEST_ROOT, self._getTestDirPrefix())
2866
2068
        name = name_prefix
2867
2069
        for i in range(100):
2868
2070
            if os.path.exists(name):
2869
2071
                name = name_prefix + '_' + str(i)
2870
2072
            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)
 
2073
                os.mkdir(name)
2875
2074
                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()
 
2075
        # now create test and home directories within this dir
 
2076
        self.test_base_dir = name
2883
2077
        self.test_home_dir = self.test_base_dir + '/home'
2884
2078
        os.mkdir(self.test_home_dir)
2885
2079
        self.test_dir = self.test_base_dir + '/work'
2891
2085
            f.write(self.id())
2892
2086
        finally:
2893
2087
            f.close()
 
2088
        self.addCleanup(self.deleteTestDir)
2894
2089
 
2895
2090
    def deleteTestDir(self):
2896
 
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2897
 
        _rmtree_temp_dir(self.test_base_dir, test_id=self.id())
 
2091
        os.chdir(self.TEST_ROOT)
 
2092
        _rmtree_temp_dir(self.test_base_dir)
2898
2093
 
2899
2094
    def build_tree(self, shape, line_endings='binary', transport=None):
2900
2095
        """Build a test tree according to a pattern.
2919
2114
                "a list or a tuple. Got %r instead" % (shape,))
2920
2115
        # It's OK to just create them using forward slashes on windows.
2921
2116
        if transport is None or transport.is_readonly():
2922
 
            transport = _mod_transport.get_transport_from_path(".")
 
2117
            transport = get_transport(".")
2923
2118
        for name in shape:
2924
 
            self.assertIsInstance(name, basestring)
 
2119
            self.assert_(isinstance(name, basestring))
2925
2120
            if name[-1] == '/':
2926
2121
                transport.mkdir(urlutils.escape(name[:-1]))
2927
2122
            else:
2935
2130
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2936
2131
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2937
2132
 
2938
 
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
 
2133
    def build_tree_contents(self, shape):
 
2134
        build_tree_contents(shape)
2939
2135
 
2940
2136
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2941
2137
        """Assert whether path or paths are in the WorkingTree"""
2969
2165
    ReadonlyTransportDecorator is used instead which allows the use of non disk
2970
2166
    based read write transports.
2971
2167
 
2972
 
    If an explicit class is provided for readonly access, that server and the
 
2168
    If an explicit class is provided for readonly access, that server and the 
2973
2169
    readwrite one must both define get_url() as resolving to os.getcwd().
2974
2170
    """
2975
2171
 
2976
 
    def setUp(self):
2977
 
        super(TestCaseWithTransport, self).setUp()
2978
 
        self.__vfs_server = None
2979
 
 
2980
2172
    def get_vfs_only_server(self):
2981
2173
        """See TestCaseWithMemoryTransport.
2982
2174
 
2985
2177
        """
2986
2178
        if self.__vfs_server is None:
2987
2179
            self.__vfs_server = self.vfs_transport_factory()
2988
 
            self.start_server(self.__vfs_server)
 
2180
            self.__vfs_server.setUp()
 
2181
            self.addCleanup(self.__vfs_server.tearDown)
2989
2182
        return self.__vfs_server
2990
2183
 
2991
2184
    def make_branch_and_tree(self, relpath, format=None):
2998
2191
        repository will also be accessed locally. Otherwise a lightweight
2999
2192
        checkout is created and returned.
3000
2193
 
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
2194
        :param format: The BzrDirFormat.
3011
2195
        :returns: the WorkingTree.
3012
2196
        """
3014
2198
        # this obviously requires a format that supports branch references
3015
2199
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
3016
2200
        # 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
2201
        b = self.make_branch(relpath, format=format)
3022
2202
        try:
3023
2203
            return b.bzrdir.create_workingtree()
3025
2205
            # We can only make working trees locally at the moment.  If the
3026
2206
            # transport can't support them, then we keep the non-disk-backed
3027
2207
            # branch and create a local checkout.
3028
 
            if self.vfs_transport_factory is test_server.LocalURLServer:
 
2208
            if self.vfs_transport_factory is LocalURLServer:
3029
2209
                # the branch is colocated on disk, we cannot create a checkout.
3030
2210
                # hopefully callers will expect this.
3031
 
                local_controldir = controldir.ControlDir.open(
3032
 
                    self.get_vfs_only_url(relpath))
 
2211
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
3033
2212
                wt = local_controldir.create_workingtree()
3034
2213
                if wt.branch._format != b._format:
3035
2214
                    wt._branch = b
3065
2244
        self.assertFalse(differences.has_changed(),
3066
2245
            "Trees %r and %r are different: %r" % (left, right, differences))
3067
2246
 
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)
 
2247
    def setUp(self):
 
2248
        super(TestCaseWithTransport, self).setUp()
 
2249
        self.__vfs_server = None
3075
2250
 
3076
2251
 
3077
2252
class ChrootedTestCase(TestCaseWithTransport):
3082
2257
    for readonly urls.
3083
2258
 
3084
2259
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
3085
 
                       be used without needed to redo it when a different
 
2260
                       be used without needed to redo it when a different 
3086
2261
                       subclass is in use ?
3087
2262
    """
3088
2263
 
3089
2264
    def setUp(self):
3090
 
        from bzrlib.tests import http_server
3091
2265
        super(ChrootedTestCase, self).setUp()
3092
 
        if not self.vfs_transport_factory == memory.MemoryServer:
3093
 
            self.transport_readonly_server = http_server.HttpServer
 
2266
        if not self.vfs_transport_factory == MemoryServer:
 
2267
            self.transport_readonly_server = HttpServer
3094
2268
 
3095
2269
 
3096
2270
def condition_id_re(pattern):
3097
2271
    """Create a condition filter which performs a re check on a test's id.
3098
 
 
 
2272
    
3099
2273
    :param pattern: A regular expression string.
3100
2274
    :return: A callable that returns True if the re matches.
3101
2275
    """
3102
 
    filter_re = re.compile(pattern, 0)
 
2276
    filter_re = re.compile(pattern)
3103
2277
    def condition(test):
3104
2278
        test_id = test.id()
3105
2279
        return filter_re.search(test_id)
3108
2282
 
3109
2283
def condition_isinstance(klass_or_klass_list):
3110
2284
    """Create a condition filter which returns isinstance(param, klass).
3111
 
 
 
2285
    
3112
2286
    :return: A callable which when called with one parameter obj return the
3113
2287
        result of isinstance(obj, klass_or_klass_list).
3114
2288
    """
3119
2293
 
3120
2294
def condition_id_in_list(id_list):
3121
2295
    """Create a condition filter which verify that test's id in a list.
3122
 
 
 
2296
    
3123
2297
    :param id_list: A TestIdList object.
3124
2298
    :return: A callable that returns True if the test's id appears in the list.
3125
2299
    """
3128
2302
    return condition
3129
2303
 
3130
2304
 
3131
 
def condition_id_startswith(starts):
 
2305
def condition_id_startswith(start):
3132
2306
    """Create a condition filter verifying that test's id starts with a string.
3133
 
 
3134
 
    :param starts: A list of string.
3135
 
    :return: A callable that returns True if the test's id starts with one of
3136
 
        the given strings.
 
2307
    
 
2308
    :param start: A string.
 
2309
    :return: A callable that returns True if the test's id starts with the
 
2310
        given string.
3137
2311
    """
3138
2312
    def condition(test):
3139
 
        for start in starts:
3140
 
            if test.id().startswith(start):
3141
 
                return True
3142
 
        return False
 
2313
        return test.id().startswith(start)
3143
2314
    return condition
3144
2315
 
3145
2316
 
3161
2332
 
3162
2333
def filter_suite_by_condition(suite, condition):
3163
2334
    """Create a test suite by filtering another one.
3164
 
 
 
2335
    
3165
2336
    :param suite: The source suite.
3166
2337
    :param condition: A callable whose result evaluates True when called with a
3167
2338
        test case which should be included in the result.
3168
2339
    :return: A suite which contains the tests found in suite that pass
3169
2340
        condition.
3170
 
    """
 
2341
    """ 
3171
2342
    result = []
3172
2343
    for test in iter_suite_tests(suite):
3173
2344
        if condition(test):
3177
2348
 
3178
2349
def filter_suite_by_re(suite, pattern):
3179
2350
    """Create a test suite by filtering another one.
3180
 
 
 
2351
    
3181
2352
    :param suite:           the source suite
3182
2353
    :param pattern:         pattern that names must match
3183
2354
    :returns: the newly created suite
3184
 
    """
 
2355
    """ 
3185
2356
    condition = condition_id_re(pattern)
3186
2357
    result_suite = filter_suite_by_condition(suite, condition)
3187
2358
    return result_suite
3203
2374
    """Create a test suite by filtering another one.
3204
2375
 
3205
2376
    :param suite: The source suite.
3206
 
    :param start: A list of string the test id must start with one of.
 
2377
    :param start: A string the test id must start with.
3207
2378
    :returns: the newly created suite
3208
2379
    """
3209
2380
    condition = condition_id_startswith(start)
3235
2406
 
3236
2407
def randomize_suite(suite):
3237
2408
    """Return a new TestSuite with suite's tests in random order.
3238
 
 
 
2409
    
3239
2410
    The tests in the input suite are flattened into a single suite in order to
3240
2411
    accomplish this. Any nested TestSuites are removed to provide global
3241
2412
    randomness.
3247
2418
 
3248
2419
def split_suite_by_condition(suite, condition):
3249
2420
    """Split a test suite into two by a condition.
3250
 
 
 
2421
    
3251
2422
    :param suite: The suite to split.
3252
2423
    :param condition: The condition to match on. Tests that match this
3253
2424
        condition are returned in the first test suite, ones that do not match
3256
2427
        suite matching the condition, and the second contains the remainder
3257
2428
        from suite. The order within each output suite is the same as it was in
3258
2429
        suite.
3259
 
    """
 
2430
    """ 
3260
2431
    matched = []
3261
2432
    did_not_match = []
3262
2433
    for test in iter_suite_tests(suite):
3269
2440
 
3270
2441
def split_suite_by_re(suite, pattern):
3271
2442
    """Split a test suite into two by a regular expression.
3272
 
 
 
2443
    
3273
2444
    :param suite: The suite to split.
3274
2445
    :param pattern: A regular expression string. Test ids that match this
3275
2446
        pattern will be in the first test suite returned, and the others in the
3278
2449
        suite matching pattern, and the second contains the remainder from
3279
2450
        suite. The order within each output suite is the same as it was in
3280
2451
        suite.
3281
 
    """
 
2452
    """ 
3282
2453
    return split_suite_by_condition(suite, condition_id_re(pattern))
3283
2454
 
3284
2455
 
3289
2460
              list_only=False,
3290
2461
              random_seed=None,
3291
2462
              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
 
    """
 
2463
              strict=False):
3305
2464
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
3306
2465
    if verbose:
3307
2466
        verbosity = 2
3308
2467
    else:
3309
2468
        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,
 
2469
    runner = TextTestRunner(stream=sys.stdout,
3315
2470
                            descriptions=0,
3316
2471
                            verbosity=verbosity,
3317
2472
                            bench_history=bench_history,
3318
 
                            strict=strict,
3319
 
                            result_decorators=result_decorators,
 
2473
                            list_only=list_only,
3320
2474
                            )
3321
2475
    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))
 
2476
    # Initialise the random number generator and display the seed used.
 
2477
    # We convert the seed to a long to make it reuseable across invocations.
 
2478
    random_order = False
 
2479
    if random_seed is not None:
 
2480
        random_order = True
 
2481
        if random_seed == "now":
 
2482
            random_seed = long(time.time())
 
2483
        else:
 
2484
            # Convert the seed to a long if we can
 
2485
            try:
 
2486
                random_seed = long(random_seed)
 
2487
            except:
 
2488
                pass
 
2489
        runner.stream.writeln("Randomizing test order using seed %s\n" %
 
2490
            (random_seed))
 
2491
        random.seed(random_seed)
 
2492
    # Customise the list of tests if requested
 
2493
    if exclude_pattern is not None:
 
2494
        suite = exclude_tests_by_re(suite, exclude_pattern)
 
2495
    if random_order:
 
2496
        order_changer = randomize_suite
3332
2497
    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
 
2498
        order_changer = preserve_input
 
2499
    if pattern != '.*' or random_order:
 
2500
        if matching_tests_first:
 
2501
            suites = map(order_changer, split_suite_by_re(suite, pattern))
 
2502
            suite = TestUtil.TestSuite(suites)
 
2503
        else:
 
2504
            suite = order_changer(filter_suite_by_re(suite, pattern))
 
2505
 
3351
2506
    result = runner.run(suite)
 
2507
 
3352
2508
    if strict:
3353
2509
        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
 
2510
 
 
2511
    return result.wasSuccessful()
3683
2512
 
3684
2513
 
3685
2514
# 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
2515
selftest_debug_flags = set()
3699
2516
 
3700
2517
 
3711
2528
             load_list=None,
3712
2529
             debug_flags=None,
3713
2530
             starting_with=None,
3714
 
             runner_class=None,
3715
 
             suite_decorators=None,
3716
 
             stream=None,
3717
 
             lsprof_tests=False,
3718
2531
             ):
3719
2532
    """Run the whole test suite under the enhanced runner"""
3720
2533
    # XXX: Very ugly way to do this...
3737
2550
            keep_only = None
3738
2551
        else:
3739
2552
            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
2553
        if test_suite_factory is None:
3744
 
            # Reduce loading time by loading modules based on the starting_with
3745
 
            # patterns.
3746
2554
            suite = test_suite(keep_only, starting_with)
3747
2555
        else:
3748
2556
            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
2557
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3756
2558
                     stop_on_failure=stop_on_failure,
3757
2559
                     transport=transport,
3761
2563
                     list_only=list_only,
3762
2564
                     random_seed=random_seed,
3763
2565
                     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
 
                     )
 
2566
                     strict=strict)
3770
2567
    finally:
3771
2568
        default_transport = old_transport
3772
2569
        selftest_debug_flags = old_debug_flags
3799
2596
    """Warns about tests not appearing or appearing more than once.
3800
2597
 
3801
2598
    :param test_suite: A TestSuite object.
3802
 
    :param test_id_list: The list of test ids that should be found in
 
2599
    :param test_id_list: The list of test ids that should be found in 
3803
2600
         test_suite.
3804
2601
 
3805
2602
    :return: (absents, duplicates) absents is a list containing the test found
3806
2603
        in id_list but not in test_suite, duplicates is a list containing the
3807
 
        tests found multiple times in test_suite.
 
2604
        test found multiple times in test_suite.
3808
2605
 
3809
2606
    When using a prefined test id list, it may occurs that some tests do not
3810
2607
    exist anymore or that some tests use the same id. This function warns the
3874
2671
        return self.tests.has_key(test_id)
3875
2672
 
3876
2673
 
3877
 
class TestPrefixAliasRegistry(registry.Registry):
3878
 
    """A registry for test prefix aliases.
3879
 
 
3880
 
    This helps implement shorcuts for the --starting-with selftest
3881
 
    option. Overriding existing prefixes is not allowed but not fatal (a
3882
 
    warning will be emitted).
3883
 
    """
3884
 
 
3885
 
    def register(self, key, obj, help=None, info=None,
3886
 
                 override_existing=False):
3887
 
        """See Registry.register.
3888
 
 
3889
 
        Trying to override an existing alias causes a warning to be emitted,
3890
 
        not a fatal execption.
3891
 
        """
3892
 
        try:
3893
 
            super(TestPrefixAliasRegistry, self).register(
3894
 
                key, obj, help=help, info=info, override_existing=False)
3895
 
        except KeyError:
3896
 
            actual = self.get(key)
3897
 
            trace.note(
3898
 
                'Test prefix alias %s is already used for %s, ignoring %s'
3899
 
                % (key, actual, obj))
3900
 
 
3901
 
    def resolve_alias(self, id_start):
3902
 
        """Replace the alias by the prefix in the given string.
3903
 
 
3904
 
        Using an unknown prefix is an error to help catching typos.
3905
 
        """
3906
 
        parts = id_start.split('.')
3907
 
        try:
3908
 
            parts[0] = self.get(parts[0])
3909
 
        except KeyError:
3910
 
            raise errors.BzrCommandError(
3911
 
                '%s is not a known test prefix alias' % parts[0])
3912
 
        return '.'.join(parts)
3913
 
 
3914
 
 
3915
 
test_prefix_alias_registry = TestPrefixAliasRegistry()
3916
 
"""Registry of test prefix aliases."""
3917
 
 
3918
 
 
3919
 
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
3920
 
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3921
 
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3922
 
 
3923
 
# Obvious highest levels prefixes, feel free to add your own via a plugin
3924
 
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3925
 
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3926
 
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3927
 
test_prefix_alias_registry.register('bb', 'bzrlib.tests.blackbox')
3928
 
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3929
 
 
3930
 
 
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
2674
def test_suite(keep_only=None, starting_with=None):
4171
2675
    """Build and return TestSuite for the whole of bzrlib.
4172
2676
 
4178
2682
    This function can be replaced if you need to change the default test
4179
2683
    suite on a global basis, but it is not encouraged.
4180
2684
    """
 
2685
    testmod_names = [
 
2686
                   'bzrlib.doc',
 
2687
                   'bzrlib.util.tests.test_bencode',
 
2688
                   'bzrlib.tests.blackbox',
 
2689
                   'bzrlib.tests.branch_implementations',
 
2690
                   'bzrlib.tests.bzrdir_implementations',
 
2691
                   'bzrlib.tests.commands',
 
2692
                   'bzrlib.tests.inventory_implementations',
 
2693
                   'bzrlib.tests.interrepository_implementations',
 
2694
                   'bzrlib.tests.intertree_implementations',
 
2695
                   'bzrlib.tests.per_lock',
 
2696
                   'bzrlib.tests.repository_implementations',
 
2697
                   'bzrlib.tests.test__dirstate_helpers',
 
2698
                   'bzrlib.tests.test_ancestry',
 
2699
                   'bzrlib.tests.test_annotate',
 
2700
                   'bzrlib.tests.test_api',
 
2701
                   'bzrlib.tests.test_atomicfile',
 
2702
                   'bzrlib.tests.test_bad_files',
 
2703
                   'bzrlib.tests.test_bisect_multi',
 
2704
                   'bzrlib.tests.test_branch',
 
2705
                   'bzrlib.tests.test_branchbuilder',
 
2706
                   'bzrlib.tests.test_bugtracker',
 
2707
                   'bzrlib.tests.test_bundle',
 
2708
                   'bzrlib.tests.test_bzrdir',
 
2709
                   'bzrlib.tests.test_cache_utf8',
 
2710
                   'bzrlib.tests.test_commands',
 
2711
                   'bzrlib.tests.test_commit',
 
2712
                   'bzrlib.tests.test_commit_merge',
 
2713
                   'bzrlib.tests.test_config',
 
2714
                   'bzrlib.tests.test_conflicts',
 
2715
                   'bzrlib.tests.test_counted_lock',
 
2716
                   'bzrlib.tests.test_decorators',
 
2717
                   'bzrlib.tests.test_delta',
 
2718
                   'bzrlib.tests.test_deprecated_graph',
 
2719
                   'bzrlib.tests.test_diff',
 
2720
                   'bzrlib.tests.test_dirstate',
 
2721
                   'bzrlib.tests.test_directory_service',
 
2722
                   'bzrlib.tests.test_email_message',
 
2723
                   'bzrlib.tests.test_errors',
 
2724
                   'bzrlib.tests.test_extract',
 
2725
                   'bzrlib.tests.test_fetch',
 
2726
                   'bzrlib.tests.test_ftp_transport',
 
2727
                   'bzrlib.tests.test_generate_docs',
 
2728
                   'bzrlib.tests.test_generate_ids',
 
2729
                   'bzrlib.tests.test_globbing',
 
2730
                   'bzrlib.tests.test_gpg',
 
2731
                   'bzrlib.tests.test_graph',
 
2732
                   'bzrlib.tests.test_hashcache',
 
2733
                   'bzrlib.tests.test_help',
 
2734
                   'bzrlib.tests.test_hooks',
 
2735
                   'bzrlib.tests.test_http',
 
2736
                   'bzrlib.tests.test_http_implementations',
 
2737
                   'bzrlib.tests.test_http_response',
 
2738
                   'bzrlib.tests.test_https_ca_bundle',
 
2739
                   'bzrlib.tests.test_identitymap',
 
2740
                   'bzrlib.tests.test_ignores',
 
2741
                   'bzrlib.tests.test_index',
 
2742
                   'bzrlib.tests.test_info',
 
2743
                   'bzrlib.tests.test_inv',
 
2744
                   'bzrlib.tests.test_knit',
 
2745
                   'bzrlib.tests.test_lazy_import',
 
2746
                   'bzrlib.tests.test_lazy_regex',
 
2747
                   'bzrlib.tests.test_lockdir',
 
2748
                   'bzrlib.tests.test_lockable_files',
 
2749
                   'bzrlib.tests.test_log',
 
2750
                   'bzrlib.tests.test_lsprof',
 
2751
                   'bzrlib.tests.test_lru_cache',
 
2752
                   'bzrlib.tests.test_mail_client',
 
2753
                   'bzrlib.tests.test_memorytree',
 
2754
                   'bzrlib.tests.test_merge',
 
2755
                   'bzrlib.tests.test_merge3',
 
2756
                   'bzrlib.tests.test_merge_core',
 
2757
                   'bzrlib.tests.test_merge_directive',
 
2758
                   'bzrlib.tests.test_missing',
 
2759
                   'bzrlib.tests.test_msgeditor',
 
2760
                   'bzrlib.tests.test_multiparent',
 
2761
                   'bzrlib.tests.test_mutabletree',
 
2762
                   'bzrlib.tests.test_nonascii',
 
2763
                   'bzrlib.tests.test_options',
 
2764
                   'bzrlib.tests.test_osutils',
 
2765
                   'bzrlib.tests.test_osutils_encodings',
 
2766
                   'bzrlib.tests.test_pack',
 
2767
                   'bzrlib.tests.test_pack_repository',
 
2768
                   'bzrlib.tests.test_patch',
 
2769
                   'bzrlib.tests.test_patches',
 
2770
                   'bzrlib.tests.test_permissions',
 
2771
                   'bzrlib.tests.test_plugins',
 
2772
                   'bzrlib.tests.test_progress',
 
2773
                   'bzrlib.tests.test_read_bundle',
 
2774
                   'bzrlib.tests.test_reconfigure',
 
2775
                   'bzrlib.tests.test_reconcile',
 
2776
                   'bzrlib.tests.test_registry',
 
2777
                   'bzrlib.tests.test_remote',
 
2778
                   'bzrlib.tests.test_repository',
 
2779
                   'bzrlib.tests.per_repository_reference',
 
2780
                   'bzrlib.tests.test_revert',
 
2781
                   'bzrlib.tests.test_revision',
 
2782
                   'bzrlib.tests.test_revisionspec',
 
2783
                   'bzrlib.tests.test_revisiontree',
 
2784
                   'bzrlib.tests.test_rio',
 
2785
                   'bzrlib.tests.test_rules',
 
2786
                   'bzrlib.tests.test_sampler',
 
2787
                   'bzrlib.tests.test_selftest',
 
2788
                   'bzrlib.tests.test_setup',
 
2789
                   'bzrlib.tests.test_sftp_transport',
 
2790
                   'bzrlib.tests.test_smart',
 
2791
                   'bzrlib.tests.test_smart_add',
 
2792
                   'bzrlib.tests.test_smart_transport',
 
2793
                   'bzrlib.tests.test_smtp_connection',
 
2794
                   'bzrlib.tests.test_source',
 
2795
                   'bzrlib.tests.test_ssh_transport',
 
2796
                   'bzrlib.tests.test_status',
 
2797
                   'bzrlib.tests.test_store',
 
2798
                   'bzrlib.tests.test_strace',
 
2799
                   'bzrlib.tests.test_subsume',
 
2800
                   'bzrlib.tests.test_switch',
 
2801
                   'bzrlib.tests.test_symbol_versioning',
 
2802
                   'bzrlib.tests.test_tag',
 
2803
                   'bzrlib.tests.test_testament',
 
2804
                   'bzrlib.tests.test_textfile',
 
2805
                   'bzrlib.tests.test_textmerge',
 
2806
                   'bzrlib.tests.test_timestamp',
 
2807
                   'bzrlib.tests.test_trace',
 
2808
                   'bzrlib.tests.test_transactions',
 
2809
                   'bzrlib.tests.test_transform',
 
2810
                   'bzrlib.tests.test_transport',
 
2811
                   'bzrlib.tests.test_transport_implementations',
 
2812
                   'bzrlib.tests.test_tree',
 
2813
                   'bzrlib.tests.test_treebuilder',
 
2814
                   'bzrlib.tests.test_tsort',
 
2815
                   'bzrlib.tests.test_tuned_gzip',
 
2816
                   'bzrlib.tests.test_ui',
 
2817
                   'bzrlib.tests.test_uncommit',
 
2818
                   'bzrlib.tests.test_upgrade',
 
2819
                   'bzrlib.tests.test_upgrade_stacked',
 
2820
                   'bzrlib.tests.test_urlutils',
 
2821
                   'bzrlib.tests.test_versionedfile',
 
2822
                   'bzrlib.tests.test_version',
 
2823
                   'bzrlib.tests.test_version_info',
 
2824
                   'bzrlib.tests.test__walkdirs_win32',
 
2825
                   'bzrlib.tests.test_weave',
 
2826
                   'bzrlib.tests.test_whitebox',
 
2827
                   'bzrlib.tests.test_win32utils',
 
2828
                   'bzrlib.tests.test_workingtree',
 
2829
                   'bzrlib.tests.test_workingtree_4',
 
2830
                   'bzrlib.tests.test_wsgi',
 
2831
                   'bzrlib.tests.test_xml',
 
2832
                   'bzrlib.tests.tree_implementations',
 
2833
                   'bzrlib.tests.workingtree_implementations',
 
2834
                   ]
4181
2835
 
4182
2836
    loader = TestUtil.TestLoader()
4183
2837
 
4184
 
    if keep_only is not None:
4185
 
        id_filter = TestIdList(keep_only)
4186
 
    if starting_with:
 
2838
    if starting_with is not None:
4187
2839
        # We take precedence over keep_only because *at loading time* using
4188
2840
        # both options means we will load less tests for the same final result.
4189
2841
        def interesting_module(name):
4190
 
            for start in starting_with:
4191
 
                if (
4192
 
                    # Either the module name starts with the specified string
4193
 
                    name.startswith(start)
4194
 
                    # or it may contain tests starting with the specified string
4195
 
                    or start.startswith(name)
4196
 
                    ):
4197
 
                    return True
4198
 
            return False
 
2842
            return (
 
2843
                # Either the module name starts with the specified string
 
2844
                name.startswith(starting_with)
 
2845
                # or it may contain tests starting with the specified string
 
2846
                or starting_with.startswith(name)
 
2847
                )
4199
2848
        loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
4200
2849
 
4201
2850
    elif keep_only is not None:
 
2851
        id_filter = TestIdList(keep_only)
4202
2852
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
4203
2853
        def interesting_module(name):
4204
2854
            return id_filter.refers_to(name)
4212
2862
    suite = loader.suiteClass()
4213
2863
 
4214
2864
    # 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():
 
2865
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
2866
 
 
2867
    modules_to_doctest = [
 
2868
        'bzrlib',
 
2869
        'bzrlib.errors',
 
2870
        'bzrlib.export',
 
2871
        'bzrlib.inventory',
 
2872
        'bzrlib.iterablefile',
 
2873
        'bzrlib.lockdir',
 
2874
        'bzrlib.merge3',
 
2875
        'bzrlib.option',
 
2876
        'bzrlib.store',
 
2877
        'bzrlib.symbol_versioning',
 
2878
        'bzrlib.tests',
 
2879
        'bzrlib.timestamp',
 
2880
        'bzrlib.version_info_formats.format_custom',
 
2881
        ]
 
2882
 
 
2883
    for mod in modules_to_doctest:
4218
2884
        if not interesting_module(mod):
4219
2885
            # No tests to keep here, move along
4220
2886
            continue
4221
2887
        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)
 
2888
            doc_suite = doctest.DocTestSuite(mod)
4226
2889
        except ValueError, e:
4227
2890
            print '**failed to get doctest for: %s\n%s' % (mod, e)
4228
2891
            raise
4229
 
        if len(doc_suite._tests) == 0:
4230
 
            raise errors.BzrError("no doctests found in %s" % (mod,))
4231
2892
        suite.addTest(doc_suite)
4232
2893
 
4233
2894
    default_encoding = sys.getdefaultencoding()
4234
 
    for name, plugin in _mod_plugin.plugins().items():
 
2895
    for name, plugin in bzrlib.plugin.plugins().items():
4235
2896
        if not interesting_module(plugin.module.__name__):
4236
2897
            continue
4237
2898
        plugin_suite = plugin.test_suite()
4243
2904
        if plugin_suite is not None:
4244
2905
            suite.addTest(plugin_suite)
4245
2906
        if default_encoding != sys.getdefaultencoding():
4246
 
            trace.warning(
 
2907
            bzrlib.trace.warning(
4247
2908
                'Plugin "%s" tried to reset default encoding to: %s', name,
4248
2909
                sys.getdefaultencoding())
4249
2910
            reload(sys)
4250
2911
            sys.setdefaultencoding(default_encoding)
4251
2912
 
 
2913
    if starting_with is not None:
 
2914
        suite = filter_suite_by_id_startswith(suite, starting_with)
 
2915
 
4252
2916
    if keep_only is not None:
4253
2917
        # Now that the referred modules have loaded their tests, keep only the
4254
2918
        # requested ones.
4255
2919
        suite = filter_suite_by_id_list(suite, id_filter)
4256
2920
        # Do some sanity checks on the id_list filtering
4257
2921
        not_found, duplicates = suite_matches_id_list(suite, keep_only)
4258
 
        if starting_with:
 
2922
        if starting_with is not None:
4259
2923
            # The tester has used both keep_only and starting_with, so he is
4260
2924
            # already aware that some tests are excluded from the list, there
4261
2925
            # is no need to tell him which.
4264
2928
            # Some tests mentioned in the list are not in the test suite. The
4265
2929
            # list may be out of date, report to the tester.
4266
2930
            for id in not_found:
4267
 
                trace.warning('"%s" not found in the test suite', id)
 
2931
                bzrlib.trace.warning('"%s" not found in the test suite', id)
4268
2932
        for id in duplicates:
4269
 
            trace.warning('"%s" is used as an id by several tests', id)
 
2933
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
4270
2934
 
4271
2935
    return suite
4272
2936
 
4273
2937
 
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.
 
2938
def multiply_tests_from_modules(module_name_list, scenario_iter, loader=None):
 
2939
    """Adapt all tests in some given modules to given scenarios.
 
2940
 
 
2941
    This is the recommended public interface for test parameterization.
 
2942
    Typically the test_suite() method for a per-implementation test
 
2943
    suite will call multiply_tests_from_modules and return the 
 
2944
    result.
 
2945
 
 
2946
    :param module_name_list: List of fully-qualified names of test
 
2947
        modules.
 
2948
    :param scenario_iter: Iterable of pairs of (scenario_name, 
 
2949
        scenario_param_dict).
 
2950
    :param loader: If provided, will be used instead of a new 
 
2951
        bzrlib.tests.TestLoader() instance.
 
2952
 
 
2953
    This returns a new TestSuite containing the cross product of
 
2954
    all the tests in all the modules, each repeated for each scenario.
 
2955
    Each test is adapted by adding the scenario name at the end 
 
2956
    of its name, and updating the test object's __dict__ with the
 
2957
    scenario_param_dict.
 
2958
 
 
2959
    >>> r = multiply_tests_from_modules(
 
2960
    ...     ['bzrlib.tests.test_sampler'],
 
2961
    ...     [('one', dict(param=1)), 
 
2962
    ...      ('two', dict(param=2))])
 
2963
    >>> tests = list(iter_suite_tests(r))
 
2964
    >>> len(tests)
 
2965
    2
 
2966
    >>> tests[0].id()
 
2967
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
 
2968
    >>> tests[0].param
 
2969
    1
 
2970
    >>> tests[1].param
 
2971
    2
4282
2972
    """
4283
 
    return reduce(_multiply_two_scenarios, map(list, scenarios))
4284
 
 
4285
 
 
4286
 
def _multiply_two_scenarios(scenarios_left, scenarios_right):
 
2973
    # XXX: Isn't load_tests() a better way to provide the same functionality
 
2974
    # without forcing a predefined TestScenarioApplier ? --vila 080215
 
2975
    if loader is None:
 
2976
        loader = TestUtil.TestLoader()
 
2977
 
 
2978
    suite = loader.suiteClass()
 
2979
 
 
2980
    adapter = TestScenarioApplier()
 
2981
    adapter.scenarios = list(scenario_iter)
 
2982
    adapt_modules(module_name_list, adapter, loader, suite)
 
2983
    return suite
 
2984
 
 
2985
 
 
2986
def multiply_scenarios(scenarios_left, scenarios_right):
4287
2987
    """Multiply two sets of scenarios.
4288
2988
 
4289
2989
    :returns: the cartesian product of the two sets of scenarios, that is
4297
2997
        for right_name, right_dict in scenarios_right]
4298
2998
 
4299
2999
 
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):
 
3000
 
 
3001
def adapt_modules(mods_list, adapter, loader, suite):
 
3002
    """Adapt the modules in mods_list using adapter and add to suite."""
 
3003
    tests = loader.loadTestsFromModuleNames(mods_list)
 
3004
    adapt_tests(tests, adapter, suite)
 
3005
 
 
3006
 
 
3007
def adapt_tests(tests_list, adapter, suite):
 
3008
    """Adapt the tests in tests_list using adapter and add to suite."""
 
3009
    for test in iter_suite_tests(tests_list):
 
3010
        suite.addTests(adapter.adapt(test))
 
3011
 
 
3012
 
 
3013
def _rmtree_temp_dir(dirname):
4436
3014
    # If LANG=C we probably have created some bogus paths
4437
3015
    # which rmtree(unicode) will fail to delete
4438
3016
    # so make sure we are using rmtree(str) to delete everything
4447
3025
    try:
4448
3026
        osutils.rmtree(dirname)
4449
3027
    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))
 
3028
        if sys.platform == 'win32' and e.errno == errno.EACCES:
 
3029
            sys.stderr.write(('Permission denied: '
 
3030
                                 'unable to remove testing dir '
 
3031
                                 '%s\n' % os.path.basename(dirname)))
 
3032
        else:
 
3033
            raise
 
3034
 
 
3035
 
 
3036
class Feature(object):
 
3037
    """An operating system Feature."""
 
3038
 
 
3039
    def __init__(self):
 
3040
        self._available = None
 
3041
 
 
3042
    def available(self):
 
3043
        """Is the feature available?
 
3044
 
 
3045
        :return: True if the feature is available.
 
3046
        """
 
3047
        if self._available is None:
 
3048
            self._available = self._probe()
 
3049
        return self._available
 
3050
 
 
3051
    def _probe(self):
 
3052
        """Implement this method in concrete features.
 
3053
 
 
3054
        :return: True if the feature is available.
 
3055
        """
 
3056
        raise NotImplementedError
 
3057
 
 
3058
    def __str__(self):
 
3059
        if getattr(self, 'feature_name', None):
 
3060
            return self.feature_name()
 
3061
        return self.__class__.__name__
 
3062
 
 
3063
 
 
3064
class _SymlinkFeature(Feature):
 
3065
 
 
3066
    def _probe(self):
 
3067
        return osutils.has_symlinks()
 
3068
 
 
3069
    def feature_name(self):
 
3070
        return 'symlinks'
 
3071
 
 
3072
SymlinkFeature = _SymlinkFeature()
 
3073
 
 
3074
 
 
3075
class _HardlinkFeature(Feature):
 
3076
 
 
3077
    def _probe(self):
 
3078
        return osutils.has_hardlinks()
 
3079
 
 
3080
    def feature_name(self):
 
3081
        return 'hardlinks'
 
3082
 
 
3083
HardlinkFeature = _HardlinkFeature()
 
3084
 
 
3085
 
 
3086
class _OsFifoFeature(Feature):
 
3087
 
 
3088
    def _probe(self):
 
3089
        return getattr(os, 'mkfifo', None)
 
3090
 
 
3091
    def feature_name(self):
 
3092
        return 'filesystem fifos'
 
3093
 
 
3094
OsFifoFeature = _OsFifoFeature()
 
3095
 
 
3096
 
 
3097
class _UnicodeFilenameFeature(Feature):
 
3098
    """Does the filesystem support Unicode filenames?"""
 
3099
 
 
3100
    def _probe(self):
 
3101
        try:
 
3102
            # Check for character combinations unlikely to be covered by any
 
3103
            # single non-unicode encoding. We use the characters
 
3104
            # - greek small letter alpha (U+03B1) and
 
3105
            # - braille pattern dots-123456 (U+283F).
 
3106
            os.stat(u'\u03b1\u283f')
 
3107
        except UnicodeEncodeError:
 
3108
            return False
 
3109
        except (IOError, OSError):
 
3110
            # The filesystem allows the Unicode filename but the file doesn't
 
3111
            # exist.
 
3112
            return True
 
3113
        else:
 
3114
            # The filesystem allows the Unicode filename and the file exists,
 
3115
            # for some reason.
 
3116
            return True
 
3117
 
 
3118
UnicodeFilenameFeature = _UnicodeFilenameFeature()
 
3119
 
 
3120
 
 
3121
class TestScenarioApplier(object):
 
3122
    """A tool to apply scenarios to tests."""
 
3123
 
 
3124
    def adapt(self, test):
 
3125
        """Return a TestSuite containing a copy of test for each scenario."""
 
3126
        result = unittest.TestSuite()
 
3127
        for scenario in self.scenarios:
 
3128
            result.addTest(self.adapt_test_to_scenario(test, scenario))
 
3129
        return result
 
3130
 
 
3131
    def adapt_test_to_scenario(self, test, scenario):
 
3132
        """Copy test and apply scenario to it.
 
3133
 
 
3134
        :param test: A test to adapt.
 
3135
        :param scenario: A tuple describing the scenarion.
 
3136
            The first element of the tuple is the new test id.
 
3137
            The second element is a dict containing attributes to set on the
 
3138
            test.
 
3139
        :return: The adapted test.
 
3140
        """
 
3141
        from copy import deepcopy
 
3142
        new_test = deepcopy(test)
 
3143
        for name, value in scenario[1].items():
 
3144
            setattr(new_test, name, value)
 
3145
        new_id = "%s(%s)" % (new_test.id(), scenario[0])
 
3146
        new_test.id = lambda: new_id
 
3147
        return new_test
4461
3148
 
4462
3149
 
4463
3150
def probe_unicode_in_user_encoding():
4469
3156
    possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
4470
3157
    for uni_val in possible_vals:
4471
3158
        try:
4472
 
            str_val = uni_val.encode(osutils.get_user_encoding())
 
3159
            str_val = uni_val.encode(bzrlib.user_encoding)
4473
3160
        except UnicodeEncodeError:
4474
3161
            # Try a different character
4475
3162
            pass
4493
3180
    return None
4494
3181
 
4495
3182
 
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')
 
3183
class _FTPServerFeature(Feature):
 
3184
    """Some tests want an FTP Server, check if one is available.
 
3185
 
 
3186
    Right now, the only way this is available is if 'medusa' is installed.
 
3187
    http://www.amk.ca/python/code/medusa.html
 
3188
    """
 
3189
 
 
3190
    def _probe(self):
 
3191
        try:
 
3192
            import bzrlib.tests.ftp_server
 
3193
            return True
 
3194
        except ImportError:
 
3195
            return False
 
3196
 
 
3197
    def feature_name(self):
 
3198
        return 'FTPServer'
 
3199
 
 
3200
FTPServerFeature = _FTPServerFeature()
 
3201
 
 
3202
 
 
3203
class _UnicodeFilename(Feature):
 
3204
    """Does the filesystem support Unicode filenames?"""
 
3205
 
 
3206
    def _probe(self):
 
3207
        try:
 
3208
            os.stat(u'\u03b1')
 
3209
        except UnicodeEncodeError:
 
3210
            return False
 
3211
        except (IOError, OSError):
 
3212
            # The filesystem allows the Unicode filename but the file doesn't
 
3213
            # exist.
 
3214
            return True
 
3215
        else:
 
3216
            # The filesystem allows the Unicode filename and the file exists,
 
3217
            # for some reason.
 
3218
            return True
 
3219
 
 
3220
UnicodeFilename = _UnicodeFilename()
 
3221
 
 
3222
 
 
3223
class _UTF8Filesystem(Feature):
 
3224
    """Is the filesystem UTF-8?"""
 
3225
 
 
3226
    def _probe(self):
 
3227
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
 
3228
            return True
 
3229
        return False
 
3230
 
 
3231
UTF8Filesystem = _UTF8Filesystem()
 
3232
 
 
3233
 
 
3234
class _CaseInsensitiveFilesystemFeature(Feature):
 
3235
    """Check if underlined filesystem is case-insensitive
 
3236
    (e.g. on Windows, Cygwin, MacOS)
 
3237
    """
 
3238
 
 
3239
    def _probe(self):
 
3240
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
 
3241
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
 
3242
            TestCaseWithMemoryTransport.TEST_ROOT = root
 
3243
        else:
 
3244
            root = TestCaseWithMemoryTransport.TEST_ROOT
 
3245
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
 
3246
            dir=root)
 
3247
        name_a = osutils.pathjoin(tdir, 'a')
 
3248
        name_A = osutils.pathjoin(tdir, 'A')
 
3249
        os.mkdir(name_a)
 
3250
        result = osutils.isdir(name_A)
 
3251
        _rmtree_temp_dir(tdir)
 
3252
        return result
 
3253
 
 
3254
    def feature_name(self):
 
3255
        return 'case-insensitive filesystem'
 
3256
 
 
3257
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()