~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-07-12 12:36:57 UTC
  • mfrom: (1732.3.4 bzr.revnoX)
  • Revision ID: pqm@pqm.ubuntu.com-20060712123657-365eeb32b69308bf
(matthieu) revno:x:url revision spec

Show diffs side-by-side

added added

removed removed

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