~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

(vila) Forbid more operations on ReadonlyTransportDecorator (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

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