~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Alexander Belchenko
  • Date: 2006-08-01 18:27:42 UTC
  • mto: (1711.2.111 jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1906.
  • Revision ID: bialix@ukr.net-20060801182742-b28d2edf7eea75d1
English

Show diffs side-by-side

added added

removed removed

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