~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

(vila) Make all transport put_bytes() raises TypeError when given unicode
 strings rather than bytes (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

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