~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Jelmer Vernooij
  • Date: 2009-06-09 00:59:51 UTC
  • mto: (4443.1.1 bzr.dev)
  • mto: This revision was merged to the branch mainline in revision 4444.
  • Revision ID: jelmer@samba.org-20090609005951-apv900cdk35o2ygh
Move squashing of XML-invalid characters to XMLSerializer.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
"""Testing framework extensions"""
 
17
 
 
18
# TODO: Perhaps there should be an API to find out if bzr running under the
 
19
# test suite -- some plugins might want to avoid making intrusive changes if
 
20
# this is the case.  However, we want behaviour under to test to diverge as
 
21
# little as possible, so this should be used rarely if it's added at all.
 
22
# (Suggestion from j-a-meinel, 2005-11-24)
18
23
 
19
24
# NOTE: Some classes in here use camelCaseNaming() rather than
20
25
# underscore_naming().  That's for consistency with unittest; it's not the
23
28
 
24
29
import atexit
25
30
import codecs
26
 
import copy
27
31
from cStringIO import StringIO
28
32
import difflib
29
33
import doctest
30
34
import errno
31
 
import itertools
32
35
import logging
 
36
import math
33
37
import os
34
 
import platform
35
 
import pprint
 
38
from pprint import pformat
36
39
import random
37
40
import re
38
41
import shlex
39
42
import stat
40
 
import subprocess
 
43
from subprocess import Popen, PIPE, STDOUT
41
44
import sys
42
45
import tempfile
43
46
import threading
44
47
import time
45
 
import traceback
46
48
import unittest
47
49
import warnings
48
50
 
49
 
import testtools
50
 
# nb: check this before importing anything else from within it
51
 
_testtools_version = getattr(testtools, '__version__', ())
52
 
if _testtools_version < (0, 9, 5):
53
 
    raise ImportError("need at least testtools 0.9.5: %s is %r"
54
 
        % (testtools.__file__, _testtools_version))
55
 
from testtools import content
56
51
 
57
 
import bzrlib
58
52
from bzrlib import (
59
53
    branchbuilder,
60
54
    bzrdir,
61
 
    chk_map,
62
 
    commands as _mod_commands,
63
 
    config,
64
55
    debug,
65
56
    errors,
66
57
    hooks,
67
58
    lock as _mod_lock,
68
 
    lockdir,
69
59
    memorytree,
70
60
    osutils,
71
 
    plugin as _mod_plugin,
72
 
    pyutils,
 
61
    progress,
73
62
    ui,
74
63
    urlutils,
75
64
    registry,
76
 
    symbol_versioning,
77
 
    trace,
78
 
    transport as _mod_transport,
79
65
    workingtree,
80
66
    )
 
67
import bzrlib.branch
 
68
import bzrlib.commands
 
69
import bzrlib.timestamp
 
70
import bzrlib.export
 
71
import bzrlib.inventory
 
72
import bzrlib.iterablefile
 
73
import bzrlib.lockdir
81
74
try:
82
75
    import bzrlib.lsprof
83
76
except ImportError:
84
77
    # lsprof not available
85
78
    pass
86
 
from bzrlib.smart import client, request
87
 
from bzrlib.transport import (
88
 
    memory,
89
 
    pathfilter,
90
 
    )
 
79
from bzrlib.merge import merge_inner
 
80
import bzrlib.merge3
 
81
import bzrlib.plugin
 
82
from bzrlib.smart import client, request, server
 
83
import bzrlib.store
 
84
from bzrlib import symbol_versioning
91
85
from bzrlib.symbol_versioning import (
 
86
    DEPRECATED_PARAMETER,
92
87
    deprecated_function,
93
 
    deprecated_in,
94
 
    )
95
 
from bzrlib.tests import (
96
 
    test_server,
97
 
    TestUtil,
98
 
    treeshape,
99
 
    )
100
 
from bzrlib.ui import NullProgressView
101
 
from bzrlib.ui.text import TextUIFactory
 
88
    deprecated_method,
 
89
    deprecated_passed,
 
90
    )
 
91
import bzrlib.trace
 
92
from bzrlib.transport import get_transport
 
93
import bzrlib.transport
 
94
from bzrlib.transport.local import LocalURLServer
 
95
from bzrlib.transport.memory import MemoryServer
 
96
from bzrlib.transport.readonly import ReadonlyServer
 
97
from bzrlib.trace import mutter, note
 
98
from bzrlib.tests import TestUtil
 
99
from bzrlib.tests.http_server import HttpServer
 
100
from bzrlib.tests.TestUtil import (
 
101
                          TestSuite,
 
102
                          TestLoader,
 
103
                          )
 
104
from bzrlib.tests.treeshape import build_tree_contents
 
105
import bzrlib.version_info_formats.format_custom
 
106
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
102
107
 
103
108
# Mark this python module as being part of the implementation
104
109
# of unittest: this gives us better tracebacks where the last
105
110
# shown frame is the test code, not our assertXYZ.
106
111
__unittest = 1
107
112
 
108
 
default_transport = test_server.LocalURLServer
109
 
 
110
 
 
111
 
_unitialized_attr = object()
112
 
"""A sentinel needed to act as a default value in a method signature."""
113
 
 
114
 
 
115
 
# Subunit result codes, defined here to prevent a hard dependency on subunit.
116
 
SUBUNIT_SEEK_SET = 0
117
 
SUBUNIT_SEEK_CUR = 1
118
 
 
119
 
# These are intentionally brought into this namespace. That way plugins, etc
120
 
# can just "from bzrlib.tests import TestCase, TestLoader, etc"
121
 
TestSuite = TestUtil.TestSuite
122
 
TestLoader = TestUtil.TestLoader
123
 
 
124
 
# Tests should run in a clean and clearly defined environment. The goal is to
125
 
# keep them isolated from the running environment as mush as possible. The test
126
 
# framework ensures the variables defined below are set (or deleted if the
127
 
# value is None) before a test is run and reset to their original value after
128
 
# the test is run. Generally if some code depends on an environment variable,
129
 
# the tests should start without this variable in the environment. There are a
130
 
# few exceptions but you shouldn't violate this rule lightly.
131
 
isolated_environ = {
132
 
    'BZR_HOME': None,
133
 
    'HOME': None,
134
 
    # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
135
 
    # tests do check our impls match APPDATA
136
 
    'BZR_EDITOR': None, # test_msgeditor manipulates this variable
137
 
    'VISUAL': None,
138
 
    'EDITOR': None,
139
 
    'BZR_EMAIL': None,
140
 
    'BZREMAIL': None, # may still be present in the environment
141
 
    'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
142
 
    'BZR_PROGRESS_BAR': None,
143
 
    # This should trap leaks to ~/.bzr.log. This occurs when tests use TestCase
144
 
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
145
 
    # TestCase should not use disk resources, BZR_LOG is one.
146
 
    'BZR_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
147
 
    'BZR_PLUGIN_PATH': None,
148
 
    'BZR_DISABLE_PLUGINS': None,
149
 
    'BZR_PLUGINS_AT': None,
150
 
    'BZR_CONCURRENCY': None,
151
 
    # Make sure that any text ui tests are consistent regardless of
152
 
    # the environment the test case is run in; you may want tests that
153
 
    # test other combinations.  'dumb' is a reasonable guess for tests
154
 
    # going to a pipe or a StringIO.
155
 
    'TERM': 'dumb',
156
 
    'LINES': '25',
157
 
    'COLUMNS': '80',
158
 
    'BZR_COLUMNS': '80',
159
 
    # Disable SSH Agent
160
 
    'SSH_AUTH_SOCK': None,
161
 
    # Proxies
162
 
    'http_proxy': None,
163
 
    'HTTP_PROXY': None,
164
 
    'https_proxy': None,
165
 
    'HTTPS_PROXY': None,
166
 
    'no_proxy': None,
167
 
    'NO_PROXY': None,
168
 
    'all_proxy': None,
169
 
    'ALL_PROXY': None,
170
 
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
171
 
    # least. If you do (care), please update this comment
172
 
    # -- vila 20080401
173
 
    'ftp_proxy': None,
174
 
    'FTP_PROXY': None,
175
 
    'BZR_REMOTE_PATH': None,
176
 
    # Generally speaking, we don't want apport reporting on crashes in
177
 
    # the test envirnoment unless we're specifically testing apport,
178
 
    # so that it doesn't leak into the real system environment.  We
179
 
    # use an env var so it propagates to subprocesses.
180
 
    'APPORT_DISABLE': '1',
181
 
    }
182
 
 
183
 
 
184
 
def override_os_environ(test, env=None):
185
 
    """Modify os.environ keeping a copy.
186
 
    
187
 
    :param test: A test instance
188
 
 
189
 
    :param env: A dict containing variable definitions to be installed
190
 
    """
191
 
    if env is None:
192
 
        env = isolated_environ
193
 
    test._original_os_environ = dict([(var, value)
194
 
                                      for var, value in os.environ.iteritems()])
195
 
    for var, value in env.iteritems():
196
 
        osutils.set_or_unset_env(var, value)
197
 
        if var not in test._original_os_environ:
198
 
            # The var is new, add it with a value of None, so
199
 
            # restore_os_environ will delete it
200
 
            test._original_os_environ[var] = None
201
 
 
202
 
 
203
 
def restore_os_environ(test):
204
 
    """Restore os.environ to its original state.
205
 
 
206
 
    :param test: A test instance previously passed to override_os_environ.
207
 
    """
208
 
    for var, value in test._original_os_environ.iteritems():
209
 
        # Restore the original value (or delete it if the value has been set to
210
 
        # None in override_os_environ).
211
 
        osutils.set_or_unset_env(var, value)
212
 
 
213
 
 
214
 
class ExtendedTestResult(testtools.TextTestResult):
 
113
default_transport = LocalURLServer
 
114
 
 
115
 
 
116
class ExtendedTestResult(unittest._TextTestResult):
215
117
    """Accepts, reports and accumulates the results of running tests.
216
118
 
217
119
    Compared to the unittest version this class adds support for
231
133
 
232
134
    def __init__(self, stream, descriptions, verbosity,
233
135
                 bench_history=None,
 
136
                 num_tests=None,
234
137
                 strict=False,
235
138
                 ):
236
139
        """Construct new TestResult.
238
141
        :param bench_history: Optionally, a writable file object to accumulate
239
142
            benchmark results.
240
143
        """
241
 
        testtools.TextTestResult.__init__(self, stream)
 
144
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
242
145
        if bench_history is not None:
243
146
            from bzrlib.version import _get_bzr_source_tree
244
147
            src_tree = _get_bzr_source_tree()
255
158
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
256
159
        self._bench_history = bench_history
257
160
        self.ui = ui.ui_factory
258
 
        self.num_tests = 0
 
161
        self.num_tests = num_tests
259
162
        self.error_count = 0
260
163
        self.failure_count = 0
261
164
        self.known_failure_count = 0
265
168
        self.count = 0
266
169
        self._overall_start_time = time.time()
267
170
        self._strict = strict
268
 
        self._first_thread_leaker_id = None
269
 
        self._tests_leaking_threads_count = 0
270
 
        self._traceback_from_test = None
271
171
 
272
 
    def stopTestRun(self):
273
 
        run = self.testsRun
274
 
        actionTaken = "Ran"
275
 
        stopTime = time.time()
276
 
        timeTaken = stopTime - self.startTime
277
 
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
278
 
        #                the parent class method is similar have to duplicate
279
 
        self._show_list('ERROR', self.errors)
280
 
        self._show_list('FAIL', self.failures)
281
 
        self.stream.write(self.sep2)
282
 
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
283
 
                            run, run != 1 and "s" or "", timeTaken))
284
 
        if not self.wasSuccessful():
285
 
            self.stream.write("FAILED (")
286
 
            failed, errored = map(len, (self.failures, self.errors))
287
 
            if failed:
288
 
                self.stream.write("failures=%d" % failed)
289
 
            if errored:
290
 
                if failed: self.stream.write(", ")
291
 
                self.stream.write("errors=%d" % errored)
292
 
            if self.known_failure_count:
293
 
                if failed or errored: self.stream.write(", ")
294
 
                self.stream.write("known_failure_count=%d" %
295
 
                    self.known_failure_count)
296
 
            self.stream.write(")\n")
297
 
        else:
298
 
            if self.known_failure_count:
299
 
                self.stream.write("OK (known_failures=%d)\n" %
300
 
                    self.known_failure_count)
301
 
            else:
302
 
                self.stream.write("OK\n")
303
 
        if self.skip_count > 0:
304
 
            skipped = self.skip_count
305
 
            self.stream.write('%d test%s skipped\n' %
306
 
                                (skipped, skipped != 1 and "s" or ""))
307
 
        if self.unsupported:
308
 
            for feature, count in sorted(self.unsupported.items()):
309
 
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
310
 
                    (feature, count))
 
172
    def done(self):
311
173
        if self._strict:
312
174
            ok = self.wasStrictlySuccessful()
313
175
        else:
314
176
            ok = self.wasSuccessful()
315
 
        if self._first_thread_leaker_id:
 
177
        if ok:
 
178
            self.stream.write('tests passed\n')
 
179
        else:
 
180
            self.stream.write('tests failed\n')
 
181
        if TestCase._first_thread_leaker_id:
316
182
            self.stream.write(
317
183
                '%s is leaking threads among %d leaking tests.\n' % (
318
 
                self._first_thread_leaker_id,
319
 
                self._tests_leaking_threads_count))
320
 
            # We don't report the main thread as an active one.
321
 
            self.stream.write(
322
 
                '%d non-main threads were left active in the end.\n'
323
 
                % (len(self._active_threads) - 1))
324
 
 
325
 
    def getDescription(self, test):
326
 
        return test.id()
327
 
 
328
 
    def _extractBenchmarkTime(self, testCase, details=None):
 
184
                TestCase._first_thread_leaker_id,
 
185
                TestCase._leaking_threads_tests))
 
186
 
 
187
    def _extractBenchmarkTime(self, testCase):
329
188
        """Add a benchmark time for the current test case."""
330
 
        if details and 'benchtime' in details:
331
 
            return float(''.join(details['benchtime'].iter_bytes()))
332
189
        return getattr(testCase, "_benchtime", None)
333
190
 
334
191
    def _elapsedTestTimeString(self):
335
192
        """Return a time string for the overall time the current test has taken."""
336
 
        return self._formatTime(self._delta_to_float(
337
 
            self._now() - self._start_datetime))
 
193
        return self._formatTime(time.time() - self._start_time)
338
194
 
339
195
    def _testTimeString(self, testCase):
340
196
        benchmark_time = self._extractBenchmarkTime(testCase)
341
197
        if benchmark_time is not None:
342
 
            return self._formatTime(benchmark_time) + "*"
 
198
            return "%s/%s" % (
 
199
                self._formatTime(benchmark_time),
 
200
                self._elapsedTestTimeString())
343
201
        else:
344
 
            return self._elapsedTestTimeString()
 
202
            return "           %s" % self._elapsedTestTimeString()
345
203
 
346
204
    def _formatTime(self, seconds):
347
205
        """Format seconds as milliseconds with leading spaces."""
351
209
 
352
210
    def _shortened_test_description(self, test):
353
211
        what = test.id()
354
 
        what = re.sub(r'^bzrlib\.tests\.', '', what)
 
212
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
355
213
        return what
356
214
 
357
 
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
358
 
    #                multiple times in a row, because the handler is added for
359
 
    #                each test but the container list is shared between cases.
360
 
    #                See lp:498869 lp:625574 and lp:637725 for background.
361
 
    def _record_traceback_from_test(self, exc_info):
362
 
        """Store the traceback from passed exc_info tuple till"""
363
 
        self._traceback_from_test = exc_info[2]
364
 
 
365
215
    def startTest(self, test):
366
 
        super(ExtendedTestResult, self).startTest(test)
 
216
        unittest.TestResult.startTest(self, test)
367
217
        if self.count == 0:
368
218
            self.startTests()
369
 
        self.count += 1
370
219
        self.report_test_start(test)
371
220
        test.number = self.count
372
221
        self._recordTestStartTime()
373
 
        # Make testtools cases give us the real traceback on failure
374
 
        addOnException = getattr(test, "addOnException", None)
375
 
        if addOnException is not None:
376
 
            addOnException(self._record_traceback_from_test)
377
 
        # Only check for thread leaks on bzrlib derived test cases
378
 
        if isinstance(test, TestCase):
379
 
            test.addCleanup(self._check_leaked_threads, test)
380
 
 
381
 
    def stopTest(self, test):
382
 
        super(ExtendedTestResult, self).stopTest(test)
383
 
        # Manually break cycles, means touching various private things but hey
384
 
        getDetails = getattr(test, "getDetails", None)
385
 
        if getDetails is not None:
386
 
            getDetails().clear()
387
 
        # Clear _type_equality_funcs to try to stop TestCase instances
388
 
        # from wasting memory. 'clear' is not available in all Python
389
 
        # versions (bug 809048)
390
 
        type_equality_funcs = getattr(test, "_type_equality_funcs", None)
391
 
        if type_equality_funcs is not None:
392
 
            tef_clear = getattr(type_equality_funcs, "clear", None)
393
 
            if tef_clear is None:
394
 
                tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
395
 
                if tef_instance_dict is not None:
396
 
                    tef_clear = tef_instance_dict.clear
397
 
            if tef_clear is not None:
398
 
                tef_clear()
399
 
        self._traceback_from_test = None
400
222
 
401
223
    def startTests(self):
402
 
        self.report_tests_starting()
403
 
        self._active_threads = threading.enumerate()
404
 
 
405
 
    def _check_leaked_threads(self, test):
406
 
        """See if any threads have leaked since last call
407
 
 
408
 
        A sample of live threads is stored in the _active_threads attribute,
409
 
        when this method runs it compares the current live threads and any not
410
 
        in the previous sample are treated as having leaked.
411
 
        """
412
 
        now_active_threads = set(threading.enumerate())
413
 
        threads_leaked = now_active_threads.difference(self._active_threads)
414
 
        if threads_leaked:
415
 
            self._report_thread_leak(test, threads_leaked, now_active_threads)
416
 
            self._tests_leaking_threads_count += 1
417
 
            if self._first_thread_leaker_id is None:
418
 
                self._first_thread_leaker_id = test.id()
419
 
            self._active_threads = now_active_threads
 
224
        self.stream.write(
 
225
            'testing: %s\n' % (osutils.realpath(sys.argv[0]),))
 
226
        self.stream.write(
 
227
            '   %s (%s python%s)\n' % (
 
228
                    bzrlib.__path__[0],
 
229
                    bzrlib.version_string,
 
230
                    bzrlib._format_version_tuple(sys.version_info),
 
231
                    ))
 
232
        self.stream.write('\n')
420
233
 
421
234
    def _recordTestStartTime(self):
422
235
        """Record that a test has started."""
423
 
        self._start_datetime = self._now()
 
236
        self._start_time = time.time()
 
237
 
 
238
    def _cleanupLogFile(self, test):
 
239
        # We can only do this if we have one of our TestCases, not if
 
240
        # we have a doctest.
 
241
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
 
242
        if setKeepLogfile is not None:
 
243
            setKeepLogfile()
424
244
 
425
245
    def addError(self, test, err):
426
246
        """Tell result that test finished with an error.
428
248
        Called from the TestCase run() method when the test
429
249
        fails with an unexpected error.
430
250
        """
431
 
        self._post_mortem(self._traceback_from_test)
432
 
        super(ExtendedTestResult, self).addError(test, err)
433
 
        self.error_count += 1
434
 
        self.report_error(test, err)
435
 
        if self.stop_early:
436
 
            self.stop()
 
251
        self._testConcluded(test)
 
252
        if isinstance(err[1], TestNotApplicable):
 
253
            return self._addNotApplicable(test, err)
 
254
        elif isinstance(err[1], UnavailableFeature):
 
255
            return self.addNotSupported(test, err[1].args[0])
 
256
        else:
 
257
            unittest.TestResult.addError(self, test, err)
 
258
            self.error_count += 1
 
259
            self.report_error(test, err)
 
260
            if self.stop_early:
 
261
                self.stop()
 
262
            self._cleanupLogFile(test)
437
263
 
438
264
    def addFailure(self, test, err):
439
265
        """Tell result that test failed.
441
267
        Called from the TestCase run() method when the test
442
268
        fails because e.g. an assert() method failed.
443
269
        """
444
 
        self._post_mortem(self._traceback_from_test)
445
 
        super(ExtendedTestResult, self).addFailure(test, err)
446
 
        self.failure_count += 1
447
 
        self.report_failure(test, err)
448
 
        if self.stop_early:
449
 
            self.stop()
 
270
        self._testConcluded(test)
 
271
        if isinstance(err[1], KnownFailure):
 
272
            return self._addKnownFailure(test, err)
 
273
        else:
 
274
            unittest.TestResult.addFailure(self, test, err)
 
275
            self.failure_count += 1
 
276
            self.report_failure(test, err)
 
277
            if self.stop_early:
 
278
                self.stop()
 
279
            self._cleanupLogFile(test)
450
280
 
451
 
    def addSuccess(self, test, details=None):
 
281
    def addSuccess(self, test):
452
282
        """Tell result that test completed successfully.
453
283
 
454
284
        Called from the TestCase run()
455
285
        """
 
286
        self._testConcluded(test)
456
287
        if self._bench_history is not None:
457
 
            benchmark_time = self._extractBenchmarkTime(test, details)
 
288
            benchmark_time = self._extractBenchmarkTime(test)
458
289
            if benchmark_time is not None:
459
290
                self._bench_history.write("%s %s\n" % (
460
291
                    self._formatTime(benchmark_time),
461
292
                    test.id()))
462
293
        self.report_success(test)
463
 
        super(ExtendedTestResult, self).addSuccess(test)
 
294
        self._cleanupLogFile(test)
 
295
        unittest.TestResult.addSuccess(self, test)
464
296
        test._log_contents = ''
465
297
 
466
 
    def addExpectedFailure(self, test, err):
 
298
    def _testConcluded(self, test):
 
299
        """Common code when a test has finished.
 
300
 
 
301
        Called regardless of whether it succeded, failed, etc.
 
302
        """
 
303
        pass
 
304
 
 
305
    def _addKnownFailure(self, test, err):
467
306
        self.known_failure_count += 1
468
307
        self.report_known_failure(test, err)
469
308
 
470
 
    def addUnexpectedSuccess(self, test, details=None):
471
 
        """Tell result the test unexpectedly passed, counting as a failure
472
 
 
473
 
        When the minimum version of testtools required becomes 0.9.8 this
474
 
        can be updated to use the new handling there.
475
 
        """
476
 
        super(ExtendedTestResult, self).addFailure(test, details=details)
477
 
        self.failure_count += 1
478
 
        self.report_unexpected_success(test,
479
 
            "".join(details["reason"].iter_text()))
480
 
        if self.stop_early:
481
 
            self.stop()
482
 
 
483
309
    def addNotSupported(self, test, feature):
484
310
        """The test will not be run because of a missing feature.
485
311
        """
486
312
        # this can be called in two different ways: it may be that the
487
 
        # test started running, and then raised (through requireFeature)
 
313
        # test started running, and then raised (through addError)
488
314
        # UnavailableFeature.  Alternatively this method can be called
489
 
        # while probing for features before running the test code proper; in
490
 
        # that case we will see startTest and stopTest, but the test will
491
 
        # never actually run.
 
315
        # while probing for features before running the tests; in that
 
316
        # case we will see startTest and stopTest, but the test will never
 
317
        # actually run.
492
318
        self.unsupported.setdefault(str(feature), 0)
493
319
        self.unsupported[str(feature)] += 1
494
320
        self.report_unsupported(test, feature)
498
324
        self.skip_count += 1
499
325
        self.report_skip(test, reason)
500
326
 
501
 
    def addNotApplicable(self, test, reason):
502
 
        self.not_applicable_count += 1
503
 
        self.report_not_applicable(test, reason)
504
 
 
505
 
    def _post_mortem(self, tb=None):
506
 
        """Start a PDB post mortem session."""
507
 
        if os.environ.get('BZR_TEST_PDB', None):
508
 
            import pdb
509
 
            pdb.post_mortem(tb)
510
 
 
511
 
    def progress(self, offset, whence):
512
 
        """The test is adjusting the count of tests to run."""
513
 
        if whence == SUBUNIT_SEEK_SET:
514
 
            self.num_tests = offset
515
 
        elif whence == SUBUNIT_SEEK_CUR:
516
 
            self.num_tests += offset
517
 
        else:
518
 
            raise errors.BzrError("Unknown whence %r" % whence)
519
 
 
520
 
    def report_tests_starting(self):
521
 
        """Display information before the test run begins"""
522
 
        if getattr(sys, 'frozen', None) is None:
523
 
            bzr_path = osutils.realpath(sys.argv[0])
524
 
        else:
525
 
            bzr_path = sys.executable
526
 
        self.stream.write(
527
 
            'bzr selftest: %s\n' % (bzr_path,))
528
 
        self.stream.write(
529
 
            '   %s\n' % (
530
 
                    bzrlib.__path__[0],))
531
 
        self.stream.write(
532
 
            '   bzr-%s python-%s %s\n' % (
533
 
                    bzrlib.version_string,
534
 
                    bzrlib._format_version_tuple(sys.version_info),
535
 
                    platform.platform(aliased=1),
536
 
                    ))
537
 
        self.stream.write('\n')
538
 
 
539
 
    def report_test_start(self, test):
540
 
        """Display information on the test just about to be run"""
541
 
 
542
 
    def _report_thread_leak(self, test, leaked_threads, active_threads):
543
 
        """Display information on a test that leaked one or more threads"""
544
 
        # GZ 2010-09-09: A leak summary reported separately from the general
545
 
        #                thread debugging would be nice. Tests under subunit
546
 
        #                need something not using stream, perhaps adding a
547
 
        #                testtools details object would be fitting.
548
 
        if 'threads' in selftest_debug_flags:
549
 
            self.stream.write('%s is leaking, active is now %d\n' %
550
 
                (test.id(), len(active_threads)))
551
 
 
552
 
    def startTestRun(self):
553
 
        self.startTime = time.time()
 
327
    def _addNotApplicable(self, test, skip_excinfo):
 
328
        if isinstance(skip_excinfo[1], TestNotApplicable):
 
329
            self.not_applicable_count += 1
 
330
            self.report_not_applicable(test, skip_excinfo)
 
331
        try:
 
332
            test.tearDown()
 
333
        except KeyboardInterrupt:
 
334
            raise
 
335
        except:
 
336
            self.addError(test, test.exc_info())
 
337
        else:
 
338
            # seems best to treat this as success from point-of-view of unittest
 
339
            # -- it actually does nothing so it barely matters :)
 
340
            unittest.TestResult.addSuccess(self, test)
 
341
            test._log_contents = ''
 
342
 
 
343
    def printErrorList(self, flavour, errors):
 
344
        for test, err in errors:
 
345
            self.stream.writeln(self.separator1)
 
346
            self.stream.write("%s: " % flavour)
 
347
            self.stream.writeln(self.getDescription(test))
 
348
            if getattr(test, '_get_log', None) is not None:
 
349
                self.stream.write('\n')
 
350
                self.stream.write(
 
351
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
 
352
                self.stream.write('\n')
 
353
                self.stream.write(test._get_log())
 
354
                self.stream.write('\n')
 
355
                self.stream.write(
 
356
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
 
357
                self.stream.write('\n')
 
358
            self.stream.writeln(self.separator2)
 
359
            self.stream.writeln("%s" % err)
 
360
 
 
361
    def finished(self):
 
362
        pass
 
363
 
 
364
    def report_cleaning_up(self):
 
365
        pass
554
366
 
555
367
    def report_success(self, test):
556
368
        pass
566
378
 
567
379
    def __init__(self, stream, descriptions, verbosity,
568
380
                 bench_history=None,
 
381
                 num_tests=None,
569
382
                 pb=None,
570
383
                 strict=None,
571
384
                 ):
572
385
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
573
 
            bench_history, strict)
574
 
        # We no longer pass them around, but just rely on the UIFactory stack
575
 
        # for state
576
 
        if pb is not None:
577
 
            warnings.warn("Passing pb to TextTestResult is deprecated")
578
 
        self.pb = self.ui.nested_progress_bar()
 
386
            bench_history, num_tests, strict)
 
387
        if pb is None:
 
388
            self.pb = self.ui.nested_progress_bar()
 
389
            self._supplied_pb = False
 
390
        else:
 
391
            self.pb = pb
 
392
            self._supplied_pb = True
579
393
        self.pb.show_pct = False
580
394
        self.pb.show_spinner = False
581
395
        self.pb.show_eta = False,
582
396
        self.pb.show_count = False
583
397
        self.pb.show_bar = False
584
 
        self.pb.update_latency = 0
585
 
        self.pb.show_transport_activity = False
586
 
 
587
 
    def stopTestRun(self):
588
 
        # called when the tests that are going to run have run
589
 
        self.pb.clear()
590
 
        self.pb.finished()
591
 
        super(TextTestResult, self).stopTestRun()
592
 
 
593
 
    def report_tests_starting(self):
594
 
        super(TextTestResult, self).report_tests_starting()
 
398
 
 
399
    def report_starting(self):
595
400
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
596
401
 
597
402
    def _progress_prefix_text(self):
604
409
        ##     a += ', %d skip' % self.skip_count
605
410
        ## if self.known_failure_count:
606
411
        ##     a += '+%dX' % self.known_failure_count
607
 
        if self.num_tests:
 
412
        if self.num_tests is not None:
608
413
            a +='/%d' % self.num_tests
609
414
        a += ' in '
610
415
        runtime = time.time() - self._overall_start_time
612
417
            a += '%dm%ds' % (runtime / 60, runtime % 60)
613
418
        else:
614
419
            a += '%ds' % runtime
615
 
        total_fail_count = self.error_count + self.failure_count
616
 
        if total_fail_count:
617
 
            a += ', %d failed' % total_fail_count
618
 
        # if self.unsupported:
619
 
        #     a += ', %d missing' % len(self.unsupported)
 
420
        if self.error_count:
 
421
            a += ', %d err' % self.error_count
 
422
        if self.failure_count:
 
423
            a += ', %d fail' % self.failure_count
 
424
        if self.unsupported:
 
425
            a += ', %d missing' % len(self.unsupported)
620
426
        a += ']'
621
427
        return a
622
428
 
623
429
    def report_test_start(self, test):
 
430
        self.count += 1
624
431
        self.pb.update(
625
432
                self._progress_prefix_text()
626
433
                + ' '
630
437
        return self._shortened_test_description(test)
631
438
 
632
439
    def report_error(self, test, err):
633
 
        self.stream.write('ERROR: %s\n    %s\n' % (
 
440
        self.pb.note('ERROR: %s\n    %s\n',
634
441
            self._test_description(test),
635
442
            err[1],
636
 
            ))
 
443
            )
637
444
 
638
445
    def report_failure(self, test, err):
639
 
        self.stream.write('FAIL: %s\n    %s\n' % (
 
446
        self.pb.note('FAIL: %s\n    %s\n',
640
447
            self._test_description(test),
641
448
            err[1],
642
 
            ))
 
449
            )
643
450
 
644
451
    def report_known_failure(self, test, err):
645
 
        pass
646
 
 
647
 
    def report_unexpected_success(self, test, reason):
648
 
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
649
 
            self._test_description(test),
650
 
            "Unexpected success. Should have failed",
651
 
            reason,
652
 
            ))
 
452
        self.pb.note('XFAIL: %s\n%s\n',
 
453
            self._test_description(test), err[1])
653
454
 
654
455
    def report_skip(self, test, reason):
655
456
        pass
656
457
 
657
 
    def report_not_applicable(self, test, reason):
 
458
    def report_not_applicable(self, test, skip_excinfo):
658
459
        pass
659
460
 
660
461
    def report_unsupported(self, test, feature):
661
462
        """test cannot be run because feature is missing."""
662
463
 
 
464
    def report_cleaning_up(self):
 
465
        self.pb.update('Cleaning up')
 
466
 
 
467
    def finished(self):
 
468
        if not self._supplied_pb:
 
469
            self.pb.finished()
 
470
 
663
471
 
664
472
class VerboseTestResult(ExtendedTestResult):
665
473
    """Produce long output, with one line per test run plus times"""
672
480
            result = a_string
673
481
        return result.ljust(final_width)
674
482
 
675
 
    def report_tests_starting(self):
 
483
    def report_starting(self):
676
484
        self.stream.write('running %d tests...\n' % self.num_tests)
677
 
        super(VerboseTestResult, self).report_tests_starting()
678
485
 
679
486
    def report_test_start(self, test):
 
487
        self.count += 1
680
488
        name = self._shortened_test_description(test)
681
 
        width = osutils.terminal_width()
682
 
        if width is not None:
683
 
            # width needs space for 6 char status, plus 1 for slash, plus an
684
 
            # 11-char time string, plus a trailing blank
685
 
            # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on
686
 
            # space
687
 
            self.stream.write(self._ellipsize_to_right(name, width-18))
688
 
        else:
689
 
            self.stream.write(name)
 
489
        # width needs space for 6 char status, plus 1 for slash, plus 2 10-char
 
490
        # numbers, plus a trailing blank
 
491
        # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
 
492
        self.stream.write(self._ellipsize_to_right(name,
 
493
                          osutils.terminal_width()-30))
690
494
        self.stream.flush()
691
495
 
692
496
    def _error_summary(self, err):
694
498
        return '%s%s' % (indent, err[1])
695
499
 
696
500
    def report_error(self, test, err):
697
 
        self.stream.write('ERROR %s\n%s\n'
 
501
        self.stream.writeln('ERROR %s\n%s'
698
502
                % (self._testTimeString(test),
699
503
                   self._error_summary(err)))
700
504
 
701
505
    def report_failure(self, test, err):
702
 
        self.stream.write(' FAIL %s\n%s\n'
 
506
        self.stream.writeln(' FAIL %s\n%s'
703
507
                % (self._testTimeString(test),
704
508
                   self._error_summary(err)))
705
509
 
706
510
    def report_known_failure(self, test, err):
707
 
        self.stream.write('XFAIL %s\n%s\n'
 
511
        self.stream.writeln('XFAIL %s\n%s'
708
512
                % (self._testTimeString(test),
709
513
                   self._error_summary(err)))
710
514
 
711
 
    def report_unexpected_success(self, test, reason):
712
 
        self.stream.write(' FAIL %s\n%s: %s\n'
713
 
                % (self._testTimeString(test),
714
 
                   "Unexpected success. Should have failed",
715
 
                   reason))
716
 
 
717
515
    def report_success(self, test):
718
 
        self.stream.write('   OK %s\n' % self._testTimeString(test))
 
516
        self.stream.writeln('   OK %s' % self._testTimeString(test))
719
517
        for bench_called, stats in getattr(test, '_benchcalls', []):
720
 
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
 
518
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
721
519
            stats.pprint(file=self.stream)
722
520
        # flush the stream so that we get smooth output. This verbose mode is
723
521
        # used to show the output in PQM.
724
522
        self.stream.flush()
725
523
 
726
524
    def report_skip(self, test, reason):
727
 
        self.stream.write(' SKIP %s\n%s\n'
 
525
        self.stream.writeln(' SKIP %s\n%s'
728
526
                % (self._testTimeString(test), reason))
729
527
 
730
 
    def report_not_applicable(self, test, reason):
731
 
        self.stream.write('  N/A %s\n    %s\n'
732
 
                % (self._testTimeString(test), reason))
 
528
    def report_not_applicable(self, test, skip_excinfo):
 
529
        self.stream.writeln('  N/A %s\n%s'
 
530
                % (self._testTimeString(test),
 
531
                   self._error_summary(skip_excinfo)))
733
532
 
734
533
    def report_unsupported(self, test, feature):
735
534
        """test cannot be run because feature is missing."""
736
 
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
 
535
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
737
536
                %(self._testTimeString(test), feature))
738
537
 
739
538
 
745
544
                 descriptions=0,
746
545
                 verbosity=1,
747
546
                 bench_history=None,
 
547
                 list_only=False,
748
548
                 strict=False,
749
 
                 result_decorators=None,
750
549
                 ):
751
 
        """Create a TextTestRunner.
752
 
 
753
 
        :param result_decorators: An optional list of decorators to apply
754
 
            to the result object being used by the runner. Decorators are
755
 
            applied left to right - the first element in the list is the 
756
 
            innermost decorator.
757
 
        """
758
 
        # stream may know claim to know to write unicode strings, but in older
759
 
        # pythons this goes sufficiently wrong that it is a bad idea. (
760
 
        # specifically a built in file with encoding 'UTF-8' will still try
761
 
        # to encode using ascii.
762
 
        new_encoding = osutils.get_terminal_encoding()
763
 
        codec = codecs.lookup(new_encoding)
764
 
        if type(codec) is tuple:
765
 
            # Python 2.4
766
 
            encode = codec[0]
767
 
        else:
768
 
            encode = codec.encode
769
 
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
770
 
        #                so should swap to the plain codecs.StreamWriter
771
 
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
772
 
            "backslashreplace")
773
 
        stream.encoding = new_encoding
774
 
        self.stream = stream
 
550
        self.stream = unittest._WritelnDecorator(stream)
775
551
        self.descriptions = descriptions
776
552
        self.verbosity = verbosity
777
553
        self._bench_history = bench_history
 
554
        self.list_only = list_only
778
555
        self._strict = strict
779
 
        self._result_decorators = result_decorators or []
780
556
 
781
557
    def run(self, test):
782
558
        "Run the given test case or test suite."
 
559
        startTime = time.time()
783
560
        if self.verbosity == 1:
784
561
            result_class = TextTestResult
785
562
        elif self.verbosity >= 2:
786
563
            result_class = VerboseTestResult
787
 
        original_result = result_class(self.stream,
 
564
        result = result_class(self.stream,
788
565
                              self.descriptions,
789
566
                              self.verbosity,
790
567
                              bench_history=self._bench_history,
 
568
                              num_tests=test.countTestCases(),
791
569
                              strict=self._strict,
792
570
                              )
793
 
        # Signal to result objects that look at stop early policy to stop,
794
 
        original_result.stop_early = self.stop_on_failure
795
 
        result = original_result
796
 
        for decorator in self._result_decorators:
797
 
            result = decorator(result)
798
 
            result.stop_early = self.stop_on_failure
799
 
        result.startTestRun()
800
 
        try:
801
 
            test.run(result)
802
 
        finally:
803
 
            result.stopTestRun()
804
 
        # higher level code uses our extended protocol to determine
805
 
        # what exit code to give.
806
 
        return original_result
 
571
        result.stop_early = self.stop_on_failure
 
572
        result.report_starting()
 
573
        if self.list_only:
 
574
            if self.verbosity >= 2:
 
575
                self.stream.writeln("Listing tests only ...\n")
 
576
            run = 0
 
577
            for t in iter_suite_tests(test):
 
578
                self.stream.writeln("%s" % (t.id()))
 
579
                run += 1
 
580
            return None
 
581
        else:
 
582
            try:
 
583
                import testtools
 
584
            except ImportError:
 
585
                test.run(result)
 
586
            else:
 
587
                if isinstance(test, testtools.ConcurrentTestSuite):
 
588
                    # We need to catch bzr specific behaviors
 
589
                    test.run(BZRTransformingResult(result))
 
590
                else:
 
591
                    test.run(result)
 
592
            run = result.testsRun
 
593
            actionTaken = "Ran"
 
594
        stopTime = time.time()
 
595
        timeTaken = stopTime - startTime
 
596
        result.printErrors()
 
597
        self.stream.writeln(result.separator2)
 
598
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
599
                            run, run != 1 and "s" or "", timeTaken))
 
600
        self.stream.writeln()
 
601
        if not result.wasSuccessful():
 
602
            self.stream.write("FAILED (")
 
603
            failed, errored = map(len, (result.failures, result.errors))
 
604
            if failed:
 
605
                self.stream.write("failures=%d" % failed)
 
606
            if errored:
 
607
                if failed: self.stream.write(", ")
 
608
                self.stream.write("errors=%d" % errored)
 
609
            if result.known_failure_count:
 
610
                if failed or errored: self.stream.write(", ")
 
611
                self.stream.write("known_failure_count=%d" %
 
612
                    result.known_failure_count)
 
613
            self.stream.writeln(")")
 
614
        else:
 
615
            if result.known_failure_count:
 
616
                self.stream.writeln("OK (known_failures=%d)" %
 
617
                    result.known_failure_count)
 
618
            else:
 
619
                self.stream.writeln("OK")
 
620
        if result.skip_count > 0:
 
621
            skipped = result.skip_count
 
622
            self.stream.writeln('%d test%s skipped' %
 
623
                                (skipped, skipped != 1 and "s" or ""))
 
624
        if result.unsupported:
 
625
            for feature, count in sorted(result.unsupported.items()):
 
626
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
627
                    (feature, count))
 
628
        result.finished()
 
629
        return result
807
630
 
808
631
 
809
632
def iter_suite_tests(suite):
819
642
                        % (type(suite), suite))
820
643
 
821
644
 
822
 
TestSkipped = testtools.testcase.TestSkipped
 
645
class TestSkipped(Exception):
 
646
    """Indicates that a test was intentionally skipped, rather than failing."""
823
647
 
824
648
 
825
649
class TestNotApplicable(TestSkipped):
831
655
    """
832
656
 
833
657
 
834
 
# traceback._some_str fails to format exceptions that have the default
835
 
# __str__ which does an implicit ascii conversion. However, repr() on those
836
 
# objects works, for all that its not quite what the doctor may have ordered.
837
 
def _clever_some_str(value):
838
 
    try:
839
 
        return str(value)
840
 
    except:
841
 
        try:
842
 
            return repr(value).replace('\\n', '\n')
843
 
        except:
844
 
            return '<unprintable %s object>' % type(value).__name__
845
 
 
846
 
traceback._some_str = _clever_some_str
847
 
 
848
 
 
849
 
# deprecated - use self.knownFailure(), or self.expectFailure.
850
 
KnownFailure = testtools.testcase._ExpectedFailure
 
658
class KnownFailure(AssertionError):
 
659
    """Indicates that a test failed in a precisely expected manner.
 
660
 
 
661
    Such failures dont block the whole test suite from passing because they are
 
662
    indicators of partially completed code or of future work. We have an
 
663
    explicit error for them so that we can ensure that they are always visible:
 
664
    KnownFailures are always shown in the output of bzr selftest.
 
665
    """
851
666
 
852
667
 
853
668
class UnavailableFeature(Exception):
854
669
    """A feature required for this test was not available.
855
670
 
856
 
    This can be considered a specialised form of SkippedTest.
857
 
 
858
671
    The feature should be used to construct the exception.
859
672
    """
860
673
 
861
674
 
 
675
class CommandFailed(Exception):
 
676
    pass
 
677
 
 
678
 
862
679
class StringIOWrapper(object):
863
680
    """A wrapper around cStringIO which just adds an encoding attribute.
864
681
 
885
702
            return setattr(self._cstring, name, val)
886
703
 
887
704
 
888
 
class TestUIFactory(TextUIFactory):
 
705
class TestUIFactory(ui.CLIUIFactory):
889
706
    """A UI Factory for testing.
890
707
 
891
708
    Hide the progress bar but emit note()s.
892
709
    Redirect stdin.
893
710
    Allows get_password to be tested without real tty attached.
894
 
 
895
 
    See also CannedInputUIFactory which lets you provide programmatic input in
896
 
    a structured way.
897
711
    """
898
 
    # TODO: Capture progress events at the model level and allow them to be
899
 
    # observed by tests that care.
900
 
    #
901
 
    # XXX: Should probably unify more with CannedInputUIFactory or a
902
 
    # particular configuration of TextUIFactory, or otherwise have a clearer
903
 
    # idea of how they're supposed to be different.
904
 
    # See https://bugs.launchpad.net/bzr/+bug/408213
905
712
 
906
713
    def __init__(self, stdout=None, stderr=None, stdin=None):
907
714
        if stdin is not None:
912
719
            stdin = StringIOWrapper(stdin)
913
720
        super(TestUIFactory, self).__init__(stdin, stdout, stderr)
914
721
 
 
722
    def clear(self):
 
723
        """See progress.ProgressBar.clear()."""
 
724
 
 
725
    def clear_term(self):
 
726
        """See progress.ProgressBar.clear_term()."""
 
727
 
 
728
    def finished(self):
 
729
        """See progress.ProgressBar.finished()."""
 
730
 
 
731
    def note(self, fmt_string, *args):
 
732
        """See progress.ProgressBar.note()."""
 
733
        if args:
 
734
            fmt_string = fmt_string % args
 
735
        self.stdout.write(fmt_string + "\n")
 
736
 
 
737
    def progress_bar(self):
 
738
        return self
 
739
 
 
740
    def nested_progress_bar(self):
 
741
        return self
 
742
 
 
743
    def update(self, message, count=None, total=None):
 
744
        """See progress.ProgressBar.update()."""
 
745
 
915
746
    def get_non_echoed_password(self):
916
747
        """Get password from stdin without trying to handle the echo mode"""
917
748
        password = self.stdin.readline()
921
752
            password = password[:-1]
922
753
        return password
923
754
 
924
 
    def make_progress_view(self):
925
 
        return NullProgressView()
926
 
 
927
 
 
928
 
def isolated_doctest_setUp(test):
929
 
    override_os_environ(test)
930
 
 
931
 
 
932
 
def isolated_doctest_tearDown(test):
933
 
    restore_os_environ(test)
934
 
 
935
 
 
936
 
def IsolatedDocTestSuite(*args, **kwargs):
937
 
    """Overrides doctest.DocTestSuite to handle isolation.
938
 
 
939
 
    The method is really a factory and users are expected to use it as such.
940
 
    """
941
 
 
942
 
    kwargs['setUp'] = isolated_doctest_setUp
943
 
    kwargs['tearDown'] = isolated_doctest_tearDown
944
 
    return doctest.DocTestSuite(*args, **kwargs)
945
 
 
946
 
 
947
 
class TestCase(testtools.TestCase):
 
755
 
 
756
class TestCase(unittest.TestCase):
948
757
    """Base class for bzr unit tests.
949
758
 
950
759
    Tests that need access to disk resources should subclass
960
769
    routine, and to build and check bzr trees.
961
770
 
962
771
    In addition to the usual method of overriding tearDown(), this class also
963
 
    allows subclasses to register cleanup functions via addCleanup, which are
 
772
    allows subclasses to register functions into the _cleanups list, which is
964
773
    run in order as the object is torn down.  It's less likely this will be
965
774
    accidentally overlooked.
966
775
    """
967
776
 
968
 
    _log_file = None
 
777
    _active_threads = None
 
778
    _leaking_threads_tests = 0
 
779
    _first_thread_leaker_id = None
 
780
    _log_file_name = None
 
781
    _log_contents = ''
 
782
    _keep_log_file = False
969
783
    # record lsprof data when performing benchmark calls.
970
784
    _gather_lsprof_in_benchmarks = False
 
785
    attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
 
786
                     '_log_contents', '_log_file_name', '_benchtime',
 
787
                     '_TestCase__testMethodName', '_TestCase__testMethodDoc',)
971
788
 
972
789
    def __init__(self, methodName='testMethod'):
973
790
        super(TestCase, self).__init__(methodName)
974
 
        self._directory_isolation = True
975
 
        self.exception_handlers.insert(0,
976
 
            (UnavailableFeature, self._do_unsupported_or_skip))
977
 
        self.exception_handlers.insert(0,
978
 
            (TestNotApplicable, self._do_not_applicable))
 
791
        self._cleanups = []
 
792
        self._bzr_test_setUp_run = False
 
793
        self._bzr_test_tearDown_run = False
979
794
 
980
795
    def setUp(self):
981
 
        super(TestCase, self).setUp()
982
 
        for feature in getattr(self, '_test_needs_features', []):
983
 
            self.requireFeature(feature)
 
796
        unittest.TestCase.setUp(self)
 
797
        self._bzr_test_setUp_run = True
984
798
        self._cleanEnvironment()
985
799
        self._silenceUI()
986
800
        self._startLogFile()
987
801
        self._benchcalls = []
988
802
        self._benchtime = None
989
803
        self._clear_hooks()
990
 
        self._track_transports()
 
804
        # Track locks - needs to be called before _clear_debug_flags.
991
805
        self._track_locks()
992
806
        self._clear_debug_flags()
993
 
        # Isolate global verbosity level, to make sure it's reproducible
994
 
        # between tests.  We should get rid of this altogether: bug 656694. --
995
 
        # mbp 20101008
996
 
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
997
 
        # Isolate config option expansion until its default value for bzrlib is
998
 
        # settled on or a the FIXME associated with _get_expand_default_value
999
 
        # is addressed -- vila 20110219
1000
 
        self.overrideAttr(config, '_expand_default_value', None)
1001
 
        self._log_files = set()
1002
 
        # Each key in the ``_counters`` dict holds a value for a different
1003
 
        # counter. When the test ends, addDetail() should be used to output the
1004
 
        # counter values. This happens in install_counter_hook().
1005
 
        self._counters = {}
1006
 
        if 'config_stats' in selftest_debug_flags:
1007
 
            self._install_config_stats_hooks()
 
807
        TestCase._active_threads = threading.activeCount()
 
808
        self.addCleanup(self._check_leaked_threads)
1008
809
 
1009
810
    def debug(self):
1010
811
        # debug a frame up.
1011
812
        import pdb
1012
813
        pdb.Pdb().set_trace(sys._getframe().f_back)
1013
814
 
1014
 
    def discardDetail(self, name):
1015
 
        """Extend the addDetail, getDetails api so we can remove a detail.
1016
 
 
1017
 
        eg. bzr always adds the 'log' detail at startup, but we don't want to
1018
 
        include it for skipped, xfail, etc tests.
1019
 
 
1020
 
        It is safe to call this for a detail that doesn't exist, in case this
1021
 
        gets called multiple times.
1022
 
        """
1023
 
        # We cheat. details is stored in __details which means we shouldn't
1024
 
        # touch it. but getDetails() returns the dict directly, so we can
1025
 
        # mutate it.
1026
 
        details = self.getDetails()
1027
 
        if name in details:
1028
 
            del details[name]
1029
 
 
1030
 
    def install_counter_hook(self, hooks, name, counter_name=None):
1031
 
        """Install a counting hook.
1032
 
 
1033
 
        Any hook can be counted as long as it doesn't need to return a value.
1034
 
 
1035
 
        :param hooks: Where the hook should be installed.
1036
 
 
1037
 
        :param name: The hook name that will be counted.
1038
 
 
1039
 
        :param counter_name: The counter identifier in ``_counters``, defaults
1040
 
            to ``name``.
1041
 
        """
1042
 
        _counters = self._counters # Avoid closing over self
1043
 
        if counter_name is None:
1044
 
            counter_name = name
1045
 
        if _counters.has_key(counter_name):
1046
 
            raise AssertionError('%s is already used as a counter name'
1047
 
                                  % (counter_name,))
1048
 
        _counters[counter_name] = 0
1049
 
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
1050
 
            lambda: ['%d' % (_counters[counter_name],)]))
1051
 
        def increment_counter(*args, **kwargs):
1052
 
            _counters[counter_name] += 1
1053
 
        label = 'count %s calls' % (counter_name,)
1054
 
        hooks.install_named_hook(name, increment_counter, label)
1055
 
        self.addCleanup(hooks.uninstall_named_hook, name, label)
1056
 
 
1057
 
    def _install_config_stats_hooks(self):
1058
 
        """Install config hooks to count hook calls.
1059
 
 
1060
 
        """
1061
 
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
1062
 
            self.install_counter_hook(config.ConfigHooks, hook_name,
1063
 
                                       'config.%s' % (hook_name,))
1064
 
 
1065
 
        # The OldConfigHooks are private and need special handling to protect
1066
 
        # against recursive tests (tests that run other tests), so we just do
1067
 
        # manually what registering them into _builtin_known_hooks will provide
1068
 
        # us.
1069
 
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
1070
 
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
1071
 
            self.install_counter_hook(config.OldConfigHooks, hook_name,
1072
 
                                      'old_config.%s' % (hook_name,))
 
815
    def _check_leaked_threads(self):
 
816
        active = threading.activeCount()
 
817
        leaked_threads = active - TestCase._active_threads
 
818
        TestCase._active_threads = active
 
819
        if leaked_threads:
 
820
            TestCase._leaking_threads_tests += 1
 
821
            if TestCase._first_thread_leaker_id is None:
 
822
                TestCase._first_thread_leaker_id = self.id()
1073
823
 
1074
824
    def _clear_debug_flags(self):
1075
825
        """Prevent externally set debug flags affecting tests.
1077
827
        Tests that want to use debug flags can just set them in the
1078
828
        debug_flags set during setup/teardown.
1079
829
        """
1080
 
        # Start with a copy of the current debug flags we can safely modify.
1081
 
        self.overrideAttr(debug, 'debug_flags', set(debug.debug_flags))
 
830
        self._preserved_debug_flags = set(debug.debug_flags)
1082
831
        if 'allow_debug' not in selftest_debug_flags:
1083
832
            debug.debug_flags.clear()
1084
 
        if 'disable_lock_checks' not in selftest_debug_flags:
1085
 
            debug.debug_flags.add('strict_locks')
 
833
        self.addCleanup(self._restore_debug_flags)
1086
834
 
1087
835
    def _clear_hooks(self):
1088
836
        # prevent hooks affecting tests
1089
 
        known_hooks = hooks.known_hooks
1090
837
        self._preserved_hooks = {}
1091
 
        for key, (parent, name) in known_hooks.iter_parent_objects():
1092
 
            current_hooks = getattr(parent, name)
 
838
        for key, factory in hooks.known_hooks.items():
 
839
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
 
840
            current_hooks = hooks.known_hooks_key_to_object(key)
1093
841
            self._preserved_hooks[parent] = (name, current_hooks)
1094
 
        self._preserved_lazy_hooks = hooks._lazy_hooks
1095
 
        hooks._lazy_hooks = {}
1096
842
        self.addCleanup(self._restoreHooks)
1097
 
        for key, (parent, name) in known_hooks.iter_parent_objects():
1098
 
            factory = known_hooks.get(key)
 
843
        for key, factory in hooks.known_hooks.items():
 
844
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
1099
845
            setattr(parent, name, factory())
1100
846
        # this hook should always be installed
1101
847
        request._install_hook()
1102
848
 
1103
 
    def disable_directory_isolation(self):
1104
 
        """Turn off directory isolation checks."""
1105
 
        self._directory_isolation = False
1106
 
 
1107
 
    def enable_directory_isolation(self):
1108
 
        """Enable directory isolation checks."""
1109
 
        self._directory_isolation = True
1110
 
 
1111
849
    def _silenceUI(self):
1112
850
        """Turn off UI for duration of test"""
1113
851
        # by default the UI is off; tests can turn it on if they want it.
1114
 
        self.overrideAttr(ui, 'ui_factory', ui.SilentUIFactory())
 
852
        saved = ui.ui_factory
 
853
        def _restore():
 
854
            ui.ui_factory = saved
 
855
        ui.ui_factory = ui.SilentUIFactory()
 
856
        self.addCleanup(_restore)
1115
857
 
1116
858
    def _check_locks(self):
1117
859
        """Check that all lock take/release actions have been paired."""
1118
 
        # We always check for mismatched locks. If a mismatch is found, we
1119
 
        # fail unless -Edisable_lock_checks is supplied to selftest, in which
1120
 
        # case we just print a warning.
 
860
        # once we have fixed all the current lock problems, we can change the
 
861
        # following code to always check for mismatched locks, but only do
 
862
        # traceback showing with -Dlock (self._lock_check_thorough is True).
 
863
        # For now, because the test suite will fail, we only assert that lock
 
864
        # matching has occured with -Dlock.
1121
865
        # unhook:
1122
866
        acquired_locks = [lock for action, lock in self._lock_actions
1123
867
                          if action == 'acquired']
1130
874
        # break some locks on purpose and should be taken into account by
1131
875
        # considering that breaking a lock is just a dirty way of releasing it.
1132
876
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
1133
 
            message = (
1134
 
                'Different number of acquired and '
1135
 
                'released or broken locks.\n'
1136
 
                'acquired=%s\n'
1137
 
                'released=%s\n'
1138
 
                'broken=%s\n' %
1139
 
                (acquired_locks, released_locks, broken_locks))
 
877
            message = ('Different number of acquired and '
 
878
                       'released or broken locks. (%s, %s + %s)' %
 
879
                       (acquired_locks, released_locks, broken_locks))
1140
880
            if not self._lock_check_thorough:
1141
881
                # Rather than fail, just warn
1142
882
                print "Broken test %s: %s" % (self, message)
1146
886
    def _track_locks(self):
1147
887
        """Track lock activity during tests."""
1148
888
        self._lock_actions = []
1149
 
        if 'disable_lock_checks' in selftest_debug_flags:
1150
 
            self._lock_check_thorough = False
1151
 
        else:
1152
 
            self._lock_check_thorough = True
1153
 
 
 
889
        self._lock_check_thorough = 'lock' not in debug.debug_flags
1154
890
        self.addCleanup(self._check_locks)
1155
891
        _mod_lock.Lock.hooks.install_named_hook('lock_acquired',
1156
892
                                                self._lock_acquired, None)
1168
904
    def _lock_broken(self, result):
1169
905
        self._lock_actions.append(('broken', result))
1170
906
 
1171
 
    def permit_dir(self, name):
1172
 
        """Permit a directory to be used by this test. See permit_url."""
1173
 
        name_transport = _mod_transport.get_transport_from_path(name)
1174
 
        self.permit_url(name)
1175
 
        self.permit_url(name_transport.base)
1176
 
 
1177
 
    def permit_url(self, url):
1178
 
        """Declare that url is an ok url to use in this test.
1179
 
        
1180
 
        Do this for memory transports, temporary test directory etc.
1181
 
        
1182
 
        Do not do this for the current working directory, /tmp, or any other
1183
 
        preexisting non isolated url.
1184
 
        """
1185
 
        if not url.endswith('/'):
1186
 
            url += '/'
1187
 
        self._bzr_selftest_roots.append(url)
1188
 
 
1189
 
    def permit_source_tree_branch_repo(self):
1190
 
        """Permit the source tree bzr is running from to be opened.
1191
 
 
1192
 
        Some code such as bzrlib.version attempts to read from the bzr branch
1193
 
        that bzr is executing from (if any). This method permits that directory
1194
 
        to be used in the test suite.
1195
 
        """
1196
 
        path = self.get_source_path()
1197
 
        self.record_directory_isolation()
1198
 
        try:
1199
 
            try:
1200
 
                workingtree.WorkingTree.open(path)
1201
 
            except (errors.NotBranchError, errors.NoWorkingTree):
1202
 
                raise TestSkipped('Needs a working tree of bzr sources')
1203
 
        finally:
1204
 
            self.enable_directory_isolation()
1205
 
 
1206
 
    def _preopen_isolate_transport(self, transport):
1207
 
        """Check that all transport openings are done in the test work area."""
1208
 
        while isinstance(transport, pathfilter.PathFilteringTransport):
1209
 
            # Unwrap pathfiltered transports
1210
 
            transport = transport.server.backing_transport.clone(
1211
 
                transport._filter('.'))
1212
 
        url = transport.base
1213
 
        # ReadonlySmartTCPServer_for_testing decorates the backing transport
1214
 
        # urls it is given by prepending readonly+. This is appropriate as the
1215
 
        # client shouldn't know that the server is readonly (or not readonly).
1216
 
        # We could register all servers twice, with readonly+ prepending, but
1217
 
        # that makes for a long list; this is about the same but easier to
1218
 
        # read.
1219
 
        if url.startswith('readonly+'):
1220
 
            url = url[len('readonly+'):]
1221
 
        self._preopen_isolate_url(url)
1222
 
 
1223
 
    def _preopen_isolate_url(self, url):
1224
 
        if not self._directory_isolation:
1225
 
            return
1226
 
        if self._directory_isolation == 'record':
1227
 
            self._bzr_selftest_roots.append(url)
1228
 
            return
1229
 
        # This prevents all transports, including e.g. sftp ones backed on disk
1230
 
        # from working unless they are explicitly granted permission. We then
1231
 
        # depend on the code that sets up test transports to check that they are
1232
 
        # appropriately isolated and enable their use by calling
1233
 
        # self.permit_transport()
1234
 
        if not osutils.is_inside_any(self._bzr_selftest_roots, url):
1235
 
            raise errors.BzrError("Attempt to escape test isolation: %r %r"
1236
 
                % (url, self._bzr_selftest_roots))
1237
 
 
1238
 
    def record_directory_isolation(self):
1239
 
        """Gather accessed directories to permit later access.
1240
 
        
1241
 
        This is used for tests that access the branch bzr is running from.
1242
 
        """
1243
 
        self._directory_isolation = "record"
1244
 
 
1245
 
    def start_server(self, transport_server, backing_server=None):
1246
 
        """Start transport_server for this test.
1247
 
 
1248
 
        This starts the server, registers a cleanup for it and permits the
1249
 
        server's urls to be used.
1250
 
        """
1251
 
        if backing_server is None:
1252
 
            transport_server.start_server()
1253
 
        else:
1254
 
            transport_server.start_server(backing_server)
1255
 
        self.addCleanup(transport_server.stop_server)
1256
 
        # Obtain a real transport because if the server supplies a password, it
1257
 
        # will be hidden from the base on the client side.
1258
 
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1259
 
        # Some transport servers effectively chroot the backing transport;
1260
 
        # others like SFTPServer don't - users of the transport can walk up the
1261
 
        # transport to read the entire backing transport. This wouldn't matter
1262
 
        # except that the workdir tests are given - and that they expect the
1263
 
        # server's url to point at - is one directory under the safety net. So
1264
 
        # Branch operations into the transport will attempt to walk up one
1265
 
        # directory. Chrooting all servers would avoid this but also mean that
1266
 
        # we wouldn't be testing directly against non-root urls. Alternatively
1267
 
        # getting the test framework to start the server with a backing server
1268
 
        # at the actual safety net directory would work too, but this then
1269
 
        # means that the self.get_url/self.get_transport methods would need
1270
 
        # to transform all their results. On balance its cleaner to handle it
1271
 
        # here, and permit a higher url when we have one of these transports.
1272
 
        if t.base.endswith('/work/'):
1273
 
            # we have safety net/test root/work
1274
 
            t = t.clone('../..')
1275
 
        elif isinstance(transport_server,
1276
 
                        test_server.SmartTCPServer_for_testing):
1277
 
            # The smart server adds a path similar to work, which is traversed
1278
 
            # up from by the client. But the server is chrooted - the actual
1279
 
            # backing transport is not escaped from, and VFS requests to the
1280
 
            # root will error (because they try to escape the chroot).
1281
 
            t2 = t.clone('..')
1282
 
            while t2.base != t.base:
1283
 
                t = t2
1284
 
                t2 = t.clone('..')
1285
 
        self.permit_url(t.base)
1286
 
 
1287
 
    def _track_transports(self):
1288
 
        """Install checks for transport usage."""
1289
 
        # TestCase has no safe place it can write to.
1290
 
        self._bzr_selftest_roots = []
1291
 
        # Currently the easiest way to be sure that nothing is going on is to
1292
 
        # hook into bzr dir opening. This leaves a small window of error for
1293
 
        # transport tests, but they are well known, and we can improve on this
1294
 
        # step.
1295
 
        bzrdir.BzrDir.hooks.install_named_hook("pre_open",
1296
 
            self._preopen_isolate_transport, "Check bzr directories are safe.")
1297
 
 
1298
907
    def _ndiff_strings(self, a, b):
1299
908
        """Return ndiff between two strings containing lines.
1300
909
 
1317
926
        except UnicodeError, e:
1318
927
            # If we can't compare without getting a UnicodeError, then
1319
928
            # obviously they are different
1320
 
            trace.mutter('UnicodeError: %s', e)
 
929
            mutter('UnicodeError: %s', e)
1321
930
        if message:
1322
931
            message += '\n'
1323
932
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1324
933
            % (message,
1325
 
               pprint.pformat(a), pprint.pformat(b)))
 
934
               pformat(a), pformat(b)))
1326
935
 
1327
936
    assertEquals = assertEqual
1328
937
 
1337
946
            return
1338
947
        if message is None:
1339
948
            message = "texts not equal:\n"
 
949
        if a == b + '\n':
 
950
            message = 'first string is missing a final newline.\n'
1340
951
        if a + '\n' == b:
1341
 
            message = 'first string is missing a final newline.\n'
1342
 
        if a == b + '\n':
1343
952
            message = 'second string is missing a final newline.\n'
1344
953
        raise AssertionError(message +
1345
954
                             self._ndiff_strings(a, b))
1356
965
        :raises AssertionError: If the expected and actual stat values differ
1357
966
            other than by atime.
1358
967
        """
1359
 
        self.assertEqual(expected.st_size, actual.st_size,
1360
 
                         'st_size did not match')
1361
 
        self.assertEqual(expected.st_mtime, actual.st_mtime,
1362
 
                         'st_mtime did not match')
1363
 
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1364
 
                         'st_ctime did not match')
1365
 
        if sys.platform == 'win32':
1366
 
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1367
 
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
1368
 
            # odd. We just force it to always be 0 to avoid any problems.
1369
 
            self.assertEqual(0, expected.st_dev)
1370
 
            self.assertEqual(0, actual.st_dev)
1371
 
            self.assertEqual(0, expected.st_ino)
1372
 
            self.assertEqual(0, actual.st_ino)
1373
 
        else:
1374
 
            self.assertEqual(expected.st_dev, actual.st_dev,
1375
 
                             'st_dev did not match')
1376
 
            self.assertEqual(expected.st_ino, actual.st_ino,
1377
 
                             'st_ino did not match')
1378
 
        self.assertEqual(expected.st_mode, actual.st_mode,
1379
 
                         'st_mode did not match')
 
968
        self.assertEqual(expected.st_size, actual.st_size)
 
969
        self.assertEqual(expected.st_mtime, actual.st_mtime)
 
970
        self.assertEqual(expected.st_ctime, actual.st_ctime)
 
971
        self.assertEqual(expected.st_dev, actual.st_dev)
 
972
        self.assertEqual(expected.st_ino, actual.st_ino)
 
973
        self.assertEqual(expected.st_mode, actual.st_mode)
1380
974
 
1381
975
    def assertLength(self, length, obj_with_len):
1382
976
        """Assert that obj_with_len is of length length."""
1384
978
            self.fail("Incorrect length: wanted %d, got %d for %r" % (
1385
979
                length, len(obj_with_len), obj_with_len))
1386
980
 
1387
 
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1388
 
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1389
 
        """
1390
 
        captured = []
1391
 
        orig_log_exception_quietly = trace.log_exception_quietly
1392
 
        try:
1393
 
            def capture():
1394
 
                orig_log_exception_quietly()
1395
 
                captured.append(sys.exc_info()[1])
1396
 
            trace.log_exception_quietly = capture
1397
 
            func(*args, **kwargs)
1398
 
        finally:
1399
 
            trace.log_exception_quietly = orig_log_exception_quietly
1400
 
        self.assertLength(1, captured)
1401
 
        err = captured[0]
1402
 
        self.assertIsInstance(err, exception_class)
1403
 
        return err
1404
 
 
1405
981
    def assertPositive(self, val):
1406
982
        """Assert that val is greater than 0."""
1407
983
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
1437
1013
            raise AssertionError('pattern "%s" found in "%s"'
1438
1014
                    % (needle_re, haystack))
1439
1015
 
1440
 
    def assertContainsString(self, haystack, needle):
1441
 
        if haystack.find(needle) == -1:
1442
 
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1443
 
 
1444
 
    def assertNotContainsString(self, haystack, needle):
1445
 
        if haystack.find(needle) != -1:
1446
 
            self.fail("string %r found in '''%s'''" % (needle, haystack))
1447
 
 
1448
1016
    def assertSubset(self, sublist, superlist):
1449
1017
        """Assert that every entry in sublist is present in superlist."""
1450
1018
        missing = set(sublist) - set(superlist)
1525
1093
                         osutils.realpath(path2),
1526
1094
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1527
1095
 
1528
 
    def assertIsInstance(self, obj, kls, msg=None):
1529
 
        """Fail if obj is not an instance of kls
1530
 
        
1531
 
        :param msg: Supplementary message to show if the assertion fails.
1532
 
        """
 
1096
    def assertIsInstance(self, obj, kls):
 
1097
        """Fail if obj is not an instance of kls"""
1533
1098
        if not isinstance(obj, kls):
1534
 
            m = "%r is an instance of %s rather than %s" % (
1535
 
                obj, obj.__class__, kls)
1536
 
            if msg:
1537
 
                m += ": " + msg
1538
 
            self.fail(m)
 
1099
            self.fail("%r is an instance of %s rather than %s" % (
 
1100
                obj, obj.__class__, kls))
 
1101
 
 
1102
    def expectFailure(self, reason, assertion, *args, **kwargs):
 
1103
        """Invoke a test, expecting it to fail for the given reason.
 
1104
 
 
1105
        This is for assertions that ought to succeed, but currently fail.
 
1106
        (The failure is *expected* but not *wanted*.)  Please be very precise
 
1107
        about the failure you're expecting.  If a new bug is introduced,
 
1108
        AssertionError should be raised, not KnownFailure.
 
1109
 
 
1110
        Frequently, expectFailure should be followed by an opposite assertion.
 
1111
        See example below.
 
1112
 
 
1113
        Intended to be used with a callable that raises AssertionError as the
 
1114
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
 
1115
 
 
1116
        Raises KnownFailure if the test fails.  Raises AssertionError if the
 
1117
        test succeeds.
 
1118
 
 
1119
        example usage::
 
1120
 
 
1121
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
 
1122
                             dynamic_val)
 
1123
          self.assertEqual(42, dynamic_val)
 
1124
 
 
1125
          This means that a dynamic_val of 54 will cause the test to raise
 
1126
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
 
1127
          only a dynamic_val of 42 will allow the test to pass.  Anything other
 
1128
          than 54 or 42 will cause an AssertionError.
 
1129
        """
 
1130
        try:
 
1131
            assertion(*args, **kwargs)
 
1132
        except AssertionError:
 
1133
            raise KnownFailure(reason)
 
1134
        else:
 
1135
            self.fail('Unexpected success.  Should have failed: %s' % reason)
1539
1136
 
1540
1137
    def assertFileEqual(self, content, path):
1541
1138
        """Fail if path does not contain 'content'."""
1542
 
        self.assertPathExists(path)
 
1139
        self.failUnlessExists(path)
1543
1140
        f = file(path, 'rb')
1544
1141
        try:
1545
1142
            s = f.read()
1547
1144
            f.close()
1548
1145
        self.assertEqualDiff(content, s)
1549
1146
 
1550
 
    def assertDocstring(self, expected_docstring, obj):
1551
 
        """Fail if obj does not have expected_docstring"""
1552
 
        if __doc__ is None:
1553
 
            # With -OO the docstring should be None instead
1554
 
            self.assertIs(obj.__doc__, None)
1555
 
        else:
1556
 
            self.assertEqual(expected_docstring, obj.__doc__)
1557
 
 
1558
 
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1559
1147
    def failUnlessExists(self, path):
1560
 
        return self.assertPathExists(path)
1561
 
 
1562
 
    def assertPathExists(self, path):
1563
1148
        """Fail unless path or paths, which may be abs or relative, exist."""
1564
1149
        if not isinstance(path, basestring):
1565
1150
            for p in path:
1566
 
                self.assertPathExists(p)
 
1151
                self.failUnlessExists(p)
1567
1152
        else:
1568
 
            self.assertTrue(osutils.lexists(path),
1569
 
                path + " does not exist")
 
1153
            self.failUnless(osutils.lexists(path),path+" does not exist")
1570
1154
 
1571
 
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1572
1155
    def failIfExists(self, path):
1573
 
        return self.assertPathDoesNotExist(path)
1574
 
 
1575
 
    def assertPathDoesNotExist(self, path):
1576
1156
        """Fail if path or paths, which may be abs or relative, exist."""
1577
1157
        if not isinstance(path, basestring):
1578
1158
            for p in path:
1579
 
                self.assertPathDoesNotExist(p)
 
1159
                self.failIfExists(p)
1580
1160
        else:
1581
 
            self.assertFalse(osutils.lexists(path),
1582
 
                path + " exists")
 
1161
            self.failIf(osutils.lexists(path),path+" exists")
1583
1162
 
1584
1163
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1585
1164
        """A helper for callDeprecated and applyDeprecated.
1611
1190
        not other callers that go direct to the warning module.
1612
1191
 
1613
1192
        To test that a deprecated method raises an error, do something like
1614
 
        this (remember that both assertRaises and applyDeprecated delays *args
1615
 
        and **kwargs passing)::
 
1193
        this::
1616
1194
 
1617
1195
            self.assertRaises(errors.ReservedId,
1618
1196
                self.applyDeprecated,
1700
1278
 
1701
1279
        The file is removed as the test is torn down.
1702
1280
        """
1703
 
        pseudo_log_file = StringIO()
1704
 
        def _get_log_contents_for_weird_testtools_api():
1705
 
            return [pseudo_log_file.getvalue().decode(
1706
 
                "utf-8", "replace").encode("utf-8")]
1707
 
        self.addDetail("log", content.Content(content.ContentType("text",
1708
 
            "plain", {"charset": "utf8"}),
1709
 
            _get_log_contents_for_weird_testtools_api))
1710
 
        self._log_file = pseudo_log_file
1711
 
        self._log_memento = trace.push_log_file(self._log_file)
 
1281
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
 
1282
        self._log_file = os.fdopen(fileno, 'w+')
 
1283
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
 
1284
        self._log_file_name = name
1712
1285
        self.addCleanup(self._finishLogFile)
1713
1286
 
1714
1287
    def _finishLogFile(self):
1715
1288
        """Finished with the log file.
1716
1289
 
1717
 
        Close the file and delete it.
1718
 
        """
1719
 
        if trace._trace_file:
1720
 
            # flush the log file, to get all content
1721
 
            trace._trace_file.flush()
1722
 
        trace.pop_log_file(self._log_memento)
1723
 
 
1724
 
    def thisFailsStrictLockCheck(self):
1725
 
        """It is known that this test would fail with -Dstrict_locks.
1726
 
 
1727
 
        By default, all tests are run with strict lock checking unless
1728
 
        -Edisable_lock_checks is supplied. However there are some tests which
1729
 
        we know fail strict locks at this point that have not been fixed.
1730
 
        They should call this function to disable the strict checking.
1731
 
 
1732
 
        This should be used sparingly, it is much better to fix the locking
1733
 
        issues rather than papering over the problem by calling this function.
1734
 
        """
1735
 
        debug.debug_flags.discard('strict_locks')
1736
 
 
1737
 
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1738
 
        """Overrides an object attribute restoring it after the test.
1739
 
 
1740
 
        :note: This should be used with discretion; you should think about
1741
 
        whether it's better to make the code testable without monkey-patching.
1742
 
 
1743
 
        :param obj: The object that will be mutated.
1744
 
 
1745
 
        :param attr_name: The attribute name we want to preserve/override in
1746
 
            the object.
1747
 
 
1748
 
        :param new: The optional value we want to set the attribute to.
1749
 
 
1750
 
        :returns: The actual attr value.
1751
 
        """
1752
 
        value = getattr(obj, attr_name)
1753
 
        # The actual value is captured by the call below
1754
 
        self.addCleanup(setattr, obj, attr_name, value)
1755
 
        if new is not _unitialized_attr:
1756
 
            setattr(obj, attr_name, new)
1757
 
        return value
1758
 
 
1759
 
    def overrideEnv(self, name, new):
1760
 
        """Set an environment variable, and reset it after the test.
1761
 
 
1762
 
        :param name: The environment variable name.
1763
 
 
1764
 
        :param new: The value to set the variable to. If None, the 
1765
 
            variable is deleted from the environment.
1766
 
 
1767
 
        :returns: The actual variable value.
1768
 
        """
1769
 
        value = osutils.set_or_unset_env(name, new)
1770
 
        self.addCleanup(osutils.set_or_unset_env, name, value)
1771
 
        return value
1772
 
 
1773
 
    def recordCalls(self, obj, attr_name):
1774
 
        """Monkeypatch in a wrapper that will record calls.
1775
 
 
1776
 
        The monkeypatch is automatically removed when the test concludes.
1777
 
 
1778
 
        :param obj: The namespace holding the reference to be replaced;
1779
 
            typically a module, class, or object.
1780
 
        :param attr_name: A string for the name of the attribute to 
1781
 
            patch.
1782
 
        :returns: A list that will be extended with one item every time the
1783
 
            function is called, with a tuple of (args, kwargs).
1784
 
        """
1785
 
        calls = []
1786
 
 
1787
 
        def decorator(*args, **kwargs):
1788
 
            calls.append((args, kwargs))
1789
 
            return orig(*args, **kwargs)
1790
 
        orig = self.overrideAttr(obj, attr_name, decorator)
1791
 
        return calls
 
1290
        Close the file and delete it, unless setKeepLogfile was called.
 
1291
        """
 
1292
        if self._log_file is None:
 
1293
            return
 
1294
        bzrlib.trace.pop_log_file(self._log_memento)
 
1295
        self._log_file.close()
 
1296
        self._log_file = None
 
1297
        if not self._keep_log_file:
 
1298
            os.remove(self._log_file_name)
 
1299
            self._log_file_name = None
 
1300
 
 
1301
    def setKeepLogfile(self):
 
1302
        """Make the logfile not be deleted when _finishLogFile is called."""
 
1303
        self._keep_log_file = True
 
1304
 
 
1305
    def addCleanup(self, callable, *args, **kwargs):
 
1306
        """Arrange to run a callable when this case is torn down.
 
1307
 
 
1308
        Callables are run in the reverse of the order they are registered,
 
1309
        ie last-in first-out.
 
1310
        """
 
1311
        self._cleanups.append((callable, args, kwargs))
1792
1312
 
1793
1313
    def _cleanEnvironment(self):
1794
 
        for name, value in isolated_environ.iteritems():
1795
 
            self.overrideEnv(name, value)
 
1314
        new_env = {
 
1315
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
 
1316
            'HOME': os.getcwd(),
 
1317
            # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
 
1318
            # tests do check our impls match APPDATA
 
1319
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
1320
            'VISUAL': None,
 
1321
            'EDITOR': None,
 
1322
            'BZR_EMAIL': None,
 
1323
            'BZREMAIL': None, # may still be present in the environment
 
1324
            'EMAIL': None,
 
1325
            'BZR_PROGRESS_BAR': None,
 
1326
            'BZR_LOG': None,
 
1327
            'BZR_PLUGIN_PATH': None,
 
1328
            # SSH Agent
 
1329
            'SSH_AUTH_SOCK': None,
 
1330
            # Proxies
 
1331
            'http_proxy': None,
 
1332
            'HTTP_PROXY': None,
 
1333
            'https_proxy': None,
 
1334
            'HTTPS_PROXY': None,
 
1335
            'no_proxy': None,
 
1336
            'NO_PROXY': None,
 
1337
            'all_proxy': None,
 
1338
            'ALL_PROXY': None,
 
1339
            # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
1340
            # least. If you do (care), please update this comment
 
1341
            # -- vila 20080401
 
1342
            'ftp_proxy': None,
 
1343
            'FTP_PROXY': None,
 
1344
            'BZR_REMOTE_PATH': None,
 
1345
        }
 
1346
        self.__old_env = {}
 
1347
        self.addCleanup(self._restoreEnvironment)
 
1348
        for name, value in new_env.iteritems():
 
1349
            self._captureVar(name, value)
 
1350
 
 
1351
    def _captureVar(self, name, newvalue):
 
1352
        """Set an environment variable, and reset it when finished."""
 
1353
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
 
1354
 
 
1355
    def _restore_debug_flags(self):
 
1356
        debug.debug_flags.clear()
 
1357
        debug.debug_flags.update(self._preserved_debug_flags)
 
1358
 
 
1359
    def _restoreEnvironment(self):
 
1360
        for name, value in self.__old_env.iteritems():
 
1361
            osutils.set_or_unset_env(name, value)
1796
1362
 
1797
1363
    def _restoreHooks(self):
1798
1364
        for klass, (name, hooks) in self._preserved_hooks.items():
1799
1365
            setattr(klass, name, hooks)
1800
 
        self._preserved_hooks.clear()
1801
 
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
1802
 
        self._preserved_lazy_hooks.clear()
1803
1366
 
1804
1367
    def knownFailure(self, reason):
1805
 
        """Declare that this test fails for a known reason
1806
 
 
1807
 
        Tests that are known to fail should generally be using expectedFailure
1808
 
        with an appropriate reverse assertion if a change could cause the test
1809
 
        to start passing. Conversely if the test has no immediate prospect of
1810
 
        succeeding then using skip is more suitable.
1811
 
 
1812
 
        When this method is called while an exception is being handled, that
1813
 
        traceback will be used, otherwise a new exception will be thrown to
1814
 
        provide one but won't be reported.
1815
 
        """
1816
 
        self._add_reason(reason)
1817
 
        try:
1818
 
            exc_info = sys.exc_info()
1819
 
            if exc_info != (None, None, None):
1820
 
                self._report_traceback(exc_info)
1821
 
            else:
1822
 
                try:
1823
 
                    raise self.failureException(reason)
1824
 
                except self.failureException:
1825
 
                    exc_info = sys.exc_info()
1826
 
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
1827
 
            raise testtools.testcase._ExpectedFailure(exc_info)
1828
 
        finally:
1829
 
            del exc_info
1830
 
 
1831
 
    def _suppress_log(self):
1832
 
        """Remove the log info from details."""
1833
 
        self.discardDetail('log')
 
1368
        """This test has failed for some known reason."""
 
1369
        raise KnownFailure(reason)
1834
1370
 
1835
1371
    def _do_skip(self, result, reason):
1836
 
        self._suppress_log()
1837
1372
        addSkip = getattr(result, 'addSkip', None)
1838
1373
        if not callable(addSkip):
1839
 
            result.addSuccess(result)
 
1374
            result.addError(self, sys.exc_info())
1840
1375
        else:
1841
1376
            addSkip(self, reason)
1842
1377
 
1843
 
    @staticmethod
1844
 
    def _do_known_failure(self, result, e):
1845
 
        self._suppress_log()
1846
 
        err = sys.exc_info()
1847
 
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1848
 
        if addExpectedFailure is not None:
1849
 
            addExpectedFailure(self, err)
1850
 
        else:
1851
 
            result.addSuccess(self)
1852
 
 
1853
 
    @staticmethod
1854
 
    def _do_not_applicable(self, result, e):
1855
 
        if not e.args:
1856
 
            reason = 'No reason given'
1857
 
        else:
1858
 
            reason = e.args[0]
1859
 
        self._suppress_log ()
1860
 
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1861
 
        if addNotApplicable is not None:
1862
 
            result.addNotApplicable(self, reason)
1863
 
        else:
1864
 
            self._do_skip(result, reason)
1865
 
 
1866
 
    @staticmethod
1867
 
    def _report_skip(self, result, err):
1868
 
        """Override the default _report_skip.
1869
 
 
1870
 
        We want to strip the 'log' detail. If we waint until _do_skip, it has
1871
 
        already been formatted into the 'reason' string, and we can't pull it
1872
 
        out again.
1873
 
        """
1874
 
        self._suppress_log()
1875
 
        super(TestCase, self)._report_skip(self, result, err)
1876
 
 
1877
 
    @staticmethod
1878
 
    def _report_expected_failure(self, result, err):
1879
 
        """Strip the log.
1880
 
 
1881
 
        See _report_skip for motivation.
1882
 
        """
1883
 
        self._suppress_log()
1884
 
        super(TestCase, self)._report_expected_failure(self, result, err)
1885
 
 
1886
 
    @staticmethod
1887
 
    def _do_unsupported_or_skip(self, result, e):
1888
 
        reason = e.args[0]
1889
 
        self._suppress_log()
1890
 
        addNotSupported = getattr(result, 'addNotSupported', None)
1891
 
        if addNotSupported is not None:
1892
 
            result.addNotSupported(self, reason)
1893
 
        else:
1894
 
            self._do_skip(result, reason)
 
1378
    def run(self, result=None):
 
1379
        if result is None: result = self.defaultTestResult()
 
1380
        for feature in getattr(self, '_test_needs_features', []):
 
1381
            if not feature.available():
 
1382
                result.startTest(self)
 
1383
                if getattr(result, 'addNotSupported', None):
 
1384
                    result.addNotSupported(self, feature)
 
1385
                else:
 
1386
                    result.addSuccess(self)
 
1387
                result.stopTest(self)
 
1388
                return result
 
1389
        try:
 
1390
            try:
 
1391
                result.startTest(self)
 
1392
                absent_attr = object()
 
1393
                # Python 2.5
 
1394
                method_name = getattr(self, '_testMethodName', absent_attr)
 
1395
                if method_name is absent_attr:
 
1396
                    # Python 2.4
 
1397
                    method_name = getattr(self, '_TestCase__testMethodName')
 
1398
                testMethod = getattr(self, method_name)
 
1399
                try:
 
1400
                    try:
 
1401
                        self.setUp()
 
1402
                        if not self._bzr_test_setUp_run:
 
1403
                            self.fail(
 
1404
                                "test setUp did not invoke "
 
1405
                                "bzrlib.tests.TestCase's setUp")
 
1406
                    except KeyboardInterrupt:
 
1407
                        self._runCleanups()
 
1408
                        raise
 
1409
                    except TestSkipped, e:
 
1410
                        self._do_skip(result, e.args[0])
 
1411
                        self.tearDown()
 
1412
                        return result
 
1413
                    except:
 
1414
                        result.addError(self, sys.exc_info())
 
1415
                        self._runCleanups()
 
1416
                        return result
 
1417
 
 
1418
                    ok = False
 
1419
                    try:
 
1420
                        testMethod()
 
1421
                        ok = True
 
1422
                    except self.failureException:
 
1423
                        result.addFailure(self, sys.exc_info())
 
1424
                    except TestSkipped, e:
 
1425
                        if not e.args:
 
1426
                            reason = "No reason given."
 
1427
                        else:
 
1428
                            reason = e.args[0]
 
1429
                        self._do_skip(result, reason)
 
1430
                    except KeyboardInterrupt:
 
1431
                        self._runCleanups()
 
1432
                        raise
 
1433
                    except:
 
1434
                        result.addError(self, sys.exc_info())
 
1435
 
 
1436
                    try:
 
1437
                        self.tearDown()
 
1438
                        if not self._bzr_test_tearDown_run:
 
1439
                            self.fail(
 
1440
                                "test tearDown did not invoke "
 
1441
                                "bzrlib.tests.TestCase's tearDown")
 
1442
                    except KeyboardInterrupt:
 
1443
                        self._runCleanups()
 
1444
                        raise
 
1445
                    except:
 
1446
                        result.addError(self, sys.exc_info())
 
1447
                        self._runCleanups()
 
1448
                        ok = False
 
1449
                    if ok: result.addSuccess(self)
 
1450
                finally:
 
1451
                    result.stopTest(self)
 
1452
                return result
 
1453
            except TestNotApplicable:
 
1454
                # Not moved from the result [yet].
 
1455
                self._runCleanups()
 
1456
                raise
 
1457
            except KeyboardInterrupt:
 
1458
                self._runCleanups()
 
1459
                raise
 
1460
        finally:
 
1461
            saved_attrs = {}
 
1462
            for attr_name in self.attrs_to_keep:
 
1463
                if attr_name in self.__dict__:
 
1464
                    saved_attrs[attr_name] = self.__dict__[attr_name]
 
1465
            self.__dict__ = saved_attrs
 
1466
 
 
1467
    def tearDown(self):
 
1468
        self._runCleanups()
 
1469
        self._log_contents = ''
 
1470
        self._bzr_test_tearDown_run = True
 
1471
        unittest.TestCase.tearDown(self)
1895
1472
 
1896
1473
    def time(self, callable, *args, **kwargs):
1897
1474
        """Run callable and accrue the time it takes to the benchmark time.
1901
1478
        self._benchcalls.
1902
1479
        """
1903
1480
        if self._benchtime is None:
1904
 
            self.addDetail('benchtime', content.Content(content.ContentType(
1905
 
                "text", "plain"), lambda:[str(self._benchtime)]))
1906
1481
            self._benchtime = 0
1907
1482
        start = time.time()
1908
1483
        try:
1917
1492
        finally:
1918
1493
            self._benchtime += time.time() - start
1919
1494
 
 
1495
    def _runCleanups(self):
 
1496
        """Run registered cleanup functions.
 
1497
 
 
1498
        This should only be called from TestCase.tearDown.
 
1499
        """
 
1500
        # TODO: Perhaps this should keep running cleanups even if
 
1501
        # one of them fails?
 
1502
 
 
1503
        # Actually pop the cleanups from the list so tearDown running
 
1504
        # twice is safe (this happens for skipped tests).
 
1505
        while self._cleanups:
 
1506
            cleanup, args, kwargs = self._cleanups.pop()
 
1507
            cleanup(*args, **kwargs)
 
1508
 
1920
1509
    def log(self, *args):
1921
 
        trace.mutter(*args)
1922
 
 
1923
 
    def get_log(self):
1924
 
        """Get a unicode string containing the log from bzrlib.trace.
1925
 
 
1926
 
        Undecodable characters are replaced.
 
1510
        mutter(*args)
 
1511
 
 
1512
    def _get_log(self, keep_log_file=False):
 
1513
        """Get the log from bzrlib.trace calls from this test.
 
1514
 
 
1515
        :param keep_log_file: When True, if the log is still a file on disk
 
1516
            leave it as a file on disk. When False, if the log is still a file
 
1517
            on disk, the log file is deleted and the log preserved as
 
1518
            self._log_contents.
 
1519
        :return: A string containing the log.
1927
1520
        """
1928
 
        return u"".join(self.getDetails()['log'].iter_text())
 
1521
        # flush the log file, to get all content
 
1522
        import bzrlib.trace
 
1523
        if bzrlib.trace._trace_file:
 
1524
            bzrlib.trace._trace_file.flush()
 
1525
        if self._log_contents:
 
1526
            # XXX: this can hardly contain the content flushed above --vila
 
1527
            # 20080128
 
1528
            return self._log_contents
 
1529
        if self._log_file_name is not None:
 
1530
            logfile = open(self._log_file_name)
 
1531
            try:
 
1532
                log_contents = logfile.read()
 
1533
            finally:
 
1534
                logfile.close()
 
1535
            if not keep_log_file:
 
1536
                self._log_contents = log_contents
 
1537
                try:
 
1538
                    os.remove(self._log_file_name)
 
1539
                except OSError, e:
 
1540
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
 
1541
                        sys.stderr.write(('Unable to delete log file '
 
1542
                                             ' %r\n' % self._log_file_name))
 
1543
                    else:
 
1544
                        raise
 
1545
            return log_contents
 
1546
        else:
 
1547
            return "DELETED log file to reduce memory footprint"
1929
1548
 
1930
1549
    def requireFeature(self, feature):
1931
1550
        """This test requires a specific feature is available.
1948
1567
 
1949
1568
    def _run_bzr_core(self, args, retcode, encoding, stdin,
1950
1569
            working_dir):
1951
 
        # Clear chk_map page cache, because the contents are likely to mask
1952
 
        # locking errors.
1953
 
        chk_map.clear_cache()
1954
1570
        if encoding is None:
1955
1571
            encoding = osutils.get_user_encoding()
1956
1572
        stdout = StringIOWrapper()
1973
1589
            os.chdir(working_dir)
1974
1590
 
1975
1591
        try:
1976
 
            try:
1977
 
                result = self.apply_redirected(
1978
 
                    ui.ui_factory.stdin,
1979
 
                    stdout, stderr,
1980
 
                    _mod_commands.run_bzr_catch_user_errors,
1981
 
                    args)
1982
 
            except KeyboardInterrupt:
1983
 
                # Reraise KeyboardInterrupt with contents of redirected stdout
1984
 
                # and stderr as arguments, for tests which are interested in
1985
 
                # stdout and stderr and are expecting the exception.
1986
 
                out = stdout.getvalue()
1987
 
                err = stderr.getvalue()
1988
 
                if out:
1989
 
                    self.log('output:\n%r', out)
1990
 
                if err:
1991
 
                    self.log('errors:\n%r', err)
1992
 
                raise KeyboardInterrupt(out, err)
 
1592
            result = self.apply_redirected(ui.ui_factory.stdin,
 
1593
                stdout, stderr,
 
1594
                bzrlib.commands.run_bzr_catch_user_errors,
 
1595
                args)
1993
1596
        finally:
1994
1597
            logger.removeHandler(handler)
1995
1598
            ui.ui_factory = old_ui_factory
2005
1608
        if retcode is not None:
2006
1609
            self.assertEquals(retcode, result,
2007
1610
                              message='Unexpected return code')
2008
 
        return result, out, err
 
1611
        return out, err
2009
1612
 
2010
1613
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
2011
1614
                working_dir=None, error_regexes=[], output_encoding=None):
2040
1643
        :keyword error_regexes: A list of expected error messages.  If
2041
1644
            specified they must be seen in the error output of the command.
2042
1645
        """
2043
 
        retcode, out, err = self._run_bzr_autosplit(
 
1646
        out, err = self._run_bzr_autosplit(
2044
1647
            args=args,
2045
1648
            retcode=retcode,
2046
1649
            encoding=encoding,
2125
1728
    def start_bzr_subprocess(self, process_args, env_changes=None,
2126
1729
                             skip_if_plan_to_signal=False,
2127
1730
                             working_dir=None,
2128
 
                             allow_plugins=False, stderr=subprocess.PIPE):
 
1731
                             allow_plugins=False):
2129
1732
        """Start bzr in a subprocess for testing.
2130
1733
 
2131
1734
        This starts a new Python interpreter and runs bzr in there.
2140
1743
            variables. A value of None will unset the env variable.
2141
1744
            The values must be strings. The change will only occur in the
2142
1745
            child, so you don't need to fix the environment after running.
2143
 
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
2144
 
            doesn't support signalling subprocesses.
 
1746
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
 
1747
            is not available.
2145
1748
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
2146
 
        :param stderr: file to use for the subprocess's stderr.  Valid values
2147
 
            are those valid for the stderr argument of `subprocess.Popen`.
2148
 
            Default value is ``subprocess.PIPE``.
2149
1749
 
2150
1750
        :returns: Popen object for the started process.
2151
1751
        """
2152
1752
        if skip_if_plan_to_signal:
2153
 
            if os.name != "posix":
2154
 
                raise TestSkipped("Sending signals not supported")
 
1753
            if not getattr(os, 'kill', None):
 
1754
                raise TestSkipped("os.kill not available.")
2155
1755
 
2156
1756
        if env_changes is None:
2157
1757
            env_changes = {}
2177
1777
            # so we will avoid using it on all platforms, just to
2178
1778
            # make sure the code path is used, and we don't break on win32
2179
1779
            cleanup_environment()
2180
 
            # Include the subprocess's log file in the test details, in case
2181
 
            # the test fails due to an error in the subprocess.
2182
 
            self._add_subprocess_log(trace._get_bzr_log_filename())
2183
1780
            command = [sys.executable]
2184
1781
            # frozen executables don't need the path to bzr
2185
1782
            if getattr(sys, "frozen", None) is None:
2187
1784
            if not allow_plugins:
2188
1785
                command.append('--no-plugins')
2189
1786
            command.extend(process_args)
2190
 
            process = self._popen(command, stdin=subprocess.PIPE,
2191
 
                                  stdout=subprocess.PIPE,
2192
 
                                  stderr=stderr)
 
1787
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
2193
1788
        finally:
2194
1789
            restore_environment()
2195
1790
            if cwd is not None:
2197
1792
 
2198
1793
        return process
2199
1794
 
2200
 
    def _add_subprocess_log(self, log_file_path):
2201
 
        if len(self._log_files) == 0:
2202
 
            # Register an addCleanup func.  We do this on the first call to
2203
 
            # _add_subprocess_log rather than in TestCase.setUp so that this
2204
 
            # addCleanup is registered after any cleanups for tempdirs that
2205
 
            # subclasses might create, which will probably remove the log file
2206
 
            # we want to read.
2207
 
            self.addCleanup(self._subprocess_log_cleanup)
2208
 
        # self._log_files is a set, so if a log file is reused we won't grab it
2209
 
        # twice.
2210
 
        self._log_files.add(log_file_path)
2211
 
 
2212
 
    def _subprocess_log_cleanup(self):
2213
 
        for count, log_file_path in enumerate(self._log_files):
2214
 
            # We use buffer_now=True to avoid holding the file open beyond
2215
 
            # the life of this function, which might interfere with e.g.
2216
 
            # cleaning tempdirs on Windows.
2217
 
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
2218
 
            #detail_content = content.content_from_file(
2219
 
            #    log_file_path, buffer_now=True)
2220
 
            with open(log_file_path, 'rb') as log_file:
2221
 
                log_file_bytes = log_file.read()
2222
 
            detail_content = content.Content(content.ContentType("text",
2223
 
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
2224
 
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
2225
 
                detail_content)
2226
 
 
2227
1795
    def _popen(self, *args, **kwargs):
2228
1796
        """Place a call to Popen.
2229
1797
 
2230
1798
        Allows tests to override this method to intercept the calls made to
2231
1799
        Popen for introspection.
2232
1800
        """
2233
 
        return subprocess.Popen(*args, **kwargs)
2234
 
 
2235
 
    def get_source_path(self):
2236
 
        """Return the path of the directory containing bzrlib."""
2237
 
        return os.path.dirname(os.path.dirname(bzrlib.__file__))
 
1801
        return Popen(*args, **kwargs)
2238
1802
 
2239
1803
    def get_bzr_path(self):
2240
1804
        """Return the path of the 'bzr' executable for this test suite."""
2241
 
        bzr_path = os.path.join(self.get_source_path(), "bzr")
 
1805
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
2242
1806
        if not os.path.isfile(bzr_path):
2243
1807
            # We are probably installed. Assume sys.argv is the right file
2244
1808
            bzr_path = sys.argv[0]
2266
1830
        if retcode is not None and retcode != process.returncode:
2267
1831
            if process_args is None:
2268
1832
                process_args = "(unknown args)"
2269
 
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
2270
 
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
 
1833
            mutter('Output of bzr %s:\n%s', process_args, out)
 
1834
            mutter('Error for bzr %s:\n%s', process_args, err)
2271
1835
            self.fail('Command bzr %s failed with retcode %s != %s'
2272
1836
                      % (process_args, retcode, process.returncode))
2273
1837
        return [out, err]
2274
1838
 
2275
 
    def check_tree_shape(self, tree, shape):
2276
 
        """Compare a tree to a list of expected names.
 
1839
    def check_inventory_shape(self, inv, shape):
 
1840
        """Compare an inventory to a list of expected names.
2277
1841
 
2278
1842
        Fail if they are not precisely equal.
2279
1843
        """
2280
1844
        extras = []
2281
1845
        shape = list(shape)             # copy
2282
 
        for path, ie in tree.iter_entries_by_dir():
 
1846
        for path, ie in inv.entries():
2283
1847
            name = path.replace('\\', '/')
2284
1848
            if ie.kind == 'directory':
2285
1849
                name = name + '/'
2286
 
            if name == "/":
2287
 
                pass # ignore root entry
2288
 
            elif name in shape:
 
1850
            if name in shape:
2289
1851
                shape.remove(name)
2290
1852
            else:
2291
1853
                extras.append(name)
2332
1894
 
2333
1895
        Tests that expect to provoke LockContention errors should call this.
2334
1896
        """
2335
 
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
1897
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
 
1898
        def resetTimeout():
 
1899
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
 
1900
        self.addCleanup(resetTimeout)
 
1901
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
2336
1902
 
2337
1903
    def make_utf8_encoded_stringio(self, encoding_type=None):
2338
1904
        """Return a StringIOWrapper instance, that will encode Unicode
2346
1912
        sio.encoding = output_encoding
2347
1913
        return sio
2348
1914
 
2349
 
    def disable_verb(self, verb):
2350
 
        """Disable a smart server verb for one test."""
2351
 
        from bzrlib.smart import request
2352
 
        request_handlers = request.request_handlers
2353
 
        orig_method = request_handlers.get(verb)
2354
 
        request_handlers.remove(verb)
2355
 
        self.addCleanup(request_handlers.register, verb, orig_method)
2356
 
 
2357
1915
 
2358
1916
class CapturedCall(object):
2359
1917
    """A helper for capturing smart server calls for easy debug analysis."""
2381
1939
class TestCaseWithMemoryTransport(TestCase):
2382
1940
    """Common test class for tests that do not need disk resources.
2383
1941
 
2384
 
    Tests that need disk resources should derive from TestCaseInTempDir
2385
 
    orTestCaseWithTransport.
 
1942
    Tests that need disk resources should derive from TestCaseWithTransport.
2386
1943
 
2387
1944
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2388
1945
 
2389
 
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
 
1946
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
2390
1947
    a directory which does not exist. This serves to help ensure test isolation
2391
 
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
2392
 
    must exist. However, TestCaseWithMemoryTransport does not offer local file
2393
 
    defaults for the transport in tests, nor does it obey the command line
 
1948
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
 
1949
    must exist. However, TestCaseWithMemoryTransport does not offer local
 
1950
    file defaults for the transport in tests, nor does it obey the command line
2394
1951
    override, so tests that accidentally write to the common directory should
2395
1952
    be rare.
2396
1953
 
2397
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
2398
 
        ``.bzr`` directory that stops us ascending higher into the filesystem.
 
1954
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
 
1955
    a .bzr directory that stops us ascending higher into the filesystem.
2399
1956
    """
2400
1957
 
2401
1958
    TEST_ROOT = None
2419
1976
 
2420
1977
        :param relpath: a path relative to the base url.
2421
1978
        """
2422
 
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
 
1979
        t = get_transport(self.get_url(relpath))
2423
1980
        self.assertFalse(t.is_readonly())
2424
1981
        return t
2425
1982
 
2431
1988
 
2432
1989
        :param relpath: a path relative to the base url.
2433
1990
        """
2434
 
        t = _mod_transport.get_transport(self.get_readonly_url(relpath))
 
1991
        t = get_transport(self.get_readonly_url(relpath))
2435
1992
        self.assertTrue(t.is_readonly())
2436
1993
        return t
2437
1994
 
2450
2007
        if self.__readonly_server is None:
2451
2008
            if self.transport_readonly_server is None:
2452
2009
                # readonly decorator requested
2453
 
                self.__readonly_server = test_server.ReadonlyServer()
 
2010
                # bring up the server
 
2011
                self.__readonly_server = ReadonlyServer()
 
2012
                self.__readonly_server.setUp(self.get_vfs_only_server())
2454
2013
            else:
2455
 
                # explicit readonly transport.
2456
2014
                self.__readonly_server = self.create_transport_readonly_server()
2457
 
            self.start_server(self.__readonly_server,
2458
 
                self.get_vfs_only_server())
 
2015
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
2016
            self.addCleanup(self.__readonly_server.tearDown)
2459
2017
        return self.__readonly_server
2460
2018
 
2461
2019
    def get_readonly_url(self, relpath=None):
2479
2037
        is no means to override it.
2480
2038
        """
2481
2039
        if self.__vfs_server is None:
2482
 
            self.__vfs_server = memory.MemoryServer()
2483
 
            self.start_server(self.__vfs_server)
 
2040
            self.__vfs_server = MemoryServer()
 
2041
            self.__vfs_server.setUp()
 
2042
            self.addCleanup(self.__vfs_server.tearDown)
2484
2043
        return self.__vfs_server
2485
2044
 
2486
2045
    def get_server(self):
2493
2052
        then the self.get_vfs_server is returned.
2494
2053
        """
2495
2054
        if self.__server is None:
2496
 
            if (self.transport_server is None or self.transport_server is
2497
 
                self.vfs_transport_factory):
2498
 
                self.__server = self.get_vfs_only_server()
 
2055
            if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
 
2056
                return self.get_vfs_only_server()
2499
2057
            else:
2500
2058
                # bring up a decorated means of access to the vfs only server.
2501
2059
                self.__server = self.transport_server()
2502
 
                self.start_server(self.__server, self.get_vfs_only_server())
 
2060
                try:
 
2061
                    self.__server.setUp(self.get_vfs_only_server())
 
2062
                except TypeError, e:
 
2063
                    # This should never happen; the try:Except here is to assist
 
2064
                    # developers having to update code rather than seeing an
 
2065
                    # uninformative TypeError.
 
2066
                    raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
 
2067
            self.addCleanup(self.__server.tearDown)
2503
2068
        return self.__server
2504
2069
 
2505
2070
    def _adjust_url(self, base, relpath):
2558
2123
        real branch.
2559
2124
        """
2560
2125
        root = TestCaseWithMemoryTransport.TEST_ROOT
2561
 
        wt = bzrdir.BzrDir.create_standalone_workingtree(root)
2562
 
        # Hack for speed: remember the raw bytes of the dirstate file so that
2563
 
        # we don't need to re-open the wt to check it hasn't changed.
2564
 
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
2565
 
            wt.control_transport.get_bytes('dirstate'))
 
2126
        bzrdir.BzrDir.create_standalone_workingtree(root)
2566
2127
 
2567
2128
    def _check_safety_net(self):
2568
2129
        """Check that the safety .bzr directory have not been touched.
2571
2132
        propagating. This method ensures than a test did not leaked.
2572
2133
        """
2573
2134
        root = TestCaseWithMemoryTransport.TEST_ROOT
2574
 
        t = _mod_transport.get_transport(root)
2575
 
        self.permit_url(t.base)
2576
 
        if (t.get_bytes('.bzr/checkout/dirstate') != 
2577
 
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
 
2135
        wt = workingtree.WorkingTree.open(root)
 
2136
        last_rev = wt.last_revision()
 
2137
        if last_rev != 'null:':
2578
2138
            # The current test have modified the /bzr directory, we need to
2579
2139
            # recreate a new one or all the followng tests will fail.
2580
2140
            # If you need to inspect its content uncomment the following line
2581
2141
            # import pdb; pdb.set_trace()
2582
 
            _rmtree_temp_dir(root + '/.bzr', test_id=self.id())
 
2142
            _rmtree_temp_dir(root + '/.bzr')
2583
2143
            self._create_safety_net()
2584
2144
            raise AssertionError('%s/.bzr should not be modified' % root)
2585
2145
 
2586
2146
    def _make_test_root(self):
2587
2147
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
2588
 
            # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
2589
 
            root = osutils.realpath(osutils.mkdtemp(prefix='testbzr-',
2590
 
                                                    suffix='.tmp'))
 
2148
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
2591
2149
            TestCaseWithMemoryTransport.TEST_ROOT = root
2592
2150
 
2593
2151
            self._create_safety_net()
2596
2154
            # specifically told when all tests are finished.  This will do.
2597
2155
            atexit.register(_rmtree_temp_dir, root)
2598
2156
 
2599
 
        self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
2600
2157
        self.addCleanup(self._check_safety_net)
2601
2158
 
2602
2159
    def makeAndChdirToTestDir(self):
2610
2167
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2611
2168
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2612
2169
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2613
 
        self.permit_dir(self.test_dir)
2614
2170
 
2615
2171
    def make_branch(self, relpath, format=None):
2616
2172
        """Create a branch on the transport at relpath."""
2622
2178
            # might be a relative or absolute path
2623
2179
            maybe_a_url = self.get_url(relpath)
2624
2180
            segments = maybe_a_url.rsplit('/', 1)
2625
 
            t = _mod_transport.get_transport(maybe_a_url)
 
2181
            t = get_transport(maybe_a_url)
2626
2182
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2627
2183
                t.ensure_base()
2628
2184
            if format is None:
2645
2201
        made_control = self.make_bzrdir(relpath, format=format)
2646
2202
        return made_control.create_repository(shared=shared)
2647
2203
 
2648
 
    def make_smart_server(self, path, backing_server=None):
2649
 
        if backing_server is None:
2650
 
            backing_server = self.get_server()
2651
 
        smart_server = test_server.SmartTCPServer_for_testing()
2652
 
        self.start_server(smart_server, backing_server)
2653
 
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
2654
 
                                                   ).clone(path)
 
2204
    def make_smart_server(self, path):
 
2205
        smart_server = server.SmartTCPServer_for_testing()
 
2206
        smart_server.setUp(self.get_server())
 
2207
        remote_transport = get_transport(smart_server.get_url()).clone(path)
 
2208
        self.addCleanup(smart_server.tearDown)
2655
2209
        return remote_transport
2656
2210
 
2657
2211
    def make_branch_and_memory_tree(self, relpath, format=None):
2664
2218
        return branchbuilder.BranchBuilder(branch=branch)
2665
2219
 
2666
2220
    def overrideEnvironmentForTesting(self):
2667
 
        test_home_dir = self.test_home_dir
2668
 
        if isinstance(test_home_dir, unicode):
2669
 
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2670
 
        self.overrideEnv('HOME', test_home_dir)
2671
 
        self.overrideEnv('BZR_HOME', test_home_dir)
 
2221
        os.environ['HOME'] = self.test_home_dir
 
2222
        os.environ['BZR_HOME'] = self.test_home_dir
2672
2223
 
2673
2224
    def setUp(self):
2674
2225
        super(TestCaseWithMemoryTransport, self).setUp()
2675
 
        # Ensure that ConnectedTransport doesn't leak sockets
2676
 
        def get_transport_from_url_with_cleanup(*args, **kwargs):
2677
 
            t = orig_get_transport_from_url(*args, **kwargs)
2678
 
            if isinstance(t, _mod_transport.ConnectedTransport):
2679
 
                self.addCleanup(t.disconnect)
2680
 
            return t
2681
 
 
2682
 
        orig_get_transport_from_url = self.overrideAttr(
2683
 
            _mod_transport, 'get_transport_from_url',
2684
 
            get_transport_from_url_with_cleanup)
2685
2226
        self._make_test_root()
2686
 
        self.addCleanup(os.chdir, os.getcwdu())
 
2227
        _currentdir = os.getcwdu()
 
2228
        def _leaveDirectory():
 
2229
            os.chdir(_currentdir)
 
2230
        self.addCleanup(_leaveDirectory)
2687
2231
        self.makeAndChdirToTestDir()
2688
2232
        self.overrideEnvironmentForTesting()
2689
2233
        self.__readonly_server = None
2692
2236
 
2693
2237
    def setup_smart_server_with_call_log(self):
2694
2238
        """Sets up a smart server as the transport server with a call log."""
2695
 
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2239
        self.transport_server = server.SmartTCPServer_for_testing
2696
2240
        self.hpss_calls = []
2697
2241
        import traceback
2698
2242
        # Skip the current stack down to the caller of
2730
2274
 
2731
2275
    OVERRIDE_PYTHON = 'python'
2732
2276
 
2733
 
    def setUp(self):
2734
 
        super(TestCaseInTempDir, self).setUp()
2735
 
        # Remove the protection set in isolated_environ, we have a proper
2736
 
        # access to disk resources now.
2737
 
        self.overrideEnv('BZR_LOG', None)
2738
 
 
2739
2277
    def check_file_contents(self, filename, expect):
2740
2278
        self.log("check contents of file %s" % filename)
2741
 
        f = file(filename)
2742
 
        try:
2743
 
            contents = f.read()
2744
 
        finally:
2745
 
            f.close()
 
2279
        contents = file(filename, 'r').read()
2746
2280
        if contents != expect:
2747
2281
            self.log("expected: %r" % expect)
2748
2282
            self.log("actually: %r" % contents)
2750
2284
 
2751
2285
    def _getTestDirPrefix(self):
2752
2286
        # create a directory within the top level test directory
2753
 
        if sys.platform in ('win32', 'cygwin'):
 
2287
        if sys.platform == 'win32':
2754
2288
            name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2755
2289
            # windows is likely to have path-length limits so use a short name
2756
2290
            name_prefix = name_prefix[-30:]
2771
2305
            if os.path.exists(name):
2772
2306
                name = name_prefix + '_' + str(i)
2773
2307
            else:
2774
 
                # now create test and home directories within this dir
2775
 
                self.test_base_dir = name
2776
 
                self.addCleanup(self.deleteTestDir)
2777
 
                os.mkdir(self.test_base_dir)
 
2308
                os.mkdir(name)
2778
2309
                break
2779
 
        self.permit_dir(self.test_base_dir)
2780
 
        # 'sprouting' and 'init' of a branch both walk up the tree to find
2781
 
        # stacking policy to honour; create a bzr dir with an unshared
2782
 
        # repository (but not a branch - our code would be trying to escape
2783
 
        # then!) to stop them, and permit it to be read.
2784
 
        # control = bzrdir.BzrDir.create(self.test_base_dir)
2785
 
        # control.create_repository()
 
2310
        # now create test and home directories within this dir
 
2311
        self.test_base_dir = name
2786
2312
        self.test_home_dir = self.test_base_dir + '/home'
2787
2313
        os.mkdir(self.test_home_dir)
2788
2314
        self.test_dir = self.test_base_dir + '/work'
2794
2320
            f.write(self.id())
2795
2321
        finally:
2796
2322
            f.close()
 
2323
        self.addCleanup(self.deleteTestDir)
2797
2324
 
2798
2325
    def deleteTestDir(self):
2799
2326
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2800
 
        _rmtree_temp_dir(self.test_base_dir, test_id=self.id())
 
2327
        _rmtree_temp_dir(self.test_base_dir)
2801
2328
 
2802
2329
    def build_tree(self, shape, line_endings='binary', transport=None):
2803
2330
        """Build a test tree according to a pattern.
2822
2349
                "a list or a tuple. Got %r instead" % (shape,))
2823
2350
        # It's OK to just create them using forward slashes on windows.
2824
2351
        if transport is None or transport.is_readonly():
2825
 
            transport = _mod_transport.get_transport(".")
 
2352
            transport = get_transport(".")
2826
2353
        for name in shape:
2827
2354
            self.assertIsInstance(name, basestring)
2828
2355
            if name[-1] == '/':
2838
2365
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2839
2366
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2840
2367
 
2841
 
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
 
2368
    def build_tree_contents(self, shape):
 
2369
        build_tree_contents(shape)
2842
2370
 
2843
2371
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2844
2372
        """Assert whether path or paths are in the WorkingTree"""
2884
2412
        """
2885
2413
        if self.__vfs_server is None:
2886
2414
            self.__vfs_server = self.vfs_transport_factory()
2887
 
            self.start_server(self.__vfs_server)
 
2415
            self.__vfs_server.setUp()
 
2416
            self.addCleanup(self.__vfs_server.tearDown)
2888
2417
        return self.__vfs_server
2889
2418
 
2890
2419
    def make_branch_and_tree(self, relpath, format=None):
2897
2426
        repository will also be accessed locally. Otherwise a lightweight
2898
2427
        checkout is created and returned.
2899
2428
 
2900
 
        We do this because we can't physically create a tree in the local
2901
 
        path, with a branch reference to the transport_factory url, and
2902
 
        a branch + repository in the vfs_transport, unless the vfs_transport
2903
 
        namespace is distinct from the local disk - the two branch objects
2904
 
        would collide. While we could construct a tree with its branch object
2905
 
        pointing at the transport_factory transport in memory, reopening it
2906
 
        would behaving unexpectedly, and has in the past caused testing bugs
2907
 
        when we tried to do it that way.
2908
 
 
2909
2429
        :param format: The BzrDirFormat.
2910
2430
        :returns: the WorkingTree.
2911
2431
        """
2920
2440
            # We can only make working trees locally at the moment.  If the
2921
2441
            # transport can't support them, then we keep the non-disk-backed
2922
2442
            # branch and create a local checkout.
2923
 
            if self.vfs_transport_factory is test_server.LocalURLServer:
 
2443
            if self.vfs_transport_factory is LocalURLServer:
2924
2444
                # the branch is colocated on disk, we cannot create a checkout.
2925
2445
                # hopefully callers will expect this.
2926
2446
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
2963
2483
        super(TestCaseWithTransport, self).setUp()
2964
2484
        self.__vfs_server = None
2965
2485
 
2966
 
    def disable_missing_extensions_warning(self):
2967
 
        """Some tests expect a precise stderr content.
2968
 
 
2969
 
        There is no point in forcing them to duplicate the extension related
2970
 
        warning.
2971
 
        """
2972
 
        config.GlobalConfig().set_user_option('ignore_missing_extensions', True)
2973
 
 
2974
2486
 
2975
2487
class ChrootedTestCase(TestCaseWithTransport):
2976
2488
    """A support class that provides readonly urls outside the local namespace.
2985
2497
    """
2986
2498
 
2987
2499
    def setUp(self):
2988
 
        from bzrlib.tests import http_server
2989
2500
        super(ChrootedTestCase, self).setUp()
2990
 
        if not self.vfs_transport_factory == memory.MemoryServer:
2991
 
            self.transport_readonly_server = http_server.HttpServer
 
2501
        if not self.vfs_transport_factory == MemoryServer:
 
2502
            self.transport_readonly_server = HttpServer
2992
2503
 
2993
2504
 
2994
2505
def condition_id_re(pattern):
2997
2508
    :param pattern: A regular expression string.
2998
2509
    :return: A callable that returns True if the re matches.
2999
2510
    """
3000
 
    filter_re = re.compile(pattern, 0)
 
2511
    filter_re = osutils.re_compile_checked(pattern, 0,
 
2512
        'test filter')
3001
2513
    def condition(test):
3002
2514
        test_id = test.id()
3003
2515
        return filter_re.search(test_id)
3190
2702
              strict=False,
3191
2703
              runner_class=None,
3192
2704
              suite_decorators=None,
3193
 
              stream=None,
3194
 
              result_decorators=None,
3195
 
              ):
 
2705
              stream=None):
3196
2706
    """Run a test suite for bzr selftest.
3197
2707
 
3198
2708
    :param runner_class: The class of runner to use. Must support the
3213
2723
                            descriptions=0,
3214
2724
                            verbosity=verbosity,
3215
2725
                            bench_history=bench_history,
 
2726
                            list_only=list_only,
3216
2727
                            strict=strict,
3217
 
                            result_decorators=result_decorators,
3218
2728
                            )
3219
2729
    runner.stop_on_failure=stop_on_failure
3220
2730
    # built in decorator factories:
3228
2738
        decorators.append(filter_tests(pattern))
3229
2739
    if suite_decorators:
3230
2740
        decorators.extend(suite_decorators)
3231
 
    # tell the result object how many tests will be running: (except if
3232
 
    # --parallel=fork is being used. Robert said he will provide a better
3233
 
    # progress design later -- vila 20090817)
3234
 
    if fork_decorator not in decorators:
3235
 
        decorators.append(CountingDecorator)
3236
2741
    for decorator in decorators:
3237
2742
        suite = decorator(suite)
 
2743
    result = runner.run(suite)
3238
2744
    if list_only:
3239
 
        # Done after test suite decoration to allow randomisation etc
3240
 
        # to take effect, though that is of marginal benefit.
3241
 
        if verbosity >= 2:
3242
 
            stream.write("Listing tests only ...\n")
3243
 
        for t in iter_suite_tests(suite):
3244
 
            stream.write("%s\n" % (t.id()))
3245
2745
        return True
3246
 
    result = runner.run(suite)
 
2746
    result.done()
3247
2747
    if strict:
3248
2748
        return result.wasStrictlySuccessful()
3249
2749
    else:
3255
2755
 
3256
2756
 
3257
2757
def fork_decorator(suite):
3258
 
    if getattr(os, "fork", None) is None:
3259
 
        raise errors.BzrCommandError("platform does not support fork,"
3260
 
            " try --parallel=subprocess instead.")
3261
2758
    concurrency = osutils.local_concurrency()
3262
2759
    if concurrency == 1:
3263
2760
        return suite
3318
2815
    return suite
3319
2816
 
3320
2817
 
3321
 
class TestDecorator(TestUtil.TestSuite):
 
2818
class TestDecorator(TestSuite):
3322
2819
    """A decorator for TestCase/TestSuite objects.
3323
2820
    
3324
2821
    Usually, subclasses should override __iter__(used when flattening test
3327
2824
    """
3328
2825
 
3329
2826
    def __init__(self, suite):
3330
 
        TestUtil.TestSuite.__init__(self)
 
2827
        TestSuite.__init__(self)
3331
2828
        self.addTest(suite)
3332
2829
 
3333
2830
    def countTestCases(self):
3350
2847
        return result
3351
2848
 
3352
2849
 
3353
 
class CountingDecorator(TestDecorator):
3354
 
    """A decorator which calls result.progress(self.countTestCases)."""
3355
 
 
3356
 
    def run(self, result):
3357
 
        progress_method = getattr(result, 'progress', None)
3358
 
        if callable(progress_method):
3359
 
            progress_method(self.countTestCases(), SUBUNIT_SEEK_SET)
3360
 
        return super(CountingDecorator, self).run(result)
3361
 
 
3362
 
 
3363
2850
class ExcludeDecorator(TestDecorator):
3364
2851
    """A decorator which excludes test matching an exclude pattern."""
3365
2852
 
3409
2896
        if self.randomised:
3410
2897
            return iter(self._tests)
3411
2898
        self.randomised = True
3412
 
        self.stream.write("Randomizing test order using seed %s\n\n" %
 
2899
        self.stream.writeln("Randomizing test order using seed %s\n" %
3413
2900
            (self.actual_seed()))
3414
2901
        # Initialise the random number generator.
3415
2902
        random.seed(self.actual_seed())
3452
2939
 
3453
2940
def partition_tests(suite, count):
3454
2941
    """Partition suite into count lists of tests."""
3455
 
    # This just assigns tests in a round-robin fashion.  On one hand this
3456
 
    # splits up blocks of related tests that might run faster if they shared
3457
 
    # resources, but on the other it avoids assigning blocks of slow tests to
3458
 
    # just one partition.  So the slowest partition shouldn't be much slower
3459
 
    # than the fastest.
3460
 
    partitions = [list() for i in range(count)]
3461
 
    tests = iter_suite_tests(suite)
3462
 
    for partition, test in itertools.izip(itertools.cycle(partitions), tests):
3463
 
        partition.append(test)
3464
 
    return partitions
3465
 
 
3466
 
 
3467
 
def workaround_zealous_crypto_random():
3468
 
    """Crypto.Random want to help us being secure, but we don't care here.
3469
 
 
3470
 
    This workaround some test failure related to the sftp server. Once paramiko
3471
 
    stop using the controversial API in Crypto.Random, we may get rid of it.
3472
 
    """
3473
 
    try:
3474
 
        from Crypto.Random import atfork
3475
 
        atfork()
3476
 
    except ImportError:
3477
 
        pass
 
2942
    result = []
 
2943
    tests = list(iter_suite_tests(suite))
 
2944
    tests_per_process = int(math.ceil(float(len(tests)) / count))
 
2945
    for block in range(count):
 
2946
        low_test = block * tests_per_process
 
2947
        high_test = low_test + tests_per_process
 
2948
        process_tests = tests[low_test:high_test]
 
2949
        result.append(process_tests)
 
2950
    return result
3478
2951
 
3479
2952
 
3480
2953
def fork_for_tests(suite):
3486
2959
    concurrency = osutils.local_concurrency()
3487
2960
    result = []
3488
2961
    from subunit import TestProtocolClient, ProtocolTestCase
3489
 
    from subunit.test_results import AutoTimingTestResultDecorator
3490
2962
    class TestInOtherProcess(ProtocolTestCase):
3491
2963
        # Should be in subunit, I think. RBC.
3492
2964
        def __init__(self, stream, pid):
3497
2969
            try:
3498
2970
                ProtocolTestCase.run(self, result)
3499
2971
            finally:
3500
 
                os.waitpid(self.pid, 0)
 
2972
                os.waitpid(self.pid, os.WNOHANG)
3501
2973
 
3502
2974
    test_blocks = partition_tests(suite, concurrency)
3503
2975
    for process_tests in test_blocks:
3504
 
        process_suite = TestUtil.TestSuite()
 
2976
        process_suite = TestSuite()
3505
2977
        process_suite.addTests(process_tests)
3506
2978
        c2pread, c2pwrite = os.pipe()
3507
2979
        pid = os.fork()
3508
2980
        if pid == 0:
3509
 
            workaround_zealous_crypto_random()
3510
2981
            try:
3511
2982
                os.close(c2pread)
3512
2983
                # Leave stderr and stdout open so we can see test noise
3516
2987
                sys.stdin.close()
3517
2988
                sys.stdin = None
3518
2989
                stream = os.fdopen(c2pwrite, 'wb', 1)
3519
 
                subunit_result = AutoTimingTestResultDecorator(
3520
 
                    TestProtocolClient(stream))
 
2990
                subunit_result = TestProtocolClient(stream)
3521
2991
                process_suite.run(subunit_result)
3522
2992
            finally:
3523
2993
                os._exit(0)
3537
3007
    """
3538
3008
    concurrency = osutils.local_concurrency()
3539
3009
    result = []
3540
 
    from subunit import ProtocolTestCase
 
3010
    from subunit import TestProtocolClient, ProtocolTestCase
3541
3011
    class TestInSubprocess(ProtocolTestCase):
3542
3012
        def __init__(self, process, name):
3543
3013
            ProtocolTestCase.__init__(self, process.stdout)
3559
3029
        if not os.path.isfile(bzr_path):
3560
3030
            # We are probably installed. Assume sys.argv is the right file
3561
3031
            bzr_path = sys.argv[0]
3562
 
        bzr_path = [bzr_path]
3563
 
        if sys.platform == "win32":
3564
 
            # if we're on windows, we can't execute the bzr script directly
3565
 
            bzr_path = [sys.executable] + bzr_path
3566
3032
        fd, test_list_file_name = tempfile.mkstemp()
3567
3033
        test_list_file = os.fdopen(fd, 'wb', 1)
3568
3034
        for test in process_tests:
3569
3035
            test_list_file.write(test.id() + '\n')
3570
3036
        test_list_file.close()
3571
3037
        try:
3572
 
            argv = bzr_path + ['selftest', '--load-list', test_list_file_name,
 
3038
            argv = [bzr_path, 'selftest', '--load-list', test_list_file_name,
3573
3039
                '--subunit']
3574
3040
            if '--no-plugins' in sys.argv:
3575
3041
                argv.append('--no-plugins')
3576
 
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
3577
 
            # noise on stderr it can interrupt the subunit protocol.
3578
 
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
3579
 
                                      stdout=subprocess.PIPE,
3580
 
                                      stderr=subprocess.PIPE,
3581
 
                                      bufsize=1)
 
3042
            # stderr=STDOUT would be ideal, but until we prevent noise on
 
3043
            # stderr it can interrupt the subunit protocol.
 
3044
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
 
3045
                bufsize=1)
3582
3046
            test = TestInSubprocess(process, test_list_file_name)
3583
3047
            result.append(test)
3584
3048
        except:
3587
3051
    return result
3588
3052
 
3589
3053
 
3590
 
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3591
 
    """Generate profiling data for all activity between start and success.
3592
 
    
3593
 
    The profile data is appended to the test's _benchcalls attribute and can
3594
 
    be accessed by the forwarded-to TestResult.
 
3054
class BZRTransformingResult(unittest.TestResult):
3595
3055
 
3596
 
    While it might be cleaner do accumulate this in stopTest, addSuccess is
3597
 
    where our existing output support for lsprof is, and this class aims to
3598
 
    fit in with that: while it could be moved it's not necessary to accomplish
3599
 
    test profiling, nor would it be dramatically cleaner.
3600
 
    """
 
3056
    def __init__(self, target):
 
3057
        unittest.TestResult.__init__(self)
 
3058
        self.result = target
3601
3059
 
3602
3060
    def startTest(self, test):
3603
 
        self.profiler = bzrlib.lsprof.BzrProfiler()
3604
 
        # Prevent deadlocks in tests that use lsprof: those tests will
3605
 
        # unavoidably fail.
3606
 
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3607
 
        self.profiler.start()
3608
 
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
 
3061
        self.result.startTest(test)
 
3062
 
 
3063
    def stopTest(self, test):
 
3064
        self.result.stopTest(test)
 
3065
 
 
3066
    def addError(self, test, err):
 
3067
        feature = self._error_looks_like('UnavailableFeature: ', err)
 
3068
        if feature is not None:
 
3069
            self.result.addNotSupported(test, feature)
 
3070
        else:
 
3071
            self.result.addError(test, err)
 
3072
 
 
3073
    def addFailure(self, test, err):
 
3074
        known = self._error_looks_like('KnownFailure: ', err)
 
3075
        if known is not None:
 
3076
            self.result._addKnownFailure(test, [KnownFailure,
 
3077
                                                KnownFailure(known), None])
 
3078
        else:
 
3079
            self.result.addFailure(test, err)
 
3080
 
 
3081
    def addSkip(self, test, reason):
 
3082
        self.result.addSkip(test, reason)
3609
3083
 
3610
3084
    def addSuccess(self, test):
3611
 
        stats = self.profiler.stop()
3612
 
        try:
3613
 
            calls = test._benchcalls
3614
 
        except AttributeError:
3615
 
            test._benchcalls = []
3616
 
            calls = test._benchcalls
3617
 
        calls.append(((test.id(), "", ""), stats))
3618
 
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
 
3085
        self.result.addSuccess(test)
3619
3086
 
3620
 
    def stopTest(self, test):
3621
 
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3622
 
        self.profiler = None
 
3087
    def _error_looks_like(self, prefix, err):
 
3088
        """Deserialize exception and returns the stringify value."""
 
3089
        import subunit
 
3090
        value = None
 
3091
        typ, exc, _ = err
 
3092
        if isinstance(exc, subunit.RemoteException):
 
3093
            # stringify the exception gives access to the remote traceback
 
3094
            # We search the last line for 'prefix'
 
3095
            lines = str(exc).split('\n')
 
3096
            while lines and not lines[-1]:
 
3097
                lines.pop(-1)
 
3098
            if lines:
 
3099
                if lines[-1].startswith(prefix):
 
3100
                    value = lines[-1][len(prefix):]
 
3101
        return value
3623
3102
 
3624
3103
 
3625
3104
# Controlled by "bzr selftest -E=..." option
3626
 
# Currently supported:
3627
 
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
3628
 
#                           preserves any flags supplied at the command line.
3629
 
#   -Edisable_lock_checks   Turns errors in mismatched locks into simple prints
3630
 
#                           rather than failing tests. And no longer raise
3631
 
#                           LockContention when fctnl locks are not being used
3632
 
#                           with proper exclusion rules.
3633
 
#   -Ethreads               Will display thread ident at creation/join time to
3634
 
#                           help track thread leaks
3635
 
 
3636
 
#   -Econfig_stats          Will collect statistics using addDetail
3637
3105
selftest_debug_flags = set()
3638
3106
 
3639
3107
 
3652
3120
             starting_with=None,
3653
3121
             runner_class=None,
3654
3122
             suite_decorators=None,
3655
 
             stream=None,
3656
 
             lsprof_tests=False,
3657
3123
             ):
3658
3124
    """Run the whole test suite under the enhanced runner"""
3659
3125
    # XXX: Very ugly way to do this...
3676
3142
            keep_only = None
3677
3143
        else:
3678
3144
            keep_only = load_test_id_list(load_list)
3679
 
        if starting_with:
3680
 
            starting_with = [test_prefix_alias_registry.resolve_alias(start)
3681
 
                             for start in starting_with]
3682
3145
        if test_suite_factory is None:
3683
 
            # Reduce loading time by loading modules based on the starting_with
3684
 
            # patterns.
3685
3146
            suite = test_suite(keep_only, starting_with)
3686
3147
        else:
3687
3148
            suite = test_suite_factory()
3688
 
        if starting_with:
3689
 
            # But always filter as requested.
3690
 
            suite = filter_suite_by_id_startswith(suite, starting_with)
3691
 
        result_decorators = []
3692
 
        if lsprof_tests:
3693
 
            result_decorators.append(ProfileResult)
3694
3149
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3695
3150
                     stop_on_failure=stop_on_failure,
3696
3151
                     transport=transport,
3703
3158
                     strict=strict,
3704
3159
                     runner_class=runner_class,
3705
3160
                     suite_decorators=suite_decorators,
3706
 
                     stream=stream,
3707
 
                     result_decorators=result_decorators,
3708
3161
                     )
3709
3162
    finally:
3710
3163
        default_transport = old_transport
3833
3286
                key, obj, help=help, info=info, override_existing=False)
3834
3287
        except KeyError:
3835
3288
            actual = self.get(key)
3836
 
            trace.note(
3837
 
                'Test prefix alias %s is already used for %s, ignoring %s'
3838
 
                % (key, actual, obj))
 
3289
            note('Test prefix alias %s is already used for %s, ignoring %s'
 
3290
                 % (key, actual, obj))
3839
3291
 
3840
3292
    def resolve_alias(self, id_start):
3841
3293
        """Replace the alias by the prefix in the given string.
3859
3311
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
3860
3312
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
3861
3313
 
3862
 
# Obvious highest levels prefixes, feel free to add your own via a plugin
 
3314
# Obvious higest levels prefixes, feel free to add your own via a plugin
3863
3315
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
3864
3316
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
3865
3317
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
3867
3319
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
3868
3320
 
3869
3321
 
3870
 
def _test_suite_testmod_names():
3871
 
    """Return the standard list of test module names to test."""
3872
 
    return [
3873
 
        'bzrlib.doc',
3874
 
        'bzrlib.tests.blackbox',
3875
 
        'bzrlib.tests.commands',
3876
 
        'bzrlib.tests.doc_generate',
3877
 
        'bzrlib.tests.per_branch',
3878
 
        'bzrlib.tests.per_bzrdir',
3879
 
        'bzrlib.tests.per_controldir',
3880
 
        'bzrlib.tests.per_controldir_colo',
3881
 
        'bzrlib.tests.per_foreign_vcs',
3882
 
        'bzrlib.tests.per_interrepository',
3883
 
        'bzrlib.tests.per_intertree',
3884
 
        'bzrlib.tests.per_inventory',
3885
 
        'bzrlib.tests.per_interbranch',
3886
 
        'bzrlib.tests.per_lock',
3887
 
        'bzrlib.tests.per_merger',
3888
 
        'bzrlib.tests.per_transport',
3889
 
        'bzrlib.tests.per_tree',
3890
 
        'bzrlib.tests.per_pack_repository',
3891
 
        'bzrlib.tests.per_repository',
3892
 
        'bzrlib.tests.per_repository_chk',
3893
 
        'bzrlib.tests.per_repository_reference',
3894
 
        'bzrlib.tests.per_repository_vf',
3895
 
        'bzrlib.tests.per_uifactory',
3896
 
        'bzrlib.tests.per_versionedfile',
3897
 
        'bzrlib.tests.per_workingtree',
3898
 
        'bzrlib.tests.test__annotator',
3899
 
        'bzrlib.tests.test__bencode',
3900
 
        'bzrlib.tests.test__btree_serializer',
3901
 
        'bzrlib.tests.test__chk_map',
3902
 
        'bzrlib.tests.test__dirstate_helpers',
3903
 
        'bzrlib.tests.test__groupcompress',
3904
 
        'bzrlib.tests.test__known_graph',
3905
 
        'bzrlib.tests.test__rio',
3906
 
        'bzrlib.tests.test__simple_set',
3907
 
        'bzrlib.tests.test__static_tuple',
3908
 
        'bzrlib.tests.test__walkdirs_win32',
3909
 
        'bzrlib.tests.test_ancestry',
3910
 
        'bzrlib.tests.test_annotate',
3911
 
        'bzrlib.tests.test_api',
3912
 
        'bzrlib.tests.test_atomicfile',
3913
 
        'bzrlib.tests.test_bad_files',
3914
 
        'bzrlib.tests.test_bisect_multi',
3915
 
        'bzrlib.tests.test_branch',
3916
 
        'bzrlib.tests.test_branchbuilder',
3917
 
        'bzrlib.tests.test_btree_index',
3918
 
        'bzrlib.tests.test_bugtracker',
3919
 
        'bzrlib.tests.test_bundle',
3920
 
        'bzrlib.tests.test_bzrdir',
3921
 
        'bzrlib.tests.test__chunks_to_lines',
3922
 
        'bzrlib.tests.test_cache_utf8',
3923
 
        'bzrlib.tests.test_chk_map',
3924
 
        'bzrlib.tests.test_chk_serializer',
3925
 
        'bzrlib.tests.test_chunk_writer',
3926
 
        'bzrlib.tests.test_clean_tree',
3927
 
        'bzrlib.tests.test_cleanup',
3928
 
        'bzrlib.tests.test_cmdline',
3929
 
        'bzrlib.tests.test_commands',
3930
 
        'bzrlib.tests.test_commit',
3931
 
        'bzrlib.tests.test_commit_merge',
3932
 
        'bzrlib.tests.test_config',
3933
 
        'bzrlib.tests.test_conflicts',
3934
 
        'bzrlib.tests.test_controldir',
3935
 
        'bzrlib.tests.test_counted_lock',
3936
 
        'bzrlib.tests.test_crash',
3937
 
        'bzrlib.tests.test_decorators',
3938
 
        'bzrlib.tests.test_delta',
3939
 
        'bzrlib.tests.test_debug',
3940
 
        'bzrlib.tests.test_diff',
3941
 
        'bzrlib.tests.test_directory_service',
3942
 
        'bzrlib.tests.test_dirstate',
3943
 
        'bzrlib.tests.test_email_message',
3944
 
        'bzrlib.tests.test_eol_filters',
3945
 
        'bzrlib.tests.test_errors',
3946
 
        'bzrlib.tests.test_export',
3947
 
        'bzrlib.tests.test_export_pot',
3948
 
        'bzrlib.tests.test_extract',
3949
 
        'bzrlib.tests.test_features',
3950
 
        'bzrlib.tests.test_fetch',
3951
 
        'bzrlib.tests.test_fixtures',
3952
 
        'bzrlib.tests.test_fifo_cache',
3953
 
        'bzrlib.tests.test_filters',
3954
 
        'bzrlib.tests.test_filter_tree',
3955
 
        'bzrlib.tests.test_ftp_transport',
3956
 
        'bzrlib.tests.test_foreign',
3957
 
        'bzrlib.tests.test_generate_docs',
3958
 
        'bzrlib.tests.test_generate_ids',
3959
 
        'bzrlib.tests.test_globbing',
3960
 
        'bzrlib.tests.test_gpg',
3961
 
        'bzrlib.tests.test_graph',
3962
 
        'bzrlib.tests.test_groupcompress',
3963
 
        'bzrlib.tests.test_hashcache',
3964
 
        'bzrlib.tests.test_help',
3965
 
        'bzrlib.tests.test_hooks',
3966
 
        'bzrlib.tests.test_http',
3967
 
        'bzrlib.tests.test_http_response',
3968
 
        'bzrlib.tests.test_https_ca_bundle',
3969
 
        'bzrlib.tests.test_i18n',
3970
 
        'bzrlib.tests.test_identitymap',
3971
 
        'bzrlib.tests.test_ignores',
3972
 
        'bzrlib.tests.test_index',
3973
 
        'bzrlib.tests.test_import_tariff',
3974
 
        'bzrlib.tests.test_info',
3975
 
        'bzrlib.tests.test_inv',
3976
 
        'bzrlib.tests.test_inventory_delta',
3977
 
        'bzrlib.tests.test_knit',
3978
 
        'bzrlib.tests.test_lazy_import',
3979
 
        'bzrlib.tests.test_lazy_regex',
3980
 
        'bzrlib.tests.test_library_state',
3981
 
        'bzrlib.tests.test_lock',
3982
 
        'bzrlib.tests.test_lockable_files',
3983
 
        'bzrlib.tests.test_lockdir',
3984
 
        'bzrlib.tests.test_log',
3985
 
        'bzrlib.tests.test_lru_cache',
3986
 
        'bzrlib.tests.test_lsprof',
3987
 
        'bzrlib.tests.test_mail_client',
3988
 
        'bzrlib.tests.test_matchers',
3989
 
        'bzrlib.tests.test_memorytree',
3990
 
        'bzrlib.tests.test_merge',
3991
 
        'bzrlib.tests.test_merge3',
3992
 
        'bzrlib.tests.test_merge_core',
3993
 
        'bzrlib.tests.test_merge_directive',
3994
 
        'bzrlib.tests.test_mergetools',
3995
 
        'bzrlib.tests.test_missing',
3996
 
        'bzrlib.tests.test_msgeditor',
3997
 
        'bzrlib.tests.test_multiparent',
3998
 
        'bzrlib.tests.test_mutabletree',
3999
 
        'bzrlib.tests.test_nonascii',
4000
 
        'bzrlib.tests.test_options',
4001
 
        'bzrlib.tests.test_osutils',
4002
 
        'bzrlib.tests.test_osutils_encodings',
4003
 
        'bzrlib.tests.test_pack',
4004
 
        'bzrlib.tests.test_patch',
4005
 
        'bzrlib.tests.test_patches',
4006
 
        'bzrlib.tests.test_permissions',
4007
 
        'bzrlib.tests.test_plugins',
4008
 
        'bzrlib.tests.test_progress',
4009
 
        'bzrlib.tests.test_pyutils',
4010
 
        'bzrlib.tests.test_read_bundle',
4011
 
        'bzrlib.tests.test_reconcile',
4012
 
        'bzrlib.tests.test_reconfigure',
4013
 
        'bzrlib.tests.test_registry',
4014
 
        'bzrlib.tests.test_remote',
4015
 
        'bzrlib.tests.test_rename_map',
4016
 
        'bzrlib.tests.test_repository',
4017
 
        'bzrlib.tests.test_revert',
4018
 
        'bzrlib.tests.test_revision',
4019
 
        'bzrlib.tests.test_revisionspec',
4020
 
        'bzrlib.tests.test_revisiontree',
4021
 
        'bzrlib.tests.test_rio',
4022
 
        'bzrlib.tests.test_rules',
4023
 
        'bzrlib.tests.test_sampler',
4024
 
        'bzrlib.tests.test_scenarios',
4025
 
        'bzrlib.tests.test_script',
4026
 
        'bzrlib.tests.test_selftest',
4027
 
        'bzrlib.tests.test_serializer',
4028
 
        'bzrlib.tests.test_setup',
4029
 
        'bzrlib.tests.test_sftp_transport',
4030
 
        'bzrlib.tests.test_shelf',
4031
 
        'bzrlib.tests.test_shelf_ui',
4032
 
        'bzrlib.tests.test_smart',
4033
 
        'bzrlib.tests.test_smart_add',
4034
 
        'bzrlib.tests.test_smart_request',
4035
 
        'bzrlib.tests.test_smart_transport',
4036
 
        'bzrlib.tests.test_smtp_connection',
4037
 
        'bzrlib.tests.test_source',
4038
 
        'bzrlib.tests.test_ssh_transport',
4039
 
        'bzrlib.tests.test_status',
4040
 
        'bzrlib.tests.test_store',
4041
 
        'bzrlib.tests.test_strace',
4042
 
        'bzrlib.tests.test_subsume',
4043
 
        'bzrlib.tests.test_switch',
4044
 
        'bzrlib.tests.test_symbol_versioning',
4045
 
        'bzrlib.tests.test_tag',
4046
 
        'bzrlib.tests.test_test_server',
4047
 
        'bzrlib.tests.test_testament',
4048
 
        'bzrlib.tests.test_textfile',
4049
 
        'bzrlib.tests.test_textmerge',
4050
 
        'bzrlib.tests.test_cethread',
4051
 
        'bzrlib.tests.test_timestamp',
4052
 
        'bzrlib.tests.test_trace',
4053
 
        'bzrlib.tests.test_transactions',
4054
 
        'bzrlib.tests.test_transform',
4055
 
        'bzrlib.tests.test_transport',
4056
 
        'bzrlib.tests.test_transport_log',
4057
 
        'bzrlib.tests.test_tree',
4058
 
        'bzrlib.tests.test_treebuilder',
4059
 
        'bzrlib.tests.test_treeshape',
4060
 
        'bzrlib.tests.test_tsort',
4061
 
        'bzrlib.tests.test_tuned_gzip',
4062
 
        'bzrlib.tests.test_ui',
4063
 
        'bzrlib.tests.test_uncommit',
4064
 
        'bzrlib.tests.test_upgrade',
4065
 
        'bzrlib.tests.test_upgrade_stacked',
4066
 
        'bzrlib.tests.test_urlutils',
4067
 
        'bzrlib.tests.test_utextwrap',
4068
 
        'bzrlib.tests.test_version',
4069
 
        'bzrlib.tests.test_version_info',
4070
 
        'bzrlib.tests.test_versionedfile',
4071
 
        'bzrlib.tests.test_weave',
4072
 
        'bzrlib.tests.test_whitebox',
4073
 
        'bzrlib.tests.test_win32utils',
4074
 
        'bzrlib.tests.test_workingtree',
4075
 
        'bzrlib.tests.test_workingtree_4',
4076
 
        'bzrlib.tests.test_wsgi',
4077
 
        'bzrlib.tests.test_xml',
4078
 
        ]
4079
 
 
4080
 
 
4081
 
def _test_suite_modules_to_doctest():
4082
 
    """Return the list of modules to doctest."""
4083
 
    if __doc__ is None:
4084
 
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
4085
 
        return []
4086
 
    return [
4087
 
        'bzrlib',
4088
 
        'bzrlib.branchbuilder',
4089
 
        'bzrlib.decorators',
4090
 
        'bzrlib.inventory',
4091
 
        'bzrlib.iterablefile',
4092
 
        'bzrlib.lockdir',
4093
 
        'bzrlib.merge3',
4094
 
        'bzrlib.option',
4095
 
        'bzrlib.pyutils',
4096
 
        'bzrlib.symbol_versioning',
4097
 
        'bzrlib.tests',
4098
 
        'bzrlib.tests.fixtures',
4099
 
        'bzrlib.timestamp',
4100
 
        'bzrlib.transport.http',
4101
 
        'bzrlib.version_info_formats.format_custom',
4102
 
        ]
4103
 
 
4104
 
 
4105
3322
def test_suite(keep_only=None, starting_with=None):
4106
3323
    """Build and return TestSuite for the whole of bzrlib.
4107
3324
 
4113
3330
    This function can be replaced if you need to change the default test
4114
3331
    suite on a global basis, but it is not encouraged.
4115
3332
    """
 
3333
    testmod_names = [
 
3334
                   'bzrlib.doc',
 
3335
                   'bzrlib.tests.blackbox',
 
3336
                   'bzrlib.tests.branch_implementations',
 
3337
                   'bzrlib.tests.bzrdir_implementations',
 
3338
                   'bzrlib.tests.commands',
 
3339
                   'bzrlib.tests.interrepository_implementations',
 
3340
                   'bzrlib.tests.intertree_implementations',
 
3341
                   'bzrlib.tests.inventory_implementations',
 
3342
                   'bzrlib.tests.per_interbranch',
 
3343
                   'bzrlib.tests.per_lock',
 
3344
                   'bzrlib.tests.per_repository',
 
3345
                   'bzrlib.tests.per_repository_chk',
 
3346
                   'bzrlib.tests.per_repository_reference',
 
3347
                   'bzrlib.tests.test__chk_map',
 
3348
                   'bzrlib.tests.test__dirstate_helpers',
 
3349
                   'bzrlib.tests.test__groupcompress',
 
3350
                   'bzrlib.tests.test__rio',
 
3351
                   'bzrlib.tests.test__walkdirs_win32',
 
3352
                   'bzrlib.tests.test_ancestry',
 
3353
                   'bzrlib.tests.test_annotate',
 
3354
                   'bzrlib.tests.test_api',
 
3355
                   'bzrlib.tests.test_atomicfile',
 
3356
                   'bzrlib.tests.test_bad_files',
 
3357
                   'bzrlib.tests.test_bencode',
 
3358
                   'bzrlib.tests.test_bisect_multi',
 
3359
                   'bzrlib.tests.test_branch',
 
3360
                   'bzrlib.tests.test_branchbuilder',
 
3361
                   'bzrlib.tests.test_btree_index',
 
3362
                   'bzrlib.tests.test_bugtracker',
 
3363
                   'bzrlib.tests.test_bundle',
 
3364
                   'bzrlib.tests.test_bzrdir',
 
3365
                   'bzrlib.tests.test__chunks_to_lines',
 
3366
                   'bzrlib.tests.test_cache_utf8',
 
3367
                   'bzrlib.tests.test_chk_map',
 
3368
                   'bzrlib.tests.test_chk_serializer',
 
3369
                   'bzrlib.tests.test_chunk_writer',
 
3370
                   'bzrlib.tests.test_clean_tree',
 
3371
                   'bzrlib.tests.test_commands',
 
3372
                   'bzrlib.tests.test_commit',
 
3373
                   'bzrlib.tests.test_commit_merge',
 
3374
                   'bzrlib.tests.test_config',
 
3375
                   'bzrlib.tests.test_conflicts',
 
3376
                   'bzrlib.tests.test_counted_lock',
 
3377
                   'bzrlib.tests.test_decorators',
 
3378
                   'bzrlib.tests.test_delta',
 
3379
                   'bzrlib.tests.test_debug',
 
3380
                   'bzrlib.tests.test_deprecated_graph',
 
3381
                   'bzrlib.tests.test_diff',
 
3382
                   'bzrlib.tests.test_directory_service',
 
3383
                   'bzrlib.tests.test_dirstate',
 
3384
                   'bzrlib.tests.test_email_message',
 
3385
                   'bzrlib.tests.test_eol_filters',
 
3386
                   'bzrlib.tests.test_errors',
 
3387
                   'bzrlib.tests.test_export',
 
3388
                   'bzrlib.tests.test_extract',
 
3389
                   'bzrlib.tests.test_fetch',
 
3390
                   'bzrlib.tests.test_fifo_cache',
 
3391
                   'bzrlib.tests.test_filters',
 
3392
                   'bzrlib.tests.test_ftp_transport',
 
3393
                   'bzrlib.tests.test_foreign',
 
3394
                   'bzrlib.tests.test_generate_docs',
 
3395
                   'bzrlib.tests.test_generate_ids',
 
3396
                   'bzrlib.tests.test_globbing',
 
3397
                   'bzrlib.tests.test_gpg',
 
3398
                   'bzrlib.tests.test_graph',
 
3399
                   'bzrlib.tests.test_groupcompress',
 
3400
                   'bzrlib.tests.test_hashcache',
 
3401
                   'bzrlib.tests.test_help',
 
3402
                   'bzrlib.tests.test_hooks',
 
3403
                   'bzrlib.tests.test_http',
 
3404
                   'bzrlib.tests.test_http_response',
 
3405
                   'bzrlib.tests.test_https_ca_bundle',
 
3406
                   'bzrlib.tests.test_identitymap',
 
3407
                   'bzrlib.tests.test_ignores',
 
3408
                   'bzrlib.tests.test_index',
 
3409
                   'bzrlib.tests.test_info',
 
3410
                   'bzrlib.tests.test_inv',
 
3411
                   'bzrlib.tests.test_inventory_delta',
 
3412
                   'bzrlib.tests.test_knit',
 
3413
                   'bzrlib.tests.test_lazy_import',
 
3414
                   'bzrlib.tests.test_lazy_regex',
 
3415
                   'bzrlib.tests.test_lockable_files',
 
3416
                   'bzrlib.tests.test_lockdir',
 
3417
                   'bzrlib.tests.test_log',
 
3418
                   'bzrlib.tests.test_lru_cache',
 
3419
                   'bzrlib.tests.test_lsprof',
 
3420
                   'bzrlib.tests.test_mail_client',
 
3421
                   'bzrlib.tests.test_memorytree',
 
3422
                   'bzrlib.tests.test_merge',
 
3423
                   'bzrlib.tests.test_merge3',
 
3424
                   'bzrlib.tests.test_merge_core',
 
3425
                   'bzrlib.tests.test_merge_directive',
 
3426
                   'bzrlib.tests.test_missing',
 
3427
                   'bzrlib.tests.test_msgeditor',
 
3428
                   'bzrlib.tests.test_multiparent',
 
3429
                   'bzrlib.tests.test_mutabletree',
 
3430
                   'bzrlib.tests.test_nonascii',
 
3431
                   'bzrlib.tests.test_options',
 
3432
                   'bzrlib.tests.test_osutils',
 
3433
                   'bzrlib.tests.test_osutils_encodings',
 
3434
                   'bzrlib.tests.test_pack',
 
3435
                   'bzrlib.tests.test_pack_repository',
 
3436
                   'bzrlib.tests.test_patch',
 
3437
                   'bzrlib.tests.test_patches',
 
3438
                   'bzrlib.tests.test_permissions',
 
3439
                   'bzrlib.tests.test_plugins',
 
3440
                   'bzrlib.tests.test_progress',
 
3441
                   'bzrlib.tests.test_read_bundle',
 
3442
                   'bzrlib.tests.test_reconcile',
 
3443
                   'bzrlib.tests.test_reconfigure',
 
3444
                   'bzrlib.tests.test_registry',
 
3445
                   'bzrlib.tests.test_remote',
 
3446
                   'bzrlib.tests.test_rename_map',
 
3447
                   'bzrlib.tests.test_repository',
 
3448
                   'bzrlib.tests.test_revert',
 
3449
                   'bzrlib.tests.test_revision',
 
3450
                   'bzrlib.tests.test_revisionspec',
 
3451
                   'bzrlib.tests.test_revisiontree',
 
3452
                   'bzrlib.tests.test_rio',
 
3453
                   'bzrlib.tests.test_rules',
 
3454
                   'bzrlib.tests.test_sampler',
 
3455
                   'bzrlib.tests.test_selftest',
 
3456
                   'bzrlib.tests.test_serializer',
 
3457
                   'bzrlib.tests.test_setup',
 
3458
                   'bzrlib.tests.test_sftp_transport',
 
3459
                   'bzrlib.tests.test_shelf',
 
3460
                   'bzrlib.tests.test_shelf_ui',
 
3461
                   'bzrlib.tests.test_smart',
 
3462
                   'bzrlib.tests.test_smart_add',
 
3463
                   'bzrlib.tests.test_smart_request',
 
3464
                   'bzrlib.tests.test_smart_transport',
 
3465
                   'bzrlib.tests.test_smtp_connection',
 
3466
                   'bzrlib.tests.test_source',
 
3467
                   'bzrlib.tests.test_ssh_transport',
 
3468
                   'bzrlib.tests.test_status',
 
3469
                   'bzrlib.tests.test_store',
 
3470
                   'bzrlib.tests.test_strace',
 
3471
                   'bzrlib.tests.test_subsume',
 
3472
                   'bzrlib.tests.test_switch',
 
3473
                   'bzrlib.tests.test_symbol_versioning',
 
3474
                   'bzrlib.tests.test_tag',
 
3475
                   'bzrlib.tests.test_testament',
 
3476
                   'bzrlib.tests.test_textfile',
 
3477
                   'bzrlib.tests.test_textmerge',
 
3478
                   'bzrlib.tests.test_timestamp',
 
3479
                   'bzrlib.tests.test_trace',
 
3480
                   'bzrlib.tests.test_transactions',
 
3481
                   'bzrlib.tests.test_transform',
 
3482
                   'bzrlib.tests.test_transport',
 
3483
                   'bzrlib.tests.test_transport_implementations',
 
3484
                   'bzrlib.tests.test_transport_log',
 
3485
                   'bzrlib.tests.test_tree',
 
3486
                   'bzrlib.tests.test_treebuilder',
 
3487
                   'bzrlib.tests.test_tsort',
 
3488
                   'bzrlib.tests.test_tuned_gzip',
 
3489
                   'bzrlib.tests.test_ui',
 
3490
                   'bzrlib.tests.test_uncommit',
 
3491
                   'bzrlib.tests.test_upgrade',
 
3492
                   'bzrlib.tests.test_upgrade_stacked',
 
3493
                   'bzrlib.tests.test_urlutils',
 
3494
                   'bzrlib.tests.test_version',
 
3495
                   'bzrlib.tests.test_version_info',
 
3496
                   'bzrlib.tests.test_versionedfile',
 
3497
                   'bzrlib.tests.test_weave',
 
3498
                   'bzrlib.tests.test_whitebox',
 
3499
                   'bzrlib.tests.test_win32utils',
 
3500
                   'bzrlib.tests.test_workingtree',
 
3501
                   'bzrlib.tests.test_workingtree_4',
 
3502
                   'bzrlib.tests.test_wsgi',
 
3503
                   'bzrlib.tests.test_xml',
 
3504
                   'bzrlib.tests.tree_implementations',
 
3505
                   'bzrlib.tests.workingtree_implementations',
 
3506
                   ]
4116
3507
 
4117
3508
    loader = TestUtil.TestLoader()
4118
3509
 
4119
 
    if keep_only is not None:
4120
 
        id_filter = TestIdList(keep_only)
4121
3510
    if starting_with:
 
3511
        starting_with = [test_prefix_alias_registry.resolve_alias(start)
 
3512
                         for start in starting_with]
4122
3513
        # We take precedence over keep_only because *at loading time* using
4123
3514
        # both options means we will load less tests for the same final result.
4124
3515
        def interesting_module(name):
4134
3525
        loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
4135
3526
 
4136
3527
    elif keep_only is not None:
 
3528
        id_filter = TestIdList(keep_only)
4137
3529
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
4138
3530
        def interesting_module(name):
4139
3531
            return id_filter.refers_to(name)
4147
3539
    suite = loader.suiteClass()
4148
3540
 
4149
3541
    # modules building their suite with loadTestsFromModuleNames
4150
 
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
4151
 
 
4152
 
    for mod in _test_suite_modules_to_doctest():
 
3542
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
3543
 
 
3544
    modules_to_doctest = [
 
3545
        'bzrlib',
 
3546
        'bzrlib.branchbuilder',
 
3547
        'bzrlib.export',
 
3548
        'bzrlib.inventory',
 
3549
        'bzrlib.iterablefile',
 
3550
        'bzrlib.lockdir',
 
3551
        'bzrlib.merge3',
 
3552
        'bzrlib.option',
 
3553
        'bzrlib.symbol_versioning',
 
3554
        'bzrlib.tests',
 
3555
        'bzrlib.timestamp',
 
3556
        'bzrlib.version_info_formats.format_custom',
 
3557
        ]
 
3558
 
 
3559
    for mod in modules_to_doctest:
4153
3560
        if not interesting_module(mod):
4154
3561
            # No tests to keep here, move along
4155
3562
            continue
4156
3563
        try:
4157
3564
            # note that this really does mean "report only" -- doctest
4158
3565
            # still runs the rest of the examples
4159
 
            doc_suite = IsolatedDocTestSuite(
4160
 
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
3566
            doc_suite = doctest.DocTestSuite(mod,
 
3567
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
4161
3568
        except ValueError, e:
4162
3569
            print '**failed to get doctest for: %s\n%s' % (mod, e)
4163
3570
            raise
4166
3573
        suite.addTest(doc_suite)
4167
3574
 
4168
3575
    default_encoding = sys.getdefaultencoding()
4169
 
    for name, plugin in _mod_plugin.plugins().items():
 
3576
    for name, plugin in bzrlib.plugin.plugins().items():
4170
3577
        if not interesting_module(plugin.module.__name__):
4171
3578
            continue
4172
3579
        plugin_suite = plugin.test_suite()
4178
3585
        if plugin_suite is not None:
4179
3586
            suite.addTest(plugin_suite)
4180
3587
        if default_encoding != sys.getdefaultencoding():
4181
 
            trace.warning(
 
3588
            bzrlib.trace.warning(
4182
3589
                'Plugin "%s" tried to reset default encoding to: %s', name,
4183
3590
                sys.getdefaultencoding())
4184
3591
            reload(sys)
4185
3592
            sys.setdefaultencoding(default_encoding)
4186
3593
 
 
3594
    if starting_with:
 
3595
        suite = filter_suite_by_id_startswith(suite, starting_with)
 
3596
 
4187
3597
    if keep_only is not None:
4188
3598
        # Now that the referred modules have loaded their tests, keep only the
4189
3599
        # requested ones.
4199
3609
            # Some tests mentioned in the list are not in the test suite. The
4200
3610
            # list may be out of date, report to the tester.
4201
3611
            for id in not_found:
4202
 
                trace.warning('"%s" not found in the test suite', id)
 
3612
                bzrlib.trace.warning('"%s" not found in the test suite', id)
4203
3613
        for id in duplicates:
4204
 
            trace.warning('"%s" is used as an id by several tests', id)
 
3614
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
4205
3615
 
4206
3616
    return suite
4207
3617
 
4208
3618
 
4209
 
def multiply_scenarios(*scenarios):
4210
 
    """Multiply two or more iterables of scenarios.
4211
 
 
4212
 
    It is safe to pass scenario generators or iterators.
4213
 
 
4214
 
    :returns: A list of compound scenarios: the cross-product of all 
4215
 
        scenarios, with the names concatenated and the parameters
4216
 
        merged together.
4217
 
    """
4218
 
    return reduce(_multiply_two_scenarios, map(list, scenarios))
4219
 
 
4220
 
 
4221
 
def _multiply_two_scenarios(scenarios_left, scenarios_right):
 
3619
def multiply_scenarios(scenarios_left, scenarios_right):
4222
3620
    """Multiply two sets of scenarios.
4223
3621
 
4224
3622
    :returns: the cartesian product of the two sets of scenarios, that is
4255
3653
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
4256
3654
    ...     [('one', dict(param=1)),
4257
3655
    ...      ('two', dict(param=2))],
4258
 
    ...     TestUtil.TestSuite())
 
3656
    ...     TestSuite())
4259
3657
    >>> tests = list(iter_suite_tests(r))
4260
3658
    >>> len(tests)
4261
3659
    2
4308
3706
    :param new_id: The id to assign to it.
4309
3707
    :return: The new test.
4310
3708
    """
4311
 
    new_test = copy.copy(test)
 
3709
    from copy import deepcopy
 
3710
    new_test = deepcopy(test)
4312
3711
    new_test.id = lambda: new_id
4313
 
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
4314
 
    # causes cloned tests to share the 'details' dict.  This makes it hard to
4315
 
    # read the test output for parameterized tests, because tracebacks will be
4316
 
    # associated with irrelevant tests.
4317
 
    try:
4318
 
        details = new_test._TestCase__details
4319
 
    except AttributeError:
4320
 
        # must be a different version of testtools than expected.  Do nothing.
4321
 
        pass
4322
 
    else:
4323
 
        # Reset the '__details' dict.
4324
 
        new_test._TestCase__details = {}
4325
3712
    return new_test
4326
3713
 
4327
3714
 
4328
 
def permute_tests_for_extension(standard_tests, loader, py_module_name,
4329
 
                                ext_module_name):
4330
 
    """Helper for permutating tests against an extension module.
4331
 
 
4332
 
    This is meant to be used inside a modules 'load_tests()' function. It will
4333
 
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
4334
 
    against both implementations. Setting 'test.module' to the appropriate
4335
 
    module. See bzrlib.tests.test__chk_map.load_tests as an example.
4336
 
 
4337
 
    :param standard_tests: A test suite to permute
4338
 
    :param loader: A TestLoader
4339
 
    :param py_module_name: The python path to a python module that can always
4340
 
        be loaded, and will be considered the 'python' implementation. (eg
4341
 
        'bzrlib._chk_map_py')
4342
 
    :param ext_module_name: The python path to an extension module. If the
4343
 
        module cannot be loaded, a single test will be added, which notes that
4344
 
        the module is not available. If it can be loaded, all standard_tests
4345
 
        will be run against that module.
4346
 
    :return: (suite, feature) suite is a test-suite that has all the permuted
4347
 
        tests. feature is the Feature object that can be used to determine if
4348
 
        the module is available.
4349
 
    """
4350
 
 
4351
 
    from bzrlib.tests.features import ModuleAvailableFeature
4352
 
    py_module = pyutils.get_named_object(py_module_name)
4353
 
    scenarios = [
4354
 
        ('python', {'module': py_module}),
4355
 
    ]
4356
 
    suite = loader.suiteClass()
4357
 
    feature = ModuleAvailableFeature(ext_module_name)
4358
 
    if feature.available():
4359
 
        scenarios.append(('C', {'module': feature.module}))
4360
 
    else:
4361
 
        # the compiled module isn't available, so we add a failing test
4362
 
        class FailWithoutFeature(TestCase):
4363
 
            def test_fail(self):
4364
 
                self.requireFeature(feature)
4365
 
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
4366
 
    result = multiply_tests(standard_tests, scenarios, suite)
4367
 
    return result, feature
4368
 
 
4369
 
 
4370
 
def _rmtree_temp_dir(dirname, test_id=None):
 
3715
def _rmtree_temp_dir(dirname):
4371
3716
    # If LANG=C we probably have created some bogus paths
4372
3717
    # which rmtree(unicode) will fail to delete
4373
3718
    # so make sure we are using rmtree(str) to delete everything
4382
3727
    try:
4383
3728
        osutils.rmtree(dirname)
4384
3729
    except OSError, e:
4385
 
        # We don't want to fail here because some useful display will be lost
4386
 
        # otherwise. Polluting the tmp dir is bad, but not giving all the
4387
 
        # possible info to the test runner is even worse.
4388
 
        if test_id != None:
4389
 
            ui.ui_factory.clear_term()
4390
 
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
4391
 
        # Ugly, but the last thing we want here is fail, so bear with it.
4392
 
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
4393
 
                                    ).encode('ascii', 'replace')
4394
 
        sys.stderr.write('Unable to remove testing dir %s\n%s'
4395
 
                         % (os.path.basename(dirname), printable_e))
 
3730
        if sys.platform == 'win32' and e.errno == errno.EACCES:
 
3731
            sys.stderr.write('Permission denied: '
 
3732
                             'unable to remove testing dir '
 
3733
                             '%s\n%s'
 
3734
                             % (os.path.basename(dirname), e))
 
3735
        else:
 
3736
            raise
 
3737
 
 
3738
 
 
3739
class Feature(object):
 
3740
    """An operating system Feature."""
 
3741
 
 
3742
    def __init__(self):
 
3743
        self._available = None
 
3744
 
 
3745
    def available(self):
 
3746
        """Is the feature available?
 
3747
 
 
3748
        :return: True if the feature is available.
 
3749
        """
 
3750
        if self._available is None:
 
3751
            self._available = self._probe()
 
3752
        return self._available
 
3753
 
 
3754
    def _probe(self):
 
3755
        """Implement this method in concrete features.
 
3756
 
 
3757
        :return: True if the feature is available.
 
3758
        """
 
3759
        raise NotImplementedError
 
3760
 
 
3761
    def __str__(self):
 
3762
        if getattr(self, 'feature_name', None):
 
3763
            return self.feature_name()
 
3764
        return self.__class__.__name__
 
3765
 
 
3766
 
 
3767
class _SymlinkFeature(Feature):
 
3768
 
 
3769
    def _probe(self):
 
3770
        return osutils.has_symlinks()
 
3771
 
 
3772
    def feature_name(self):
 
3773
        return 'symlinks'
 
3774
 
 
3775
SymlinkFeature = _SymlinkFeature()
 
3776
 
 
3777
 
 
3778
class _HardlinkFeature(Feature):
 
3779
 
 
3780
    def _probe(self):
 
3781
        return osutils.has_hardlinks()
 
3782
 
 
3783
    def feature_name(self):
 
3784
        return 'hardlinks'
 
3785
 
 
3786
HardlinkFeature = _HardlinkFeature()
 
3787
 
 
3788
 
 
3789
class _OsFifoFeature(Feature):
 
3790
 
 
3791
    def _probe(self):
 
3792
        return getattr(os, 'mkfifo', None)
 
3793
 
 
3794
    def feature_name(self):
 
3795
        return 'filesystem fifos'
 
3796
 
 
3797
OsFifoFeature = _OsFifoFeature()
 
3798
 
 
3799
 
 
3800
class _UnicodeFilenameFeature(Feature):
 
3801
    """Does the filesystem support Unicode filenames?"""
 
3802
 
 
3803
    def _probe(self):
 
3804
        try:
 
3805
            # Check for character combinations unlikely to be covered by any
 
3806
            # single non-unicode encoding. We use the characters
 
3807
            # - greek small letter alpha (U+03B1) and
 
3808
            # - braille pattern dots-123456 (U+283F).
 
3809
            os.stat(u'\u03b1\u283f')
 
3810
        except UnicodeEncodeError:
 
3811
            return False
 
3812
        except (IOError, OSError):
 
3813
            # The filesystem allows the Unicode filename but the file doesn't
 
3814
            # exist.
 
3815
            return True
 
3816
        else:
 
3817
            # The filesystem allows the Unicode filename and the file exists,
 
3818
            # for some reason.
 
3819
            return True
 
3820
 
 
3821
UnicodeFilenameFeature = _UnicodeFilenameFeature()
4396
3822
 
4397
3823
 
4398
3824
def probe_unicode_in_user_encoding():
4428
3854
    return None
4429
3855
 
4430
3856
 
 
3857
class _HTTPSServerFeature(Feature):
 
3858
    """Some tests want an https Server, check if one is available.
 
3859
 
 
3860
    Right now, the only way this is available is under python2.6 which provides
 
3861
    an ssl module.
 
3862
    """
 
3863
 
 
3864
    def _probe(self):
 
3865
        try:
 
3866
            import ssl
 
3867
            return True
 
3868
        except ImportError:
 
3869
            return False
 
3870
 
 
3871
    def feature_name(self):
 
3872
        return 'HTTPSServer'
 
3873
 
 
3874
 
 
3875
HTTPSServerFeature = _HTTPSServerFeature()
 
3876
 
 
3877
 
 
3878
class _UnicodeFilename(Feature):
 
3879
    """Does the filesystem support Unicode filenames?"""
 
3880
 
 
3881
    def _probe(self):
 
3882
        try:
 
3883
            os.stat(u'\u03b1')
 
3884
        except UnicodeEncodeError:
 
3885
            return False
 
3886
        except (IOError, OSError):
 
3887
            # The filesystem allows the Unicode filename but the file doesn't
 
3888
            # exist.
 
3889
            return True
 
3890
        else:
 
3891
            # The filesystem allows the Unicode filename and the file exists,
 
3892
            # for some reason.
 
3893
            return True
 
3894
 
 
3895
UnicodeFilename = _UnicodeFilename()
 
3896
 
 
3897
 
 
3898
class _UTF8Filesystem(Feature):
 
3899
    """Is the filesystem UTF-8?"""
 
3900
 
 
3901
    def _probe(self):
 
3902
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
 
3903
            return True
 
3904
        return False
 
3905
 
 
3906
UTF8Filesystem = _UTF8Filesystem()
 
3907
 
 
3908
 
 
3909
class _CaseInsCasePresFilenameFeature(Feature):
 
3910
    """Is the file-system case insensitive, but case-preserving?"""
 
3911
 
 
3912
    def _probe(self):
 
3913
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
 
3914
        try:
 
3915
            # first check truly case-preserving for created files, then check
 
3916
            # case insensitive when opening existing files.
 
3917
            name = osutils.normpath(name)
 
3918
            base, rel = osutils.split(name)
 
3919
            found_rel = osutils.canonical_relpath(base, name)
 
3920
            return (found_rel == rel
 
3921
                    and os.path.isfile(name.upper())
 
3922
                    and os.path.isfile(name.lower()))
 
3923
        finally:
 
3924
            os.close(fileno)
 
3925
            os.remove(name)
 
3926
 
 
3927
    def feature_name(self):
 
3928
        return "case-insensitive case-preserving filesystem"
 
3929
 
 
3930
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
 
3931
 
 
3932
 
 
3933
class _CaseInsensitiveFilesystemFeature(Feature):
 
3934
    """Check if underlying filesystem is case-insensitive but *not* case
 
3935
    preserving.
 
3936
    """
 
3937
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
 
3938
    # more likely to be case preserving, so this case is rare.
 
3939
 
 
3940
    def _probe(self):
 
3941
        if CaseInsCasePresFilenameFeature.available():
 
3942
            return False
 
3943
 
 
3944
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
 
3945
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
 
3946
            TestCaseWithMemoryTransport.TEST_ROOT = root
 
3947
        else:
 
3948
            root = TestCaseWithMemoryTransport.TEST_ROOT
 
3949
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
 
3950
            dir=root)
 
3951
        name_a = osutils.pathjoin(tdir, 'a')
 
3952
        name_A = osutils.pathjoin(tdir, 'A')
 
3953
        os.mkdir(name_a)
 
3954
        result = osutils.isdir(name_A)
 
3955
        _rmtree_temp_dir(tdir)
 
3956
        return result
 
3957
 
 
3958
    def feature_name(self):
 
3959
        return 'case-insensitive filesystem'
 
3960
 
 
3961
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
 
3962
 
 
3963
 
 
3964
class _SubUnitFeature(Feature):
 
3965
    """Check if subunit is available."""
 
3966
 
 
3967
    def _probe(self):
 
3968
        try:
 
3969
            import subunit
 
3970
            return True
 
3971
        except ImportError:
 
3972
            return False
 
3973
 
 
3974
    def feature_name(self):
 
3975
        return 'subunit'
 
3976
 
 
3977
SubUnitFeature = _SubUnitFeature()
4431
3978
# Only define SubUnitBzrRunner if subunit is available.
4432
3979
try:
4433
3980
    from subunit import TestProtocolClient
4434
 
    from subunit.test_results import AutoTimingTestResultDecorator
4435
 
    class SubUnitBzrProtocolClient(TestProtocolClient):
4436
 
 
4437
 
        def addSuccess(self, test, details=None):
4438
 
            # The subunit client always includes the details in the subunit
4439
 
            # stream, but we don't want to include it in ours.
4440
 
            if details is not None and 'log' in details:
4441
 
                del details['log']
4442
 
            return super(SubUnitBzrProtocolClient, self).addSuccess(
4443
 
                test, details)
4444
 
 
4445
3981
    class SubUnitBzrRunner(TextTestRunner):
4446
3982
        def run(self, test):
4447
 
            result = AutoTimingTestResultDecorator(
4448
 
                SubUnitBzrProtocolClient(self.stream))
 
3983
            result = TestProtocolClient(self.stream)
4449
3984
            test.run(result)
4450
3985
            return result
4451
3986
except ImportError:
4452
3987
    pass
4453
 
 
4454
 
 
4455
 
@deprecated_function(deprecated_in((2, 5, 0)))
4456
 
def ModuleAvailableFeature(name):
4457
 
    from bzrlib.tests import features
4458
 
    return features.ModuleAvailableFeature(name)
4459