~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Ross Lagerwall
  • Date: 2012-08-07 06:32:51 UTC
  • mto: (6437.63.5 2.5)
  • mto: This revision was merged to the branch mainline in revision 6558.
  • Revision ID: rosslagerwall@gmail.com-20120807063251-x9p03ghg2ws8oqjc
Add bzrlib/locale to .bzrignore

bzrlib/locale is generated with ./setup.py build_mo which is in turn called
by ./setup.py build

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
16
16
 
17
17
"""Testing framework extensions"""
18
18
 
19
 
# TODO: Perhaps there should be an API to find out if bzr running under the
20
 
# test suite -- some plugins might want to avoid making intrusive changes if
21
 
# this is the case.  However, we want behaviour under to test to diverge as
22
 
# little as possible, so this should be used rarely if it's added at all.
23
 
# (Suggestion from j-a-meinel, 2005-11-24)
 
19
from __future__ import absolute_import
24
20
 
25
21
# NOTE: Some classes in here use camelCaseNaming() rather than
26
22
# underscore_naming().  That's for consistency with unittest; it's not the
29
25
 
30
26
import atexit
31
27
import codecs
32
 
from copy import copy
 
28
import copy
33
29
from cStringIO import StringIO
34
30
import difflib
35
31
import doctest
36
32
import errno
 
33
import itertools
37
34
import logging
38
 
import math
39
35
import os
40
 
from pprint import pformat
 
36
import platform
 
37
import pprint
41
38
import random
42
39
import re
43
40
import shlex
 
41
import site
44
42
import stat
45
 
from subprocess import Popen, PIPE, STDOUT
 
43
import subprocess
46
44
import sys
47
45
import tempfile
48
46
import threading
54
52
import testtools
55
53
# nb: check this before importing anything else from within it
56
54
_testtools_version = getattr(testtools, '__version__', ())
57
 
if _testtools_version < (0, 9, 2):
58
 
    raise ImportError("need at least testtools 0.9.2: %s is %r"
 
55
if _testtools_version < (0, 9, 5):
 
56
    raise ImportError("need at least testtools 0.9.5: %s is %r"
59
57
        % (testtools.__file__, _testtools_version))
60
58
from testtools import content
61
59
 
 
60
import bzrlib
62
61
from bzrlib import (
63
62
    branchbuilder,
64
63
    bzrdir,
65
64
    chk_map,
 
65
    commands as _mod_commands,
66
66
    config,
 
67
    i18n,
67
68
    debug,
68
69
    errors,
69
70
    hooks,
70
71
    lock as _mod_lock,
 
72
    lockdir,
71
73
    memorytree,
72
74
    osutils,
73
 
    progress,
 
75
    plugin as _mod_plugin,
 
76
    pyutils,
74
77
    ui,
75
78
    urlutils,
76
79
    registry,
 
80
    symbol_versioning,
 
81
    trace,
 
82
    transport as _mod_transport,
77
83
    workingtree,
78
84
    )
79
 
import bzrlib.branch
80
 
import bzrlib.commands
81
 
import bzrlib.timestamp
82
 
import bzrlib.export
83
 
import bzrlib.inventory
84
 
import bzrlib.iterablefile
85
 
import bzrlib.lockdir
86
85
try:
87
86
    import bzrlib.lsprof
88
87
except ImportError:
89
88
    # lsprof not available
90
89
    pass
91
 
from bzrlib.merge import merge_inner
92
 
import bzrlib.merge3
93
 
import bzrlib.plugin
94
 
from bzrlib.smart import client, request, server
95
 
import bzrlib.store
96
 
from bzrlib import symbol_versioning
 
90
from bzrlib.smart import client, request
 
91
from bzrlib.transport import (
 
92
    memory,
 
93
    pathfilter,
 
94
    )
97
95
from bzrlib.symbol_versioning import (
98
 
    DEPRECATED_PARAMETER,
99
96
    deprecated_function,
100
97
    deprecated_in,
101
 
    deprecated_method,
102
 
    deprecated_passed,
103
 
    )
104
 
import bzrlib.trace
105
 
from bzrlib.transport import (
106
 
    get_transport,
107
 
    memory,
108
 
    pathfilter,
109
 
    )
110
 
import bzrlib.transport
111
 
from bzrlib.trace import mutter, note
 
98
    )
112
99
from bzrlib.tests import (
 
100
    fixtures,
113
101
    test_server,
114
102
    TestUtil,
 
103
    treeshape,
115
104
    )
116
 
from bzrlib.tests.http_server import HttpServer
117
 
from bzrlib.tests.TestUtil import (
118
 
                          TestSuite,
119
 
                          TestLoader,
120
 
                          )
121
 
from bzrlib.tests.treeshape import build_tree_contents
122
105
from bzrlib.ui import NullProgressView
123
106
from bzrlib.ui.text import TextUIFactory
124
 
import bzrlib.version_info_formats.format_custom
125
 
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
 
107
from bzrlib.tests.features import _CompatabilityThunkFeature
126
108
 
127
109
# Mark this python module as being part of the implementation
128
110
# of unittest: this gives us better tracebacks where the last
140
122
SUBUNIT_SEEK_SET = 0
141
123
SUBUNIT_SEEK_CUR = 1
142
124
 
143
 
 
144
 
class ExtendedTestResult(unittest._TextTestResult):
 
125
# These are intentionally brought into this namespace. That way plugins, etc
 
126
# can just "from bzrlib.tests import TestCase, TestLoader, etc"
 
127
TestSuite = TestUtil.TestSuite
 
128
TestLoader = TestUtil.TestLoader
 
129
 
 
130
# Tests should run in a clean and clearly defined environment. The goal is to
 
131
# keep them isolated from the running environment as mush as possible. The test
 
132
# framework ensures the variables defined below are set (or deleted if the
 
133
# value is None) before a test is run and reset to their original value after
 
134
# the test is run. Generally if some code depends on an environment variable,
 
135
# the tests should start without this variable in the environment. There are a
 
136
# few exceptions but you shouldn't violate this rule lightly.
 
137
isolated_environ = {
 
138
    'BZR_HOME': None,
 
139
    'HOME': None,
 
140
    'XDG_CONFIG_HOME': None,
 
141
    # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
 
142
    # tests do check our impls match APPDATA
 
143
    'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
144
    'VISUAL': None,
 
145
    'EDITOR': None,
 
146
    'BZR_EMAIL': None,
 
147
    'BZREMAIL': None, # may still be present in the environment
 
148
    'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
 
149
    'BZR_PROGRESS_BAR': None,
 
150
    # This should trap leaks to ~/.bzr.log. This occurs when tests use TestCase
 
151
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
 
152
    # TestCase should not use disk resources, BZR_LOG is one.
 
153
    'BZR_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
154
    'BZR_PLUGIN_PATH': None,
 
155
    'BZR_DISABLE_PLUGINS': None,
 
156
    'BZR_PLUGINS_AT': None,
 
157
    'BZR_CONCURRENCY': None,
 
158
    # Make sure that any text ui tests are consistent regardless of
 
159
    # the environment the test case is run in; you may want tests that
 
160
    # test other combinations.  'dumb' is a reasonable guess for tests
 
161
    # going to a pipe or a StringIO.
 
162
    'TERM': 'dumb',
 
163
    'LINES': '25',
 
164
    'COLUMNS': '80',
 
165
    'BZR_COLUMNS': '80',
 
166
    # Disable SSH Agent
 
167
    'SSH_AUTH_SOCK': None,
 
168
    # Proxies
 
169
    'http_proxy': None,
 
170
    'HTTP_PROXY': None,
 
171
    'https_proxy': None,
 
172
    'HTTPS_PROXY': None,
 
173
    'no_proxy': None,
 
174
    'NO_PROXY': None,
 
175
    'all_proxy': None,
 
176
    'ALL_PROXY': None,
 
177
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
178
    # least. If you do (care), please update this comment
 
179
    # -- vila 20080401
 
180
    'ftp_proxy': None,
 
181
    'FTP_PROXY': None,
 
182
    'BZR_REMOTE_PATH': None,
 
183
    # Generally speaking, we don't want apport reporting on crashes in
 
184
    # the test envirnoment unless we're specifically testing apport,
 
185
    # so that it doesn't leak into the real system environment.  We
 
186
    # use an env var so it propagates to subprocesses.
 
187
    'APPORT_DISABLE': '1',
 
188
    }
 
189
 
 
190
 
 
191
def override_os_environ(test, env=None):
 
192
    """Modify os.environ keeping a copy.
 
193
    
 
194
    :param test: A test instance
 
195
 
 
196
    :param env: A dict containing variable definitions to be installed
 
197
    """
 
198
    if env is None:
 
199
        env = isolated_environ
 
200
    test._original_os_environ = dict([(var, value)
 
201
                                      for var, value in os.environ.iteritems()])
 
202
    for var, value in env.iteritems():
 
203
        osutils.set_or_unset_env(var, value)
 
204
        if var not in test._original_os_environ:
 
205
            # The var is new, add it with a value of None, so
 
206
            # restore_os_environ will delete it
 
207
            test._original_os_environ[var] = None
 
208
 
 
209
 
 
210
def restore_os_environ(test):
 
211
    """Restore os.environ to its original state.
 
212
 
 
213
    :param test: A test instance previously passed to override_os_environ.
 
214
    """
 
215
    for var, value in test._original_os_environ.iteritems():
 
216
        # Restore the original value (or delete it if the value has been set to
 
217
        # None in override_os_environ).
 
218
        osutils.set_or_unset_env(var, value)
 
219
 
 
220
 
 
221
def _clear__type_equality_funcs(test):
 
222
    """Cleanup bound methods stored on TestCase instances
 
223
 
 
224
    Clear the dict breaking a few (mostly) harmless cycles in the affected
 
225
    unittests released with Python 2.6 and initial Python 2.7 versions.
 
226
 
 
227
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
 
228
    shipped in Oneiric, an object with no clear method was used, hence the
 
229
    extra complications, see bug 809048 for details.
 
230
    """
 
231
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
232
    if type_equality_funcs is not None:
 
233
        tef_clear = getattr(type_equality_funcs, "clear", None)
 
234
        if tef_clear is None:
 
235
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
 
236
            if tef_instance_dict is not None:
 
237
                tef_clear = tef_instance_dict.clear
 
238
        if tef_clear is not None:
 
239
            tef_clear()
 
240
 
 
241
 
 
242
class ExtendedTestResult(testtools.TextTestResult):
145
243
    """Accepts, reports and accumulates the results of running tests.
146
244
 
147
245
    Compared to the unittest version this class adds support for
168
266
        :param bench_history: Optionally, a writable file object to accumulate
169
267
            benchmark results.
170
268
        """
171
 
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
269
        testtools.TextTestResult.__init__(self, stream)
172
270
        if bench_history is not None:
173
271
            from bzrlib.version import _get_bzr_source_tree
174
272
            src_tree = _get_bzr_source_tree()
195
293
        self.count = 0
196
294
        self._overall_start_time = time.time()
197
295
        self._strict = strict
 
296
        self._first_thread_leaker_id = None
 
297
        self._tests_leaking_threads_count = 0
 
298
        self._traceback_from_test = None
198
299
 
199
300
    def stopTestRun(self):
200
301
        run = self.testsRun
201
302
        actionTaken = "Ran"
202
303
        stopTime = time.time()
203
304
        timeTaken = stopTime - self.startTime
204
 
        self.printErrors()
205
 
        self.stream.writeln(self.separator2)
206
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
305
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
 
306
        #                the parent class method is similar have to duplicate
 
307
        self._show_list('ERROR', self.errors)
 
308
        self._show_list('FAIL', self.failures)
 
309
        self.stream.write(self.sep2)
 
310
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
207
311
                            run, run != 1 and "s" or "", timeTaken))
208
 
        self.stream.writeln()
209
312
        if not self.wasSuccessful():
210
313
            self.stream.write("FAILED (")
211
314
            failed, errored = map(len, (self.failures, self.errors))
218
321
                if failed or errored: self.stream.write(", ")
219
322
                self.stream.write("known_failure_count=%d" %
220
323
                    self.known_failure_count)
221
 
            self.stream.writeln(")")
 
324
            self.stream.write(")\n")
222
325
        else:
223
326
            if self.known_failure_count:
224
 
                self.stream.writeln("OK (known_failures=%d)" %
 
327
                self.stream.write("OK (known_failures=%d)\n" %
225
328
                    self.known_failure_count)
226
329
            else:
227
 
                self.stream.writeln("OK")
 
330
                self.stream.write("OK\n")
228
331
        if self.skip_count > 0:
229
332
            skipped = self.skip_count
230
 
            self.stream.writeln('%d test%s skipped' %
 
333
            self.stream.write('%d test%s skipped\n' %
231
334
                                (skipped, skipped != 1 and "s" or ""))
232
335
        if self.unsupported:
233
336
            for feature, count in sorted(self.unsupported.items()):
234
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
337
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
235
338
                    (feature, count))
236
339
        if self._strict:
237
340
            ok = self.wasStrictlySuccessful()
238
341
        else:
239
342
            ok = self.wasSuccessful()
240
 
        if TestCase._first_thread_leaker_id:
 
343
        if self._first_thread_leaker_id:
241
344
            self.stream.write(
242
345
                '%s is leaking threads among %d leaking tests.\n' % (
243
 
                TestCase._first_thread_leaker_id,
244
 
                TestCase._leaking_threads_tests))
 
346
                self._first_thread_leaker_id,
 
347
                self._tests_leaking_threads_count))
245
348
            # We don't report the main thread as an active one.
246
349
            self.stream.write(
247
350
                '%d non-main threads were left active in the end.\n'
248
 
                % (TestCase._active_threads - 1))
 
351
                % (len(self._active_threads) - 1))
249
352
 
250
353
    def getDescription(self, test):
251
354
        return test.id()
258
361
 
259
362
    def _elapsedTestTimeString(self):
260
363
        """Return a time string for the overall time the current test has taken."""
261
 
        return self._formatTime(time.time() - self._start_time)
 
364
        return self._formatTime(self._delta_to_float(
 
365
            self._now() - self._start_datetime))
262
366
 
263
367
    def _testTimeString(self, testCase):
264
368
        benchmark_time = self._extractBenchmarkTime(testCase)
275
379
 
276
380
    def _shortened_test_description(self, test):
277
381
        what = test.id()
278
 
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
382
        what = re.sub(r'^bzrlib\.tests\.', '', what)
279
383
        return what
280
384
 
 
385
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
386
    #                multiple times in a row, because the handler is added for
 
387
    #                each test but the container list is shared between cases.
 
388
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
389
    def _record_traceback_from_test(self, exc_info):
 
390
        """Store the traceback from passed exc_info tuple till"""
 
391
        self._traceback_from_test = exc_info[2]
 
392
 
281
393
    def startTest(self, test):
282
 
        unittest.TestResult.startTest(self, test)
 
394
        super(ExtendedTestResult, self).startTest(test)
283
395
        if self.count == 0:
284
396
            self.startTests()
 
397
        self.count += 1
285
398
        self.report_test_start(test)
286
399
        test.number = self.count
287
400
        self._recordTestStartTime()
 
401
        # Make testtools cases give us the real traceback on failure
 
402
        addOnException = getattr(test, "addOnException", None)
 
403
        if addOnException is not None:
 
404
            addOnException(self._record_traceback_from_test)
 
405
        # Only check for thread leaks on bzrlib derived test cases
 
406
        if isinstance(test, TestCase):
 
407
            test.addCleanup(self._check_leaked_threads, test)
 
408
 
 
409
    def stopTest(self, test):
 
410
        super(ExtendedTestResult, self).stopTest(test)
 
411
        # Manually break cycles, means touching various private things but hey
 
412
        getDetails = getattr(test, "getDetails", None)
 
413
        if getDetails is not None:
 
414
            getDetails().clear()
 
415
        _clear__type_equality_funcs(test)
 
416
        self._traceback_from_test = None
288
417
 
289
418
    def startTests(self):
290
 
        import platform
291
 
        if getattr(sys, 'frozen', None) is None:
292
 
            bzr_path = osutils.realpath(sys.argv[0])
293
 
        else:
294
 
            bzr_path = sys.executable
295
 
        self.stream.write(
296
 
            'bzr selftest: %s\n' % (bzr_path,))
297
 
        self.stream.write(
298
 
            '   %s\n' % (
299
 
                    bzrlib.__path__[0],))
300
 
        self.stream.write(
301
 
            '   bzr-%s python-%s %s\n' % (
302
 
                    bzrlib.version_string,
303
 
                    bzrlib._format_version_tuple(sys.version_info),
304
 
                    platform.platform(aliased=1),
305
 
                    ))
306
 
        self.stream.write('\n')
 
419
        self.report_tests_starting()
 
420
        self._active_threads = threading.enumerate()
 
421
 
 
422
    def _check_leaked_threads(self, test):
 
423
        """See if any threads have leaked since last call
 
424
 
 
425
        A sample of live threads is stored in the _active_threads attribute,
 
426
        when this method runs it compares the current live threads and any not
 
427
        in the previous sample are treated as having leaked.
 
428
        """
 
429
        now_active_threads = set(threading.enumerate())
 
430
        threads_leaked = now_active_threads.difference(self._active_threads)
 
431
        if threads_leaked:
 
432
            self._report_thread_leak(test, threads_leaked, now_active_threads)
 
433
            self._tests_leaking_threads_count += 1
 
434
            if self._first_thread_leaker_id is None:
 
435
                self._first_thread_leaker_id = test.id()
 
436
            self._active_threads = now_active_threads
307
437
 
308
438
    def _recordTestStartTime(self):
309
439
        """Record that a test has started."""
310
 
        self._start_time = time.time()
311
 
 
312
 
    def _cleanupLogFile(self, test):
313
 
        # We can only do this if we have one of our TestCases, not if
314
 
        # we have a doctest.
315
 
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
316
 
        if setKeepLogfile is not None:
317
 
            setKeepLogfile()
 
440
        self._start_datetime = self._now()
318
441
 
319
442
    def addError(self, test, err):
320
443
        """Tell result that test finished with an error.
322
445
        Called from the TestCase run() method when the test
323
446
        fails with an unexpected error.
324
447
        """
325
 
        self._post_mortem()
326
 
        unittest.TestResult.addError(self, test, err)
 
448
        self._post_mortem(self._traceback_from_test)
 
449
        super(ExtendedTestResult, self).addError(test, err)
327
450
        self.error_count += 1
328
451
        self.report_error(test, err)
329
452
        if self.stop_early:
330
453
            self.stop()
331
 
        self._cleanupLogFile(test)
332
454
 
333
455
    def addFailure(self, test, err):
334
456
        """Tell result that test failed.
336
458
        Called from the TestCase run() method when the test
337
459
        fails because e.g. an assert() method failed.
338
460
        """
339
 
        self._post_mortem()
340
 
        unittest.TestResult.addFailure(self, test, err)
 
461
        self._post_mortem(self._traceback_from_test)
 
462
        super(ExtendedTestResult, self).addFailure(test, err)
341
463
        self.failure_count += 1
342
464
        self.report_failure(test, err)
343
465
        if self.stop_early:
344
466
            self.stop()
345
 
        self._cleanupLogFile(test)
346
467
 
347
468
    def addSuccess(self, test, details=None):
348
469
        """Tell result that test completed successfully.
356
477
                    self._formatTime(benchmark_time),
357
478
                    test.id()))
358
479
        self.report_success(test)
359
 
        self._cleanupLogFile(test)
360
 
        unittest.TestResult.addSuccess(self, test)
 
480
        super(ExtendedTestResult, self).addSuccess(test)
361
481
        test._log_contents = ''
362
482
 
363
483
    def addExpectedFailure(self, test, err):
364
484
        self.known_failure_count += 1
365
485
        self.report_known_failure(test, err)
366
486
 
 
487
    def addUnexpectedSuccess(self, test, details=None):
 
488
        """Tell result the test unexpectedly passed, counting as a failure
 
489
 
 
490
        When the minimum version of testtools required becomes 0.9.8 this
 
491
        can be updated to use the new handling there.
 
492
        """
 
493
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
494
        self.failure_count += 1
 
495
        self.report_unexpected_success(test,
 
496
            "".join(details["reason"].iter_text()))
 
497
        if self.stop_early:
 
498
            self.stop()
 
499
 
367
500
    def addNotSupported(self, test, feature):
368
501
        """The test will not be run because of a missing feature.
369
502
        """
386
519
        self.not_applicable_count += 1
387
520
        self.report_not_applicable(test, reason)
388
521
 
389
 
    def _post_mortem(self):
 
522
    def _count_stored_tests(self):
 
523
        """Count of tests instances kept alive due to not succeeding"""
 
524
        return self.error_count + self.failure_count + self.known_failure_count
 
525
 
 
526
    def _post_mortem(self, tb=None):
390
527
        """Start a PDB post mortem session."""
391
528
        if os.environ.get('BZR_TEST_PDB', None):
392
 
            import pdb;pdb.post_mortem()
 
529
            import pdb
 
530
            pdb.post_mortem(tb)
393
531
 
394
532
    def progress(self, offset, whence):
395
533
        """The test is adjusting the count of tests to run."""
400
538
        else:
401
539
            raise errors.BzrError("Unknown whence %r" % whence)
402
540
 
403
 
    def report_cleaning_up(self):
404
 
        pass
 
541
    def report_tests_starting(self):
 
542
        """Display information before the test run begins"""
 
543
        if getattr(sys, 'frozen', None) is None:
 
544
            bzr_path = osutils.realpath(sys.argv[0])
 
545
        else:
 
546
            bzr_path = sys.executable
 
547
        self.stream.write(
 
548
            'bzr selftest: %s\n' % (bzr_path,))
 
549
        self.stream.write(
 
550
            '   %s\n' % (
 
551
                    bzrlib.__path__[0],))
 
552
        self.stream.write(
 
553
            '   bzr-%s python-%s %s\n' % (
 
554
                    bzrlib.version_string,
 
555
                    bzrlib._format_version_tuple(sys.version_info),
 
556
                    platform.platform(aliased=1),
 
557
                    ))
 
558
        self.stream.write('\n')
 
559
 
 
560
    def report_test_start(self, test):
 
561
        """Display information on the test just about to be run"""
 
562
 
 
563
    def _report_thread_leak(self, test, leaked_threads, active_threads):
 
564
        """Display information on a test that leaked one or more threads"""
 
565
        # GZ 2010-09-09: A leak summary reported separately from the general
 
566
        #                thread debugging would be nice. Tests under subunit
 
567
        #                need something not using stream, perhaps adding a
 
568
        #                testtools details object would be fitting.
 
569
        if 'threads' in selftest_debug_flags:
 
570
            self.stream.write('%s is leaking, active is now %d\n' %
 
571
                (test.id(), len(active_threads)))
405
572
 
406
573
    def startTestRun(self):
407
574
        self.startTime = time.time()
444
611
        self.pb.finished()
445
612
        super(TextTestResult, self).stopTestRun()
446
613
 
447
 
    def startTestRun(self):
448
 
        super(TextTestResult, self).startTestRun()
 
614
    def report_tests_starting(self):
 
615
        super(TextTestResult, self).report_tests_starting()
449
616
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
450
617
 
451
 
    def printErrors(self):
452
 
        # clear the pb to make room for the error listing
453
 
        self.pb.clear()
454
 
        super(TextTestResult, self).printErrors()
455
 
 
456
618
    def _progress_prefix_text(self):
457
619
        # the longer this text, the less space we have to show the test
458
620
        # name...
480
642
        return a
481
643
 
482
644
    def report_test_start(self, test):
483
 
        self.count += 1
484
645
        self.pb.update(
485
646
                self._progress_prefix_text()
486
647
                + ' '
504
665
    def report_known_failure(self, test, err):
505
666
        pass
506
667
 
 
668
    def report_unexpected_success(self, test, reason):
 
669
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
 
670
            self._test_description(test),
 
671
            "Unexpected success. Should have failed",
 
672
            reason,
 
673
            ))
 
674
 
507
675
    def report_skip(self, test, reason):
508
676
        pass
509
677
 
513
681
    def report_unsupported(self, test, feature):
514
682
        """test cannot be run because feature is missing."""
515
683
 
516
 
    def report_cleaning_up(self):
517
 
        self.pb.update('Cleaning up')
518
 
 
519
684
 
520
685
class VerboseTestResult(ExtendedTestResult):
521
686
    """Produce long output, with one line per test run plus times"""
528
693
            result = a_string
529
694
        return result.ljust(final_width)
530
695
 
531
 
    def startTestRun(self):
532
 
        super(VerboseTestResult, self).startTestRun()
 
696
    def report_tests_starting(self):
533
697
        self.stream.write('running %d tests...\n' % self.num_tests)
 
698
        super(VerboseTestResult, self).report_tests_starting()
534
699
 
535
700
    def report_test_start(self, test):
536
 
        self.count += 1
537
701
        name = self._shortened_test_description(test)
538
702
        width = osutils.terminal_width()
539
703
        if width is not None:
551
715
        return '%s%s' % (indent, err[1])
552
716
 
553
717
    def report_error(self, test, err):
554
 
        self.stream.writeln('ERROR %s\n%s'
 
718
        self.stream.write('ERROR %s\n%s\n'
555
719
                % (self._testTimeString(test),
556
720
                   self._error_summary(err)))
557
721
 
558
722
    def report_failure(self, test, err):
559
 
        self.stream.writeln(' FAIL %s\n%s'
 
723
        self.stream.write(' FAIL %s\n%s\n'
560
724
                % (self._testTimeString(test),
561
725
                   self._error_summary(err)))
562
726
 
563
727
    def report_known_failure(self, test, err):
564
 
        self.stream.writeln('XFAIL %s\n%s'
 
728
        self.stream.write('XFAIL %s\n%s\n'
565
729
                % (self._testTimeString(test),
566
730
                   self._error_summary(err)))
567
731
 
 
732
    def report_unexpected_success(self, test, reason):
 
733
        self.stream.write(' FAIL %s\n%s: %s\n'
 
734
                % (self._testTimeString(test),
 
735
                   "Unexpected success. Should have failed",
 
736
                   reason))
 
737
 
568
738
    def report_success(self, test):
569
 
        self.stream.writeln('   OK %s' % self._testTimeString(test))
 
739
        self.stream.write('   OK %s\n' % self._testTimeString(test))
570
740
        for bench_called, stats in getattr(test, '_benchcalls', []):
571
 
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
741
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
572
742
            stats.pprint(file=self.stream)
573
743
        # flush the stream so that we get smooth output. This verbose mode is
574
744
        # used to show the output in PQM.
575
745
        self.stream.flush()
576
746
 
577
747
    def report_skip(self, test, reason):
578
 
        self.stream.writeln(' SKIP %s\n%s'
 
748
        self.stream.write(' SKIP %s\n%s\n'
579
749
                % (self._testTimeString(test), reason))
580
750
 
581
751
    def report_not_applicable(self, test, reason):
582
 
        self.stream.writeln('  N/A %s\n    %s'
 
752
        self.stream.write('  N/A %s\n    %s\n'
583
753
                % (self._testTimeString(test), reason))
584
754
 
585
755
    def report_unsupported(self, test, feature):
586
756
        """test cannot be run because feature is missing."""
587
 
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
 
757
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
588
758
                %(self._testTimeString(test), feature))
589
759
 
590
760
 
617
787
            encode = codec[0]
618
788
        else:
619
789
            encode = codec.encode
620
 
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream)
 
790
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
791
        #                so should swap to the plain codecs.StreamWriter
 
792
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
793
            "backslashreplace")
621
794
        stream.encoding = new_encoding
622
 
        self.stream = unittest._WritelnDecorator(stream)
 
795
        self.stream = stream
623
796
        self.descriptions = descriptions
624
797
        self.verbosity = verbosity
625
798
        self._bench_history = bench_history
749
922
    # XXX: Should probably unify more with CannedInputUIFactory or a
750
923
    # particular configuration of TextUIFactory, or otherwise have a clearer
751
924
    # idea of how they're supposed to be different.
752
 
    # See https://bugs.edge.launchpad.net/bzr/+bug/408213
 
925
    # See https://bugs.launchpad.net/bzr/+bug/408213
753
926
 
754
927
    def __init__(self, stdout=None, stderr=None, stdin=None):
755
928
        if stdin is not None:
773
946
        return NullProgressView()
774
947
 
775
948
 
 
949
def isolated_doctest_setUp(test):
 
950
    override_os_environ(test)
 
951
 
 
952
 
 
953
def isolated_doctest_tearDown(test):
 
954
    restore_os_environ(test)
 
955
 
 
956
 
 
957
def IsolatedDocTestSuite(*args, **kwargs):
 
958
    """Overrides doctest.DocTestSuite to handle isolation.
 
959
 
 
960
    The method is really a factory and users are expected to use it as such.
 
961
    """
 
962
 
 
963
    kwargs['setUp'] = isolated_doctest_setUp
 
964
    kwargs['tearDown'] = isolated_doctest_tearDown
 
965
    return doctest.DocTestSuite(*args, **kwargs)
 
966
 
 
967
 
776
968
class TestCase(testtools.TestCase):
777
969
    """Base class for bzr unit tests.
778
970
 
789
981
    routine, and to build and check bzr trees.
790
982
 
791
983
    In addition to the usual method of overriding tearDown(), this class also
792
 
    allows subclasses to register functions into the _cleanups list, which is
 
984
    allows subclasses to register cleanup functions via addCleanup, which are
793
985
    run in order as the object is torn down.  It's less likely this will be
794
986
    accidentally overlooked.
795
987
    """
796
988
 
797
 
    _active_threads = None
798
 
    _leaking_threads_tests = 0
799
 
    _first_thread_leaker_id = None
800
 
    _log_file_name = None
 
989
    _log_file = None
801
990
    # record lsprof data when performing benchmark calls.
802
991
    _gather_lsprof_in_benchmarks = False
803
992
 
804
993
    def __init__(self, methodName='testMethod'):
805
994
        super(TestCase, self).__init__(methodName)
806
 
        self._cleanups = []
807
995
        self._directory_isolation = True
808
996
        self.exception_handlers.insert(0,
809
997
            (UnavailableFeature, self._do_unsupported_or_skip))
812
1000
 
813
1001
    def setUp(self):
814
1002
        super(TestCase, self).setUp()
 
1003
 
 
1004
        timeout = config.GlobalStack().get('selftest.timeout')
 
1005
        if timeout:
 
1006
            timeout_fixture = fixtures.TimeoutFixture(timeout)
 
1007
            timeout_fixture.setUp()
 
1008
            self.addCleanup(timeout_fixture.cleanUp)
 
1009
 
815
1010
        for feature in getattr(self, '_test_needs_features', []):
816
1011
            self.requireFeature(feature)
817
 
        self._log_contents = None
818
 
        self.addDetail("log", content.Content(content.ContentType("text",
819
 
            "plain", {"charset": "utf8"}),
820
 
            lambda:[self._get_log(keep_log_file=True)]))
821
1012
        self._cleanEnvironment()
 
1013
 
 
1014
        if bzrlib.global_state is not None:
 
1015
            self.overrideAttr(bzrlib.global_state, 'cmdline_overrides',
 
1016
                              config.CommandLineStore())
 
1017
 
822
1018
        self._silenceUI()
823
1019
        self._startLogFile()
824
1020
        self._benchcalls = []
827
1023
        self._track_transports()
828
1024
        self._track_locks()
829
1025
        self._clear_debug_flags()
830
 
        TestCase._active_threads = threading.activeCount()
831
 
        self.addCleanup(self._check_leaked_threads)
 
1026
        # Isolate global verbosity level, to make sure it's reproducible
 
1027
        # between tests.  We should get rid of this altogether: bug 656694. --
 
1028
        # mbp 20101008
 
1029
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
 
1030
        # Isolate config option expansion until its default value for bzrlib is
 
1031
        # settled on or a the FIXME associated with _get_expand_default_value
 
1032
        # is addressed -- vila 20110219
 
1033
        self.overrideAttr(config, '_expand_default_value', None)
 
1034
        self._log_files = set()
 
1035
        # Each key in the ``_counters`` dict holds a value for a different
 
1036
        # counter. When the test ends, addDetail() should be used to output the
 
1037
        # counter values. This happens in install_counter_hook().
 
1038
        self._counters = {}
 
1039
        if 'config_stats' in selftest_debug_flags:
 
1040
            self._install_config_stats_hooks()
 
1041
        # Do not use i18n for tests (unless the test reverses this)
 
1042
        i18n.disable_i18n()
832
1043
 
833
1044
    def debug(self):
834
1045
        # debug a frame up.
835
1046
        import pdb
836
 
        pdb.Pdb().set_trace(sys._getframe().f_back)
837
 
 
838
 
    def _check_leaked_threads(self):
839
 
        active = threading.activeCount()
840
 
        leaked_threads = active - TestCase._active_threads
841
 
        TestCase._active_threads = active
842
 
        # If some tests make the number of threads *decrease*, we'll consider
843
 
        # that they are just observing old threads dieing, not agressively kill
844
 
        # random threads. So we don't report these tests as leaking. The risk
845
 
        # is that we have false positives that way (the test see 2 threads
846
 
        # going away but leak one) but it seems less likely than the actual
847
 
        # false positives (the test see threads going away and does not leak).
848
 
        if leaked_threads > 0:
849
 
            TestCase._leaking_threads_tests += 1
850
 
            if TestCase._first_thread_leaker_id is None:
851
 
                TestCase._first_thread_leaker_id = self.id()
 
1047
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
1048
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
1049
                ).set_trace(sys._getframe().f_back)
 
1050
 
 
1051
    def discardDetail(self, name):
 
1052
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1053
 
 
1054
        eg. bzr always adds the 'log' detail at startup, but we don't want to
 
1055
        include it for skipped, xfail, etc tests.
 
1056
 
 
1057
        It is safe to call this for a detail that doesn't exist, in case this
 
1058
        gets called multiple times.
 
1059
        """
 
1060
        # We cheat. details is stored in __details which means we shouldn't
 
1061
        # touch it. but getDetails() returns the dict directly, so we can
 
1062
        # mutate it.
 
1063
        details = self.getDetails()
 
1064
        if name in details:
 
1065
            del details[name]
 
1066
 
 
1067
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1068
        """Install a counting hook.
 
1069
 
 
1070
        Any hook can be counted as long as it doesn't need to return a value.
 
1071
 
 
1072
        :param hooks: Where the hook should be installed.
 
1073
 
 
1074
        :param name: The hook name that will be counted.
 
1075
 
 
1076
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1077
            to ``name``.
 
1078
        """
 
1079
        _counters = self._counters # Avoid closing over self
 
1080
        if counter_name is None:
 
1081
            counter_name = name
 
1082
        if _counters.has_key(counter_name):
 
1083
            raise AssertionError('%s is already used as a counter name'
 
1084
                                  % (counter_name,))
 
1085
        _counters[counter_name] = 0
 
1086
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1087
            lambda: ['%d' % (_counters[counter_name],)]))
 
1088
        def increment_counter(*args, **kwargs):
 
1089
            _counters[counter_name] += 1
 
1090
        label = 'count %s calls' % (counter_name,)
 
1091
        hooks.install_named_hook(name, increment_counter, label)
 
1092
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1093
 
 
1094
    def _install_config_stats_hooks(self):
 
1095
        """Install config hooks to count hook calls.
 
1096
 
 
1097
        """
 
1098
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1099
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1100
                                       'config.%s' % (hook_name,))
 
1101
 
 
1102
        # The OldConfigHooks are private and need special handling to protect
 
1103
        # against recursive tests (tests that run other tests), so we just do
 
1104
        # manually what registering them into _builtin_known_hooks will provide
 
1105
        # us.
 
1106
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1107
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1108
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1109
                                      'old_config.%s' % (hook_name,))
852
1110
 
853
1111
    def _clear_debug_flags(self):
854
1112
        """Prevent externally set debug flags affecting tests.
865
1123
 
866
1124
    def _clear_hooks(self):
867
1125
        # prevent hooks affecting tests
 
1126
        known_hooks = hooks.known_hooks
868
1127
        self._preserved_hooks = {}
869
 
        for key, factory in hooks.known_hooks.items():
870
 
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
871
 
            current_hooks = hooks.known_hooks_key_to_object(key)
 
1128
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1129
            current_hooks = getattr(parent, name)
872
1130
            self._preserved_hooks[parent] = (name, current_hooks)
 
1131
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1132
        hooks._lazy_hooks = {}
873
1133
        self.addCleanup(self._restoreHooks)
874
 
        for key, factory in hooks.known_hooks.items():
875
 
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
 
1134
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1135
            factory = known_hooks.get(key)
876
1136
            setattr(parent, name, factory())
877
1137
        # this hook should always be installed
878
1138
        request._install_hook()
907
1167
        # break some locks on purpose and should be taken into account by
908
1168
        # considering that breaking a lock is just a dirty way of releasing it.
909
1169
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
910
 
            message = ('Different number of acquired and '
911
 
                       'released or broken locks. (%s, %s + %s)' %
912
 
                       (acquired_locks, released_locks, broken_locks))
 
1170
            message = (
 
1171
                'Different number of acquired and '
 
1172
                'released or broken locks.\n'
 
1173
                'acquired=%s\n'
 
1174
                'released=%s\n'
 
1175
                'broken=%s\n' %
 
1176
                (acquired_locks, released_locks, broken_locks))
913
1177
            if not self._lock_check_thorough:
914
1178
                # Rather than fail, just warn
915
1179
                print "Broken test %s: %s" % (self, message)
943
1207
 
944
1208
    def permit_dir(self, name):
945
1209
        """Permit a directory to be used by this test. See permit_url."""
946
 
        name_transport = get_transport(name)
 
1210
        name_transport = _mod_transport.get_transport_from_path(name)
947
1211
        self.permit_url(name)
948
1212
        self.permit_url(name_transport.base)
949
1213
 
972
1236
            try:
973
1237
                workingtree.WorkingTree.open(path)
974
1238
            except (errors.NotBranchError, errors.NoWorkingTree):
975
 
                return
 
1239
                raise TestSkipped('Needs a working tree of bzr sources')
976
1240
        finally:
977
1241
            self.enable_directory_isolation()
978
1242
 
1028
1292
        self.addCleanup(transport_server.stop_server)
1029
1293
        # Obtain a real transport because if the server supplies a password, it
1030
1294
        # will be hidden from the base on the client side.
1031
 
        t = get_transport(transport_server.get_url())
 
1295
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1032
1296
        # Some transport servers effectively chroot the backing transport;
1033
1297
        # others like SFTPServer don't - users of the transport can walk up the
1034
1298
        # transport to read the entire backing transport. This wouldn't matter
1090
1354
        except UnicodeError, e:
1091
1355
            # If we can't compare without getting a UnicodeError, then
1092
1356
            # obviously they are different
1093
 
            mutter('UnicodeError: %s', e)
 
1357
            trace.mutter('UnicodeError: %s', e)
1094
1358
        if message:
1095
1359
            message += '\n'
1096
1360
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1097
1361
            % (message,
1098
 
               pformat(a), pformat(b)))
 
1362
               pprint.pformat(a), pprint.pformat(b)))
1099
1363
 
1100
1364
    assertEquals = assertEqual
1101
1365
 
1135
1399
                         'st_mtime did not match')
1136
1400
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1137
1401
                         'st_ctime did not match')
1138
 
        if sys.platform != 'win32':
 
1402
        if sys.platform == 'win32':
1139
1403
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1140
1404
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
1141
 
            # odd. Regardless we shouldn't actually try to assert anything
1142
 
            # about their values
 
1405
            # odd. We just force it to always be 0 to avoid any problems.
 
1406
            self.assertEqual(0, expected.st_dev)
 
1407
            self.assertEqual(0, actual.st_dev)
 
1408
            self.assertEqual(0, expected.st_ino)
 
1409
            self.assertEqual(0, actual.st_ino)
 
1410
        else:
1143
1411
            self.assertEqual(expected.st_dev, actual.st_dev,
1144
1412
                             'st_dev did not match')
1145
1413
            self.assertEqual(expected.st_ino, actual.st_ino,
1154
1422
                length, len(obj_with_len), obj_with_len))
1155
1423
 
1156
1424
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1157
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1425
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1158
1426
        """
1159
 
        from bzrlib import trace
1160
1427
        captured = []
1161
1428
        orig_log_exception_quietly = trace.log_exception_quietly
1162
1429
        try:
1163
1430
            def capture():
1164
1431
                orig_log_exception_quietly()
1165
 
                captured.append(sys.exc_info())
 
1432
                captured.append(sys.exc_info()[1])
1166
1433
            trace.log_exception_quietly = capture
1167
1434
            func(*args, **kwargs)
1168
1435
        finally:
1169
1436
            trace.log_exception_quietly = orig_log_exception_quietly
1170
1437
        self.assertLength(1, captured)
1171
 
        err = captured[0][1]
 
1438
        err = captured[0]
1172
1439
        self.assertIsInstance(err, exception_class)
1173
1440
        return err
1174
1441
 
1211
1478
        if haystack.find(needle) == -1:
1212
1479
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1213
1480
 
 
1481
    def assertNotContainsString(self, haystack, needle):
 
1482
        if haystack.find(needle) != -1:
 
1483
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1484
 
1214
1485
    def assertSubset(self, sublist, superlist):
1215
1486
        """Assert that every entry in sublist is present in superlist."""
1216
1487
        missing = set(sublist) - set(superlist)
1305
1576
 
1306
1577
    def assertFileEqual(self, content, path):
1307
1578
        """Fail if path does not contain 'content'."""
1308
 
        self.failUnlessExists(path)
 
1579
        self.assertPathExists(path)
1309
1580
        f = file(path, 'rb')
1310
1581
        try:
1311
1582
            s = f.read()
1321
1592
        else:
1322
1593
            self.assertEqual(expected_docstring, obj.__doc__)
1323
1594
 
 
1595
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1324
1596
    def failUnlessExists(self, path):
 
1597
        return self.assertPathExists(path)
 
1598
 
 
1599
    def assertPathExists(self, path):
1325
1600
        """Fail unless path or paths, which may be abs or relative, exist."""
1326
1601
        if not isinstance(path, basestring):
1327
1602
            for p in path:
1328
 
                self.failUnlessExists(p)
 
1603
                self.assertPathExists(p)
1329
1604
        else:
1330
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1605
            self.assertTrue(osutils.lexists(path),
 
1606
                path + " does not exist")
1331
1607
 
 
1608
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1332
1609
    def failIfExists(self, path):
 
1610
        return self.assertPathDoesNotExist(path)
 
1611
 
 
1612
    def assertPathDoesNotExist(self, path):
1333
1613
        """Fail if path or paths, which may be abs or relative, exist."""
1334
1614
        if not isinstance(path, basestring):
1335
1615
            for p in path:
1336
 
                self.failIfExists(p)
 
1616
                self.assertPathDoesNotExist(p)
1337
1617
        else:
1338
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1618
            self.assertFalse(osutils.lexists(path),
 
1619
                path + " exists")
1339
1620
 
1340
1621
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1341
1622
        """A helper for callDeprecated and applyDeprecated.
1367
1648
        not other callers that go direct to the warning module.
1368
1649
 
1369
1650
        To test that a deprecated method raises an error, do something like
1370
 
        this::
 
1651
        this (remember that both assertRaises and applyDeprecated delays *args
 
1652
        and **kwargs passing)::
1371
1653
 
1372
1654
            self.assertRaises(errors.ReservedId,
1373
1655
                self.applyDeprecated,
1451
1733
        return result
1452
1734
 
1453
1735
    def _startLogFile(self):
1454
 
        """Send bzr and test log messages to a temporary file.
1455
 
 
1456
 
        The file is removed as the test is torn down.
1457
 
        """
1458
 
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
1459
 
        self._log_file = os.fdopen(fileno, 'w+')
1460
 
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
1461
 
        self._log_file_name = name
 
1736
        """Setup a in-memory target for bzr and testcase log messages"""
 
1737
        pseudo_log_file = StringIO()
 
1738
        def _get_log_contents_for_weird_testtools_api():
 
1739
            return [pseudo_log_file.getvalue().decode(
 
1740
                "utf-8", "replace").encode("utf-8")]
 
1741
        self.addDetail("log", content.Content(content.ContentType("text",
 
1742
            "plain", {"charset": "utf8"}),
 
1743
            _get_log_contents_for_weird_testtools_api))
 
1744
        self._log_file = pseudo_log_file
 
1745
        self._log_memento = trace.push_log_file(self._log_file)
1462
1746
        self.addCleanup(self._finishLogFile)
1463
1747
 
1464
1748
    def _finishLogFile(self):
1465
 
        """Finished with the log file.
1466
 
 
1467
 
        Close the file and delete it, unless setKeepLogfile was called.
1468
 
        """
1469
 
        if bzrlib.trace._trace_file:
 
1749
        """Flush and dereference the in-memory log for this testcase"""
 
1750
        if trace._trace_file:
1470
1751
            # flush the log file, to get all content
1471
 
            bzrlib.trace._trace_file.flush()
1472
 
        bzrlib.trace.pop_log_file(self._log_memento)
1473
 
        # Cache the log result and delete the file on disk
1474
 
        self._get_log(False)
 
1752
            trace._trace_file.flush()
 
1753
        trace.pop_log_file(self._log_memento)
 
1754
        # The logging module now tracks references for cleanup so discard ours
 
1755
        del self._log_memento
1475
1756
 
1476
1757
    def thisFailsStrictLockCheck(self):
1477
1758
        """It is known that this test would fail with -Dstrict_locks.
1486
1767
        """
1487
1768
        debug.debug_flags.discard('strict_locks')
1488
1769
 
1489
 
    def addCleanup(self, callable, *args, **kwargs):
1490
 
        """Arrange to run a callable when this case is torn down.
1491
 
 
1492
 
        Callables are run in the reverse of the order they are registered,
1493
 
        ie last-in first-out.
1494
 
        """
1495
 
        self._cleanups.append((callable, args, kwargs))
1496
 
 
1497
1770
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1498
1771
        """Overrides an object attribute restoring it after the test.
1499
1772
 
 
1773
        :note: This should be used with discretion; you should think about
 
1774
        whether it's better to make the code testable without monkey-patching.
 
1775
 
1500
1776
        :param obj: The object that will be mutated.
1501
1777
 
1502
1778
        :param attr_name: The attribute name we want to preserve/override in
1513
1789
            setattr(obj, attr_name, new)
1514
1790
        return value
1515
1791
 
 
1792
    def overrideEnv(self, name, new):
 
1793
        """Set an environment variable, and reset it after the test.
 
1794
 
 
1795
        :param name: The environment variable name.
 
1796
 
 
1797
        :param new: The value to set the variable to. If None, the 
 
1798
            variable is deleted from the environment.
 
1799
 
 
1800
        :returns: The actual variable value.
 
1801
        """
 
1802
        value = osutils.set_or_unset_env(name, new)
 
1803
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1804
        return value
 
1805
 
 
1806
    def recordCalls(self, obj, attr_name):
 
1807
        """Monkeypatch in a wrapper that will record calls.
 
1808
 
 
1809
        The monkeypatch is automatically removed when the test concludes.
 
1810
 
 
1811
        :param obj: The namespace holding the reference to be replaced;
 
1812
            typically a module, class, or object.
 
1813
        :param attr_name: A string for the name of the attribute to 
 
1814
            patch.
 
1815
        :returns: A list that will be extended with one item every time the
 
1816
            function is called, with a tuple of (args, kwargs).
 
1817
        """
 
1818
        calls = []
 
1819
 
 
1820
        def decorator(*args, **kwargs):
 
1821
            calls.append((args, kwargs))
 
1822
            return orig(*args, **kwargs)
 
1823
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1824
        return calls
 
1825
 
1516
1826
    def _cleanEnvironment(self):
1517
 
        new_env = {
1518
 
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1519
 
            'HOME': os.getcwd(),
1520
 
            # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1521
 
            # tests do check our impls match APPDATA
1522
 
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
1523
 
            'VISUAL': None,
1524
 
            'EDITOR': None,
1525
 
            'BZR_EMAIL': None,
1526
 
            'BZREMAIL': None, # may still be present in the environment
1527
 
            'EMAIL': None,
1528
 
            'BZR_PROGRESS_BAR': None,
1529
 
            'BZR_LOG': None,
1530
 
            'BZR_PLUGIN_PATH': None,
1531
 
            'BZR_DISABLE_PLUGINS': None,
1532
 
            'BZR_PLUGINS_AT': None,
1533
 
            'BZR_CONCURRENCY': None,
1534
 
            # Make sure that any text ui tests are consistent regardless of
1535
 
            # the environment the test case is run in; you may want tests that
1536
 
            # test other combinations.  'dumb' is a reasonable guess for tests
1537
 
            # going to a pipe or a StringIO.
1538
 
            'TERM': 'dumb',
1539
 
            'LINES': '25',
1540
 
            'COLUMNS': '80',
1541
 
            'BZR_COLUMNS': '80',
1542
 
            # SSH Agent
1543
 
            'SSH_AUTH_SOCK': None,
1544
 
            # Proxies
1545
 
            'http_proxy': None,
1546
 
            'HTTP_PROXY': None,
1547
 
            'https_proxy': None,
1548
 
            'HTTPS_PROXY': None,
1549
 
            'no_proxy': None,
1550
 
            'NO_PROXY': None,
1551
 
            'all_proxy': None,
1552
 
            'ALL_PROXY': None,
1553
 
            # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1554
 
            # least. If you do (care), please update this comment
1555
 
            # -- vila 20080401
1556
 
            'ftp_proxy': None,
1557
 
            'FTP_PROXY': None,
1558
 
            'BZR_REMOTE_PATH': None,
1559
 
            # Generally speaking, we don't want apport reporting on crashes in
1560
 
            # the test envirnoment unless we're specifically testing apport,
1561
 
            # so that it doesn't leak into the real system environment.  We
1562
 
            # use an env var so it propagates to subprocesses.
1563
 
            'APPORT_DISABLE': '1',
1564
 
        }
1565
 
        self._old_env = {}
1566
 
        self.addCleanup(self._restoreEnvironment)
1567
 
        for name, value in new_env.iteritems():
1568
 
            self._captureVar(name, value)
1569
 
 
1570
 
    def _captureVar(self, name, newvalue):
1571
 
        """Set an environment variable, and reset it when finished."""
1572
 
        self._old_env[name] = osutils.set_or_unset_env(name, newvalue)
1573
 
 
1574
 
    def _restoreEnvironment(self):
1575
 
        for name, value in self._old_env.iteritems():
1576
 
            osutils.set_or_unset_env(name, value)
 
1827
        for name, value in isolated_environ.iteritems():
 
1828
            self.overrideEnv(name, value)
1577
1829
 
1578
1830
    def _restoreHooks(self):
1579
1831
        for klass, (name, hooks) in self._preserved_hooks.items():
1580
1832
            setattr(klass, name, hooks)
 
1833
        self._preserved_hooks.clear()
 
1834
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1835
        self._preserved_lazy_hooks.clear()
1581
1836
 
1582
1837
    def knownFailure(self, reason):
1583
 
        """This test has failed for some known reason."""
1584
 
        raise KnownFailure(reason)
 
1838
        """Declare that this test fails for a known reason
 
1839
 
 
1840
        Tests that are known to fail should generally be using expectedFailure
 
1841
        with an appropriate reverse assertion if a change could cause the test
 
1842
        to start passing. Conversely if the test has no immediate prospect of
 
1843
        succeeding then using skip is more suitable.
 
1844
 
 
1845
        When this method is called while an exception is being handled, that
 
1846
        traceback will be used, otherwise a new exception will be thrown to
 
1847
        provide one but won't be reported.
 
1848
        """
 
1849
        self._add_reason(reason)
 
1850
        try:
 
1851
            exc_info = sys.exc_info()
 
1852
            if exc_info != (None, None, None):
 
1853
                self._report_traceback(exc_info)
 
1854
            else:
 
1855
                try:
 
1856
                    raise self.failureException(reason)
 
1857
                except self.failureException:
 
1858
                    exc_info = sys.exc_info()
 
1859
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1860
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1861
        finally:
 
1862
            del exc_info
 
1863
 
 
1864
    def _suppress_log(self):
 
1865
        """Remove the log info from details."""
 
1866
        self.discardDetail('log')
1585
1867
 
1586
1868
    def _do_skip(self, result, reason):
 
1869
        self._suppress_log()
1587
1870
        addSkip = getattr(result, 'addSkip', None)
1588
1871
        if not callable(addSkip):
1589
1872
            result.addSuccess(result)
1592
1875
 
1593
1876
    @staticmethod
1594
1877
    def _do_known_failure(self, result, e):
 
1878
        self._suppress_log()
1595
1879
        err = sys.exc_info()
1596
1880
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1597
1881
        if addExpectedFailure is not None:
1605
1889
            reason = 'No reason given'
1606
1890
        else:
1607
1891
            reason = e.args[0]
 
1892
        self._suppress_log ()
1608
1893
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1609
1894
        if addNotApplicable is not None:
1610
1895
            result.addNotApplicable(self, reason)
1612
1897
            self._do_skip(result, reason)
1613
1898
 
1614
1899
    @staticmethod
 
1900
    def _report_skip(self, result, err):
 
1901
        """Override the default _report_skip.
 
1902
 
 
1903
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1904
        already been formatted into the 'reason' string, and we can't pull it
 
1905
        out again.
 
1906
        """
 
1907
        self._suppress_log()
 
1908
        super(TestCase, self)._report_skip(self, result, err)
 
1909
 
 
1910
    @staticmethod
 
1911
    def _report_expected_failure(self, result, err):
 
1912
        """Strip the log.
 
1913
 
 
1914
        See _report_skip for motivation.
 
1915
        """
 
1916
        self._suppress_log()
 
1917
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1918
 
 
1919
    @staticmethod
1615
1920
    def _do_unsupported_or_skip(self, result, e):
1616
1921
        reason = e.args[0]
 
1922
        self._suppress_log()
1617
1923
        addNotSupported = getattr(result, 'addNotSupported', None)
1618
1924
        if addNotSupported is not None:
1619
1925
            result.addNotSupported(self, reason)
1645
1951
            self._benchtime += time.time() - start
1646
1952
 
1647
1953
    def log(self, *args):
1648
 
        mutter(*args)
1649
 
 
1650
 
    def _get_log(self, keep_log_file=False):
1651
 
        """Internal helper to get the log from bzrlib.trace for this test.
1652
 
 
1653
 
        Please use self.getDetails, or self.get_log to access this in test case
1654
 
        code.
1655
 
 
1656
 
        :param keep_log_file: When True, if the log is still a file on disk
1657
 
            leave it as a file on disk. When False, if the log is still a file
1658
 
            on disk, the log file is deleted and the log preserved as
1659
 
            self._log_contents.
1660
 
        :return: A string containing the log.
1661
 
        """
1662
 
        if self._log_contents is not None:
1663
 
            try:
1664
 
                self._log_contents.decode('utf8')
1665
 
            except UnicodeDecodeError:
1666
 
                unicodestr = self._log_contents.decode('utf8', 'replace')
1667
 
                self._log_contents = unicodestr.encode('utf8')
1668
 
            return self._log_contents
1669
 
        import bzrlib.trace
1670
 
        if bzrlib.trace._trace_file:
1671
 
            # flush the log file, to get all content
1672
 
            bzrlib.trace._trace_file.flush()
1673
 
        if self._log_file_name is not None:
1674
 
            logfile = open(self._log_file_name)
1675
 
            try:
1676
 
                log_contents = logfile.read()
1677
 
            finally:
1678
 
                logfile.close()
1679
 
            try:
1680
 
                log_contents.decode('utf8')
1681
 
            except UnicodeDecodeError:
1682
 
                unicodestr = log_contents.decode('utf8', 'replace')
1683
 
                log_contents = unicodestr.encode('utf8')
1684
 
            if not keep_log_file:
1685
 
                close_attempts = 0
1686
 
                max_close_attempts = 100
1687
 
                first_close_error = None
1688
 
                while close_attempts < max_close_attempts:
1689
 
                    close_attempts += 1
1690
 
                    try:
1691
 
                        self._log_file.close()
1692
 
                    except IOError, ioe:
1693
 
                        if ioe.errno is None:
1694
 
                            # No errno implies 'close() called during
1695
 
                            # concurrent operation on the same file object', so
1696
 
                            # retry.  Probably a thread is trying to write to
1697
 
                            # the log file.
1698
 
                            if first_close_error is None:
1699
 
                                first_close_error = ioe
1700
 
                            continue
1701
 
                        raise
1702
 
                    else:
1703
 
                        break
1704
 
                if close_attempts > 1:
1705
 
                    sys.stderr.write(
1706
 
                        'Unable to close log file on first attempt, '
1707
 
                        'will retry: %s\n' % (first_close_error,))
1708
 
                    if close_attempts == max_close_attempts:
1709
 
                        sys.stderr.write(
1710
 
                            'Unable to close log file after %d attempts.\n'
1711
 
                            % (max_close_attempts,))
1712
 
                self._log_file = None
1713
 
                # Permit multiple calls to get_log until we clean it up in
1714
 
                # finishLogFile
1715
 
                self._log_contents = log_contents
1716
 
                try:
1717
 
                    os.remove(self._log_file_name)
1718
 
                except OSError, e:
1719
 
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
1720
 
                        sys.stderr.write(('Unable to delete log file '
1721
 
                                             ' %r\n' % self._log_file_name))
1722
 
                    else:
1723
 
                        raise
1724
 
                self._log_file_name = None
1725
 
            return log_contents
1726
 
        else:
1727
 
            return "No log file content and no log file name."
 
1954
        trace.mutter(*args)
1728
1955
 
1729
1956
    def get_log(self):
1730
1957
        """Get a unicode string containing the log from bzrlib.trace.
1766
1993
 
1767
1994
        self.log('run bzr: %r', args)
1768
1995
        # FIXME: don't call into logging here
1769
 
        handler = logging.StreamHandler(stderr)
1770
 
        handler.setLevel(logging.INFO)
 
1996
        handler = trace.EncodedStreamHandler(stderr, errors="replace",
 
1997
            level=logging.INFO)
1771
1998
        logger = logging.getLogger('')
1772
1999
        logger.addHandler(handler)
1773
2000
        old_ui_factory = ui.ui_factory
1780
2007
 
1781
2008
        try:
1782
2009
            try:
1783
 
                result = self.apply_redirected(ui.ui_factory.stdin,
 
2010
                result = self.apply_redirected(
 
2011
                    ui.ui_factory.stdin,
1784
2012
                    stdout, stderr,
1785
 
                    bzrlib.commands.run_bzr_catch_user_errors,
 
2013
                    _mod_commands.run_bzr_catch_user_errors,
1786
2014
                    args)
1787
2015
            except KeyboardInterrupt:
1788
2016
                # Reraise KeyboardInterrupt with contents of redirected stdout
1930
2158
    def start_bzr_subprocess(self, process_args, env_changes=None,
1931
2159
                             skip_if_plan_to_signal=False,
1932
2160
                             working_dir=None,
1933
 
                             allow_plugins=False):
 
2161
                             allow_plugins=False, stderr=subprocess.PIPE):
1934
2162
        """Start bzr in a subprocess for testing.
1935
2163
 
1936
2164
        This starts a new Python interpreter and runs bzr in there.
1945
2173
            variables. A value of None will unset the env variable.
1946
2174
            The values must be strings. The change will only occur in the
1947
2175
            child, so you don't need to fix the environment after running.
1948
 
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
1949
 
            is not available.
 
2176
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2177
            doesn't support signalling subprocesses.
1950
2178
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
2179
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2180
            are those valid for the stderr argument of `subprocess.Popen`.
 
2181
            Default value is ``subprocess.PIPE``.
1951
2182
 
1952
2183
        :returns: Popen object for the started process.
1953
2184
        """
1954
2185
        if skip_if_plan_to_signal:
1955
 
            if not getattr(os, 'kill', None):
1956
 
                raise TestSkipped("os.kill not available.")
 
2186
            if os.name != "posix":
 
2187
                raise TestSkipped("Sending signals not supported")
1957
2188
 
1958
2189
        if env_changes is None:
1959
2190
            env_changes = {}
 
2191
        # Because $HOME is set to a tempdir for the context of a test, modules
 
2192
        # installed in the user dir will not be found unless $PYTHONUSERBASE
 
2193
        # gets set to the computed directory of this parent process.
 
2194
        if site.USER_BASE is not None:
 
2195
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
1960
2196
        old_env = {}
1961
2197
 
1962
2198
        def cleanup_environment():
1979
2215
            # so we will avoid using it on all platforms, just to
1980
2216
            # make sure the code path is used, and we don't break on win32
1981
2217
            cleanup_environment()
 
2218
            # Include the subprocess's log file in the test details, in case
 
2219
            # the test fails due to an error in the subprocess.
 
2220
            self._add_subprocess_log(trace._get_bzr_log_filename())
1982
2221
            command = [sys.executable]
1983
2222
            # frozen executables don't need the path to bzr
1984
2223
            if getattr(sys, "frozen", None) is None:
1986
2225
            if not allow_plugins:
1987
2226
                command.append('--no-plugins')
1988
2227
            command.extend(process_args)
1989
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
2228
            process = self._popen(command, stdin=subprocess.PIPE,
 
2229
                                  stdout=subprocess.PIPE,
 
2230
                                  stderr=stderr)
1990
2231
        finally:
1991
2232
            restore_environment()
1992
2233
            if cwd is not None:
1994
2235
 
1995
2236
        return process
1996
2237
 
 
2238
    def _add_subprocess_log(self, log_file_path):
 
2239
        if len(self._log_files) == 0:
 
2240
            # Register an addCleanup func.  We do this on the first call to
 
2241
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2242
            # addCleanup is registered after any cleanups for tempdirs that
 
2243
            # subclasses might create, which will probably remove the log file
 
2244
            # we want to read.
 
2245
            self.addCleanup(self._subprocess_log_cleanup)
 
2246
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2247
        # twice.
 
2248
        self._log_files.add(log_file_path)
 
2249
 
 
2250
    def _subprocess_log_cleanup(self):
 
2251
        for count, log_file_path in enumerate(self._log_files):
 
2252
            # We use buffer_now=True to avoid holding the file open beyond
 
2253
            # the life of this function, which might interfere with e.g.
 
2254
            # cleaning tempdirs on Windows.
 
2255
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2256
            #detail_content = content.content_from_file(
 
2257
            #    log_file_path, buffer_now=True)
 
2258
            with open(log_file_path, 'rb') as log_file:
 
2259
                log_file_bytes = log_file.read()
 
2260
            detail_content = content.Content(content.ContentType("text",
 
2261
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2262
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2263
                detail_content)
 
2264
 
1997
2265
    def _popen(self, *args, **kwargs):
1998
2266
        """Place a call to Popen.
1999
2267
 
2000
2268
        Allows tests to override this method to intercept the calls made to
2001
2269
        Popen for introspection.
2002
2270
        """
2003
 
        return Popen(*args, **kwargs)
 
2271
        return subprocess.Popen(*args, **kwargs)
2004
2272
 
2005
2273
    def get_source_path(self):
2006
2274
        """Return the path of the directory containing bzrlib."""
2008
2276
 
2009
2277
    def get_bzr_path(self):
2010
2278
        """Return the path of the 'bzr' executable for this test suite."""
2011
 
        bzr_path = self.get_source_path()+'/bzr'
 
2279
        bzr_path = os.path.join(self.get_source_path(), "bzr")
2012
2280
        if not os.path.isfile(bzr_path):
2013
2281
            # We are probably installed. Assume sys.argv is the right file
2014
2282
            bzr_path = sys.argv[0]
2036
2304
        if retcode is not None and retcode != process.returncode:
2037
2305
            if process_args is None:
2038
2306
                process_args = "(unknown args)"
2039
 
            mutter('Output of bzr %s:\n%s', process_args, out)
2040
 
            mutter('Error for bzr %s:\n%s', process_args, err)
 
2307
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
 
2308
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
2041
2309
            self.fail('Command bzr %s failed with retcode %s != %s'
2042
2310
                      % (process_args, retcode, process.returncode))
2043
2311
        return [out, err]
2044
2312
 
2045
 
    def check_inventory_shape(self, inv, shape):
2046
 
        """Compare an inventory to a list of expected names.
 
2313
    def check_tree_shape(self, tree, shape):
 
2314
        """Compare a tree to a list of expected names.
2047
2315
 
2048
2316
        Fail if they are not precisely equal.
2049
2317
        """
2050
2318
        extras = []
2051
2319
        shape = list(shape)             # copy
2052
 
        for path, ie in inv.entries():
 
2320
        for path, ie in tree.iter_entries_by_dir():
2053
2321
            name = path.replace('\\', '/')
2054
2322
            if ie.kind == 'directory':
2055
2323
                name = name + '/'
2056
 
            if name in shape:
 
2324
            if name == "/":
 
2325
                pass # ignore root entry
 
2326
            elif name in shape:
2057
2327
                shape.remove(name)
2058
2328
            else:
2059
2329
                extras.append(name)
2100
2370
 
2101
2371
        Tests that expect to provoke LockContention errors should call this.
2102
2372
        """
2103
 
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2373
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2104
2374
 
2105
2375
    def make_utf8_encoded_stringio(self, encoding_type=None):
2106
2376
        """Return a StringIOWrapper instance, that will encode Unicode
2119
2389
        from bzrlib.smart import request
2120
2390
        request_handlers = request.request_handlers
2121
2391
        orig_method = request_handlers.get(verb)
 
2392
        orig_info = request_handlers.get_info(verb)
2122
2393
        request_handlers.remove(verb)
2123
 
        self.addCleanup(request_handlers.register, verb, orig_method)
 
2394
        self.addCleanup(request_handlers.register, verb, orig_method,
 
2395
            info=orig_info)
2124
2396
 
2125
2397
 
2126
2398
class CapturedCall(object):
2149
2421
class TestCaseWithMemoryTransport(TestCase):
2150
2422
    """Common test class for tests that do not need disk resources.
2151
2423
 
2152
 
    Tests that need disk resources should derive from TestCaseWithTransport.
 
2424
    Tests that need disk resources should derive from TestCaseInTempDir
 
2425
    orTestCaseWithTransport.
2153
2426
 
2154
2427
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2155
2428
 
2156
 
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
2429
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2157
2430
    a directory which does not exist. This serves to help ensure test isolation
2158
 
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
2159
 
    must exist. However, TestCaseWithMemoryTransport does not offer local
2160
 
    file defaults for the transport in tests, nor does it obey the command line
 
2431
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2432
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2433
    defaults for the transport in tests, nor does it obey the command line
2161
2434
    override, so tests that accidentally write to the common directory should
2162
2435
    be rare.
2163
2436
 
2164
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
2165
 
    a .bzr directory that stops us ascending higher into the filesystem.
 
2437
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2438
        ``.bzr`` directory that stops us ascending higher into the filesystem.
2166
2439
    """
2167
2440
 
2168
2441
    TEST_ROOT = None
2186
2459
 
2187
2460
        :param relpath: a path relative to the base url.
2188
2461
        """
2189
 
        t = get_transport(self.get_url(relpath))
 
2462
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2190
2463
        self.assertFalse(t.is_readonly())
2191
2464
        return t
2192
2465
 
2198
2471
 
2199
2472
        :param relpath: a path relative to the base url.
2200
2473
        """
2201
 
        t = get_transport(self.get_readonly_url(relpath))
 
2474
        t = _mod_transport.get_transport_from_url(
 
2475
            self.get_readonly_url(relpath))
2202
2476
        self.assertTrue(t.is_readonly())
2203
2477
        return t
2204
2478
 
2325
2599
        real branch.
2326
2600
        """
2327
2601
        root = TestCaseWithMemoryTransport.TEST_ROOT
2328
 
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2602
        # Make sure we get a readable and accessible home for .bzr.log
 
2603
        # and/or config files, and not fallback to weird defaults (see
 
2604
        # http://pad.lv/825027).
 
2605
        self.assertIs(None, os.environ.get('BZR_HOME', None))
 
2606
        os.environ['BZR_HOME'] = root
 
2607
        wt = bzrdir.BzrDir.create_standalone_workingtree(root)
 
2608
        del os.environ['BZR_HOME']
 
2609
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2610
        # we don't need to re-open the wt to check it hasn't changed.
 
2611
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2612
            wt.control_transport.get_bytes('dirstate'))
2329
2613
 
2330
2614
    def _check_safety_net(self):
2331
2615
        """Check that the safety .bzr directory have not been touched.
2334
2618
        propagating. This method ensures than a test did not leaked.
2335
2619
        """
2336
2620
        root = TestCaseWithMemoryTransport.TEST_ROOT
2337
 
        self.permit_url(get_transport(root).base)
2338
 
        wt = workingtree.WorkingTree.open(root)
2339
 
        last_rev = wt.last_revision()
2340
 
        if last_rev != 'null:':
 
2621
        t = _mod_transport.get_transport_from_path(root)
 
2622
        self.permit_url(t.base)
 
2623
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2624
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2341
2625
            # The current test have modified the /bzr directory, we need to
2342
2626
            # recreate a new one or all the followng tests will fail.
2343
2627
            # If you need to inspect its content uncomment the following line
2375
2659
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2376
2660
        self.permit_dir(self.test_dir)
2377
2661
 
2378
 
    def make_branch(self, relpath, format=None):
 
2662
    def make_branch(self, relpath, format=None, name=None):
2379
2663
        """Create a branch on the transport at relpath."""
2380
2664
        repo = self.make_repository(relpath, format=format)
2381
 
        return repo.bzrdir.create_branch()
 
2665
        return repo.bzrdir.create_branch(append_revisions_only=False,
 
2666
                                         name=name)
 
2667
 
 
2668
    def get_default_format(self):
 
2669
        return 'default'
 
2670
 
 
2671
    def resolve_format(self, format):
 
2672
        """Resolve an object to a ControlDir format object.
 
2673
 
 
2674
        The initial format object can either already be
 
2675
        a ControlDirFormat, None (for the default format),
 
2676
        or a string with the name of the control dir format.
 
2677
 
 
2678
        :param format: Object to resolve
 
2679
        :return A ControlDirFormat instance
 
2680
        """
 
2681
        if format is None:
 
2682
            format = self.get_default_format()
 
2683
        if isinstance(format, basestring):
 
2684
            format = bzrdir.format_registry.make_bzrdir(format)
 
2685
        return format
2382
2686
 
2383
2687
    def make_bzrdir(self, relpath, format=None):
2384
2688
        try:
2385
2689
            # might be a relative or absolute path
2386
2690
            maybe_a_url = self.get_url(relpath)
2387
2691
            segments = maybe_a_url.rsplit('/', 1)
2388
 
            t = get_transport(maybe_a_url)
 
2692
            t = _mod_transport.get_transport(maybe_a_url)
2389
2693
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2390
2694
                t.ensure_base()
2391
 
            if format is None:
2392
 
                format = 'default'
2393
 
            if isinstance(format, basestring):
2394
 
                format = bzrdir.format_registry.make_bzrdir(format)
 
2695
            format = self.resolve_format(format)
2395
2696
            return format.initialize_on_transport(t)
2396
2697
        except errors.UninitializableFormat:
2397
2698
            raise TestSkipped("Format %s is not initializable." % format)
2398
2699
 
2399
 
    def make_repository(self, relpath, shared=False, format=None):
 
2700
    def make_repository(self, relpath, shared=None, format=None):
2400
2701
        """Create a repository on our default transport at relpath.
2401
2702
 
2402
2703
        Note that relpath must be a relative path, not a full url.
2408
2709
        made_control = self.make_bzrdir(relpath, format=format)
2409
2710
        return made_control.create_repository(shared=shared)
2410
2711
 
2411
 
    def make_smart_server(self, path):
 
2712
    def make_smart_server(self, path, backing_server=None):
 
2713
        if backing_server is None:
 
2714
            backing_server = self.get_server()
2412
2715
        smart_server = test_server.SmartTCPServer_for_testing()
2413
 
        self.start_server(smart_server, self.get_server())
2414
 
        remote_transport = get_transport(smart_server.get_url()).clone(path)
 
2716
        self.start_server(smart_server, backing_server)
 
2717
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
 
2718
                                                   ).clone(path)
2415
2719
        return remote_transport
2416
2720
 
2417
2721
    def make_branch_and_memory_tree(self, relpath, format=None):
2427
2731
        test_home_dir = self.test_home_dir
2428
2732
        if isinstance(test_home_dir, unicode):
2429
2733
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2430
 
        os.environ['HOME'] = test_home_dir
2431
 
        os.environ['BZR_HOME'] = test_home_dir
 
2734
        self.overrideEnv('HOME', test_home_dir)
 
2735
        self.overrideEnv('BZR_HOME', test_home_dir)
2432
2736
 
2433
2737
    def setUp(self):
2434
2738
        super(TestCaseWithMemoryTransport, self).setUp()
 
2739
 
 
2740
        def _add_disconnect_cleanup(transport):
 
2741
            """Schedule disconnection of given transport at test cleanup
 
2742
 
 
2743
            This needs to happen for all connected transports or leaks occur.
 
2744
 
 
2745
            Note reconnections may mean we call disconnect multiple times per
 
2746
            transport which is suboptimal but seems harmless.
 
2747
            """
 
2748
            self.addCleanup(transport.disconnect)
 
2749
 
 
2750
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
 
2751
            _add_disconnect_cleanup, None)
 
2752
 
2435
2753
        self._make_test_root()
2436
2754
        self.addCleanup(os.chdir, os.getcwdu())
2437
2755
        self.makeAndChdirToTestDir()
2443
2761
    def setup_smart_server_with_call_log(self):
2444
2762
        """Sets up a smart server as the transport server with a call log."""
2445
2763
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2764
        self.hpss_connections = []
2446
2765
        self.hpss_calls = []
2447
2766
        import traceback
2448
2767
        # Skip the current stack down to the caller of
2451
2770
        def capture_hpss_call(params):
2452
2771
            self.hpss_calls.append(
2453
2772
                CapturedCall(params, prefix_length))
 
2773
        def capture_connect(transport):
 
2774
            self.hpss_connections.append(transport)
2454
2775
        client._SmartClient.hooks.install_named_hook(
2455
2776
            'call', capture_hpss_call, None)
 
2777
        _mod_transport.Transport.hooks.install_named_hook(
 
2778
            'post_connect', capture_connect, None)
2456
2779
 
2457
2780
    def reset_smart_call_log(self):
2458
2781
        self.hpss_calls = []
 
2782
        self.hpss_connections = []
2459
2783
 
2460
2784
 
2461
2785
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2480
2804
 
2481
2805
    OVERRIDE_PYTHON = 'python'
2482
2806
 
 
2807
    def setUp(self):
 
2808
        super(TestCaseInTempDir, self).setUp()
 
2809
        # Remove the protection set in isolated_environ, we have a proper
 
2810
        # access to disk resources now.
 
2811
        self.overrideEnv('BZR_LOG', None)
 
2812
 
2483
2813
    def check_file_contents(self, filename, expect):
2484
2814
        self.log("check contents of file %s" % filename)
2485
 
        contents = file(filename, 'r').read()
 
2815
        f = file(filename)
 
2816
        try:
 
2817
            contents = f.read()
 
2818
        finally:
 
2819
            f.close()
2486
2820
        if contents != expect:
2487
2821
            self.log("expected: %r" % expect)
2488
2822
            self.log("actually: %r" % contents)
2562
2896
                "a list or a tuple. Got %r instead" % (shape,))
2563
2897
        # It's OK to just create them using forward slashes on windows.
2564
2898
        if transport is None or transport.is_readonly():
2565
 
            transport = get_transport(".")
 
2899
            transport = _mod_transport.get_transport_from_path(".")
2566
2900
        for name in shape:
2567
2901
            self.assertIsInstance(name, basestring)
2568
2902
            if name[-1] == '/':
2578
2912
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2579
2913
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2580
2914
 
2581
 
    def build_tree_contents(self, shape):
2582
 
        build_tree_contents(shape)
 
2915
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2583
2916
 
2584
2917
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2585
2918
        """Assert whether path or paths are in the WorkingTree"""
2654
2987
        # this obviously requires a format that supports branch references
2655
2988
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2656
2989
        # RBC 20060208
 
2990
        format = self.resolve_format(format=format)
 
2991
        if not format.supports_workingtrees:
 
2992
            b = self.make_branch(relpath+'.branch', format=format)
 
2993
            return b.create_checkout(relpath, lightweight=True)
2657
2994
        b = self.make_branch(relpath, format=format)
2658
2995
        try:
2659
2996
            return b.bzrdir.create_workingtree()
2726
3063
    """
2727
3064
 
2728
3065
    def setUp(self):
 
3066
        from bzrlib.tests import http_server
2729
3067
        super(ChrootedTestCase, self).setUp()
2730
3068
        if not self.vfs_transport_factory == memory.MemoryServer:
2731
 
            self.transport_readonly_server = HttpServer
 
3069
            self.transport_readonly_server = http_server.HttpServer
2732
3070
 
2733
3071
 
2734
3072
def condition_id_re(pattern):
2737
3075
    :param pattern: A regular expression string.
2738
3076
    :return: A callable that returns True if the re matches.
2739
3077
    """
2740
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2741
 
        'test filter')
 
3078
    filter_re = re.compile(pattern, 0)
2742
3079
    def condition(test):
2743
3080
        test_id = test.id()
2744
3081
        return filter_re.search(test_id)
2958
3295
                            result_decorators=result_decorators,
2959
3296
                            )
2960
3297
    runner.stop_on_failure=stop_on_failure
 
3298
    if isinstance(suite, unittest.TestSuite):
 
3299
        # Empty out _tests list of passed suite and populate new TestSuite
 
3300
        suite._tests[:], suite = [], TestSuite(suite)
2961
3301
    # built in decorator factories:
2962
3302
    decorators = [
2963
3303
        random_order(random_seed, runner),
2996
3336
 
2997
3337
 
2998
3338
def fork_decorator(suite):
 
3339
    if getattr(os, "fork", None) is None:
 
3340
        raise errors.BzrCommandError("platform does not support fork,"
 
3341
            " try --parallel=subprocess instead.")
2999
3342
    concurrency = osutils.local_concurrency()
3000
3343
    if concurrency == 1:
3001
3344
        return suite
3056
3399
    return suite
3057
3400
 
3058
3401
 
3059
 
class TestDecorator(TestSuite):
 
3402
class TestDecorator(TestUtil.TestSuite):
3060
3403
    """A decorator for TestCase/TestSuite objects.
3061
 
    
3062
 
    Usually, subclasses should override __iter__(used when flattening test
3063
 
    suites), which we do to filter, reorder, parallelise and so on, run() and
3064
 
    debug().
 
3404
 
 
3405
    Contains rather than flattening suite passed on construction
3065
3406
    """
3066
3407
 
3067
 
    def __init__(self, suite):
3068
 
        TestSuite.__init__(self)
3069
 
        self.addTest(suite)
3070
 
 
3071
 
    def countTestCases(self):
3072
 
        cases = 0
3073
 
        for test in self:
3074
 
            cases += test.countTestCases()
3075
 
        return cases
3076
 
 
3077
 
    def debug(self):
3078
 
        for test in self:
3079
 
            test.debug()
3080
 
 
3081
 
    def run(self, result):
3082
 
        # Use iteration on self, not self._tests, to allow subclasses to hook
3083
 
        # into __iter__.
3084
 
        for test in self:
3085
 
            if result.shouldStop:
3086
 
                break
3087
 
            test.run(result)
3088
 
        return result
 
3408
    def __init__(self, suite=None):
 
3409
        super(TestDecorator, self).__init__()
 
3410
        if suite is not None:
 
3411
            self.addTest(suite)
 
3412
 
 
3413
    # Don't need subclass run method with suite emptying
 
3414
    run = unittest.TestSuite.run
3089
3415
 
3090
3416
 
3091
3417
class CountingDecorator(TestDecorator):
3102
3428
    """A decorator which excludes test matching an exclude pattern."""
3103
3429
 
3104
3430
    def __init__(self, suite, exclude_pattern):
3105
 
        TestDecorator.__init__(self, suite)
3106
 
        self.exclude_pattern = exclude_pattern
3107
 
        self.excluded = False
3108
 
 
3109
 
    def __iter__(self):
3110
 
        if self.excluded:
3111
 
            return iter(self._tests)
3112
 
        self.excluded = True
3113
 
        suite = exclude_tests_by_re(self, self.exclude_pattern)
3114
 
        del self._tests[:]
3115
 
        self.addTests(suite)
3116
 
        return iter(self._tests)
 
3431
        super(ExcludeDecorator, self).__init__(
 
3432
            exclude_tests_by_re(suite, exclude_pattern))
3117
3433
 
3118
3434
 
3119
3435
class FilterTestsDecorator(TestDecorator):
3120
3436
    """A decorator which filters tests to those matching a pattern."""
3121
3437
 
3122
3438
    def __init__(self, suite, pattern):
3123
 
        TestDecorator.__init__(self, suite)
3124
 
        self.pattern = pattern
3125
 
        self.filtered = False
3126
 
 
3127
 
    def __iter__(self):
3128
 
        if self.filtered:
3129
 
            return iter(self._tests)
3130
 
        self.filtered = True
3131
 
        suite = filter_suite_by_re(self, self.pattern)
3132
 
        del self._tests[:]
3133
 
        self.addTests(suite)
3134
 
        return iter(self._tests)
 
3439
        super(FilterTestsDecorator, self).__init__(
 
3440
            filter_suite_by_re(suite, pattern))
3135
3441
 
3136
3442
 
3137
3443
class RandomDecorator(TestDecorator):
3138
3444
    """A decorator which randomises the order of its tests."""
3139
3445
 
3140
3446
    def __init__(self, suite, random_seed, stream):
3141
 
        TestDecorator.__init__(self, suite)
3142
 
        self.random_seed = random_seed
3143
 
        self.randomised = False
3144
 
        self.stream = stream
3145
 
 
3146
 
    def __iter__(self):
3147
 
        if self.randomised:
3148
 
            return iter(self._tests)
3149
 
        self.randomised = True
3150
 
        self.stream.write("Randomizing test order using seed %s\n\n" %
3151
 
            (self.actual_seed()))
 
3447
        random_seed = self.actual_seed(random_seed)
 
3448
        stream.write("Randomizing test order using seed %s\n\n" %
 
3449
            (random_seed,))
3152
3450
        # Initialise the random number generator.
3153
 
        random.seed(self.actual_seed())
3154
 
        suite = randomize_suite(self)
3155
 
        del self._tests[:]
3156
 
        self.addTests(suite)
3157
 
        return iter(self._tests)
 
3451
        random.seed(random_seed)
 
3452
        super(RandomDecorator, self).__init__(randomize_suite(suite))
3158
3453
 
3159
 
    def actual_seed(self):
3160
 
        if self.random_seed == "now":
 
3454
    @staticmethod
 
3455
    def actual_seed(seed):
 
3456
        if seed == "now":
3161
3457
            # We convert the seed to a long to make it reuseable across
3162
3458
            # invocations (because the user can reenter it).
3163
 
            self.random_seed = long(time.time())
 
3459
            return long(time.time())
3164
3460
        else:
3165
3461
            # Convert the seed to a long if we can
3166
3462
            try:
3167
 
                self.random_seed = long(self.random_seed)
3168
 
            except:
 
3463
                return long(seed)
 
3464
            except (TypeError, ValueError):
3169
3465
                pass
3170
 
        return self.random_seed
 
3466
        return seed
3171
3467
 
3172
3468
 
3173
3469
class TestFirstDecorator(TestDecorator):
3174
3470
    """A decorator which moves named tests to the front."""
3175
3471
 
3176
3472
    def __init__(self, suite, pattern):
3177
 
        TestDecorator.__init__(self, suite)
3178
 
        self.pattern = pattern
3179
 
        self.filtered = False
3180
 
 
3181
 
    def __iter__(self):
3182
 
        if self.filtered:
3183
 
            return iter(self._tests)
3184
 
        self.filtered = True
3185
 
        suites = split_suite_by_re(self, self.pattern)
3186
 
        del self._tests[:]
3187
 
        self.addTests(suites)
3188
 
        return iter(self._tests)
 
3473
        super(TestFirstDecorator, self).__init__()
 
3474
        self.addTests(split_suite_by_re(suite, pattern))
3189
3475
 
3190
3476
 
3191
3477
def partition_tests(suite, count):
3192
3478
    """Partition suite into count lists of tests."""
3193
 
    result = []
3194
 
    tests = list(iter_suite_tests(suite))
3195
 
    tests_per_process = int(math.ceil(float(len(tests)) / count))
3196
 
    for block in range(count):
3197
 
        low_test = block * tests_per_process
3198
 
        high_test = low_test + tests_per_process
3199
 
        process_tests = tests[low_test:high_test]
3200
 
        result.append(process_tests)
3201
 
    return result
 
3479
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3480
    # splits up blocks of related tests that might run faster if they shared
 
3481
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3482
    # just one partition.  So the slowest partition shouldn't be much slower
 
3483
    # than the fastest.
 
3484
    partitions = [list() for i in range(count)]
 
3485
    tests = iter_suite_tests(suite)
 
3486
    for partition, test in itertools.izip(itertools.cycle(partitions), tests):
 
3487
        partition.append(test)
 
3488
    return partitions
3202
3489
 
3203
3490
 
3204
3491
def workaround_zealous_crypto_random():
3222
3509
    """
3223
3510
    concurrency = osutils.local_concurrency()
3224
3511
    result = []
3225
 
    from subunit import TestProtocolClient, ProtocolTestCase
 
3512
    from subunit import ProtocolTestCase
3226
3513
    from subunit.test_results import AutoTimingTestResultDecorator
3227
3514
    class TestInOtherProcess(ProtocolTestCase):
3228
3515
        # Should be in subunit, I think. RBC.
3234
3521
            try:
3235
3522
                ProtocolTestCase.run(self, result)
3236
3523
            finally:
3237
 
                os.waitpid(self.pid, 0)
 
3524
                pid, status = os.waitpid(self.pid, 0)
 
3525
            # GZ 2011-10-18: If status is nonzero, should report to the result
 
3526
            #                that something went wrong.
3238
3527
 
3239
3528
    test_blocks = partition_tests(suite, concurrency)
 
3529
    # Clear the tests from the original suite so it doesn't keep them alive
 
3530
    suite._tests[:] = []
3240
3531
    for process_tests in test_blocks:
3241
 
        process_suite = TestSuite()
3242
 
        process_suite.addTests(process_tests)
 
3532
        process_suite = TestUtil.TestSuite(process_tests)
 
3533
        # Also clear each split list so new suite has only reference
 
3534
        process_tests[:] = []
3243
3535
        c2pread, c2pwrite = os.pipe()
3244
3536
        pid = os.fork()
3245
3537
        if pid == 0:
3246
 
            workaround_zealous_crypto_random()
3247
3538
            try:
 
3539
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3540
                workaround_zealous_crypto_random()
3248
3541
                os.close(c2pread)
3249
3542
                # Leave stderr and stdout open so we can see test noise
3250
3543
                # Close stdin so that the child goes away if it decides to
3251
3544
                # read from stdin (otherwise its a roulette to see what
3252
3545
                # child actually gets keystrokes for pdb etc).
3253
3546
                sys.stdin.close()
3254
 
                sys.stdin = None
3255
 
                stream = os.fdopen(c2pwrite, 'wb', 1)
3256
3547
                subunit_result = AutoTimingTestResultDecorator(
3257
 
                    TestProtocolClient(stream))
 
3548
                    SubUnitBzrProtocolClient(stream))
3258
3549
                process_suite.run(subunit_result)
3259
 
            finally:
3260
 
                os._exit(0)
 
3550
            except:
 
3551
                # Try and report traceback on stream, but exit with error even
 
3552
                # if stream couldn't be created or something else goes wrong.
 
3553
                # The traceback is formatted to a string and written in one go
 
3554
                # to avoid interleaving lines from multiple failing children.
 
3555
                try:
 
3556
                    stream.write(traceback.format_exc())
 
3557
                finally:
 
3558
                    os._exit(1)
 
3559
            os._exit(0)
3261
3560
        else:
3262
3561
            os.close(c2pwrite)
3263
3562
            stream = os.fdopen(c2pread, 'rb', 1)
3310
3609
                '--subunit']
3311
3610
            if '--no-plugins' in sys.argv:
3312
3611
                argv.append('--no-plugins')
3313
 
            # stderr=STDOUT would be ideal, but until we prevent noise on
3314
 
            # stderr it can interrupt the subunit protocol.
3315
 
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3316
 
                bufsize=1)
 
3612
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3613
            # noise on stderr it can interrupt the subunit protocol.
 
3614
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3615
                                      stdout=subprocess.PIPE,
 
3616
                                      stderr=subprocess.PIPE,
 
3617
                                      bufsize=1)
3317
3618
            test = TestInSubprocess(process, test_list_file_name)
3318
3619
            result.append(test)
3319
3620
        except:
3322
3623
    return result
3323
3624
 
3324
3625
 
3325
 
class ForwardingResult(unittest.TestResult):
3326
 
 
3327
 
    def __init__(self, target):
3328
 
        unittest.TestResult.__init__(self)
3329
 
        self.result = target
3330
 
 
3331
 
    def startTest(self, test):
3332
 
        self.result.startTest(test)
3333
 
 
3334
 
    def stopTest(self, test):
3335
 
        self.result.stopTest(test)
3336
 
 
3337
 
    def startTestRun(self):
3338
 
        self.result.startTestRun()
3339
 
 
3340
 
    def stopTestRun(self):
3341
 
        self.result.stopTestRun()
3342
 
 
3343
 
    def addSkip(self, test, reason):
3344
 
        self.result.addSkip(test, reason)
3345
 
 
3346
 
    def addSuccess(self, test):
3347
 
        self.result.addSuccess(test)
3348
 
 
3349
 
    def addError(self, test, err):
3350
 
        self.result.addError(test, err)
3351
 
 
3352
 
    def addFailure(self, test, err):
3353
 
        self.result.addFailure(test, err)
3354
 
ForwardingResult = testtools.ExtendedToOriginalDecorator
3355
 
 
3356
 
 
3357
 
class ProfileResult(ForwardingResult):
 
3626
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3358
3627
    """Generate profiling data for all activity between start and success.
3359
3628
    
3360
3629
    The profile data is appended to the test's _benchcalls attribute and can
3368
3637
 
3369
3638
    def startTest(self, test):
3370
3639
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3640
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3641
        # unavoidably fail.
 
3642
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3371
3643
        self.profiler.start()
3372
 
        ForwardingResult.startTest(self, test)
 
3644
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3373
3645
 
3374
3646
    def addSuccess(self, test):
3375
3647
        stats = self.profiler.stop()
3379
3651
            test._benchcalls = []
3380
3652
            calls = test._benchcalls
3381
3653
        calls.append(((test.id(), "", ""), stats))
3382
 
        ForwardingResult.addSuccess(self, test)
 
3654
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3383
3655
 
3384
3656
    def stopTest(self, test):
3385
 
        ForwardingResult.stopTest(self, test)
 
3657
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3386
3658
        self.profiler = None
3387
3659
 
3388
3660
 
3394
3666
#                           rather than failing tests. And no longer raise
3395
3667
#                           LockContention when fctnl locks are not being used
3396
3668
#                           with proper exclusion rules.
 
3669
#   -Ethreads               Will display thread ident at creation/join time to
 
3670
#                           help track thread leaks
 
3671
#   -Euncollected_cases     Display the identity of any test cases that weren't
 
3672
#                           deallocated after being completed.
 
3673
#   -Econfig_stats          Will collect statistics using addDetail
3397
3674
selftest_debug_flags = set()
3398
3675
 
3399
3676
 
3593
3870
                key, obj, help=help, info=info, override_existing=False)
3594
3871
        except KeyError:
3595
3872
            actual = self.get(key)
3596
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3597
 
                 % (key, actual, obj))
 
3873
            trace.note(
 
3874
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3875
                % (key, actual, obj))
3598
3876
 
3599
3877
    def resolve_alias(self, id_start):
3600
3878
        """Replace the alias by the prefix in the given string.
3634
3912
        'bzrlib.tests.commands',
3635
3913
        'bzrlib.tests.per_branch',
3636
3914
        'bzrlib.tests.per_bzrdir',
3637
 
        'bzrlib.tests.per_bzrdir_colo',
 
3915
        'bzrlib.tests.per_controldir',
 
3916
        'bzrlib.tests.per_controldir_colo',
3638
3917
        'bzrlib.tests.per_foreign_vcs',
3639
3918
        'bzrlib.tests.per_interrepository',
3640
3919
        'bzrlib.tests.per_intertree',
3648
3927
        'bzrlib.tests.per_repository',
3649
3928
        'bzrlib.tests.per_repository_chk',
3650
3929
        'bzrlib.tests.per_repository_reference',
 
3930
        'bzrlib.tests.per_repository_vf',
3651
3931
        'bzrlib.tests.per_uifactory',
3652
3932
        'bzrlib.tests.per_versionedfile',
3653
3933
        'bzrlib.tests.per_workingtree',
3654
3934
        'bzrlib.tests.test__annotator',
3655
3935
        'bzrlib.tests.test__bencode',
 
3936
        'bzrlib.tests.test__btree_serializer',
3656
3937
        'bzrlib.tests.test__chk_map',
3657
3938
        'bzrlib.tests.test__dirstate_helpers',
3658
3939
        'bzrlib.tests.test__groupcompress',
3686
3967
        'bzrlib.tests.test_commit_merge',
3687
3968
        'bzrlib.tests.test_config',
3688
3969
        'bzrlib.tests.test_conflicts',
 
3970
        'bzrlib.tests.test_controldir',
3689
3971
        'bzrlib.tests.test_counted_lock',
3690
3972
        'bzrlib.tests.test_crash',
3691
3973
        'bzrlib.tests.test_decorators',
3692
3974
        'bzrlib.tests.test_delta',
3693
3975
        'bzrlib.tests.test_debug',
3694
 
        'bzrlib.tests.test_deprecated_graph',
3695
3976
        'bzrlib.tests.test_diff',
3696
3977
        'bzrlib.tests.test_directory_service',
3697
3978
        'bzrlib.tests.test_dirstate',
3698
3979
        'bzrlib.tests.test_email_message',
3699
3980
        'bzrlib.tests.test_eol_filters',
3700
3981
        'bzrlib.tests.test_errors',
 
3982
        'bzrlib.tests.test_estimate_compressed_size',
3701
3983
        'bzrlib.tests.test_export',
 
3984
        'bzrlib.tests.test_export_pot',
3702
3985
        'bzrlib.tests.test_extract',
 
3986
        'bzrlib.tests.test_features',
3703
3987
        'bzrlib.tests.test_fetch',
 
3988
        'bzrlib.tests.test_fixtures',
3704
3989
        'bzrlib.tests.test_fifo_cache',
3705
3990
        'bzrlib.tests.test_filters',
 
3991
        'bzrlib.tests.test_filter_tree',
3706
3992
        'bzrlib.tests.test_ftp_transport',
3707
3993
        'bzrlib.tests.test_foreign',
3708
3994
        'bzrlib.tests.test_generate_docs',
3717
4003
        'bzrlib.tests.test_http',
3718
4004
        'bzrlib.tests.test_http_response',
3719
4005
        'bzrlib.tests.test_https_ca_bundle',
 
4006
        'bzrlib.tests.test_https_urllib',
 
4007
        'bzrlib.tests.test_i18n',
3720
4008
        'bzrlib.tests.test_identitymap',
3721
4009
        'bzrlib.tests.test_ignores',
3722
4010
        'bzrlib.tests.test_index',
3727
4015
        'bzrlib.tests.test_knit',
3728
4016
        'bzrlib.tests.test_lazy_import',
3729
4017
        'bzrlib.tests.test_lazy_regex',
 
4018
        'bzrlib.tests.test_library_state',
3730
4019
        'bzrlib.tests.test_lock',
3731
4020
        'bzrlib.tests.test_lockable_files',
3732
4021
        'bzrlib.tests.test_lockdir',
3734
4023
        'bzrlib.tests.test_lru_cache',
3735
4024
        'bzrlib.tests.test_lsprof',
3736
4025
        'bzrlib.tests.test_mail_client',
 
4026
        'bzrlib.tests.test_matchers',
3737
4027
        'bzrlib.tests.test_memorytree',
3738
4028
        'bzrlib.tests.test_merge',
3739
4029
        'bzrlib.tests.test_merge3',
3740
4030
        'bzrlib.tests.test_merge_core',
3741
4031
        'bzrlib.tests.test_merge_directive',
 
4032
        'bzrlib.tests.test_mergetools',
3742
4033
        'bzrlib.tests.test_missing',
3743
4034
        'bzrlib.tests.test_msgeditor',
3744
4035
        'bzrlib.tests.test_multiparent',
3753
4044
        'bzrlib.tests.test_permissions',
3754
4045
        'bzrlib.tests.test_plugins',
3755
4046
        'bzrlib.tests.test_progress',
 
4047
        'bzrlib.tests.test_pyutils',
3756
4048
        'bzrlib.tests.test_read_bundle',
3757
4049
        'bzrlib.tests.test_reconcile',
3758
4050
        'bzrlib.tests.test_reconfigure',
3766
4058
        'bzrlib.tests.test_revisiontree',
3767
4059
        'bzrlib.tests.test_rio',
3768
4060
        'bzrlib.tests.test_rules',
 
4061
        'bzrlib.tests.test_url_policy_open',
3769
4062
        'bzrlib.tests.test_sampler',
 
4063
        'bzrlib.tests.test_scenarios',
3770
4064
        'bzrlib.tests.test_script',
3771
4065
        'bzrlib.tests.test_selftest',
3772
4066
        'bzrlib.tests.test_serializer',
3777
4071
        'bzrlib.tests.test_smart',
3778
4072
        'bzrlib.tests.test_smart_add',
3779
4073
        'bzrlib.tests.test_smart_request',
 
4074
        'bzrlib.tests.test_smart_signals',
3780
4075
        'bzrlib.tests.test_smart_transport',
3781
4076
        'bzrlib.tests.test_smtp_connection',
3782
4077
        'bzrlib.tests.test_source',
3788
4083
        'bzrlib.tests.test_switch',
3789
4084
        'bzrlib.tests.test_symbol_versioning',
3790
4085
        'bzrlib.tests.test_tag',
 
4086
        'bzrlib.tests.test_test_server',
3791
4087
        'bzrlib.tests.test_testament',
3792
4088
        'bzrlib.tests.test_textfile',
3793
4089
        'bzrlib.tests.test_textmerge',
 
4090
        'bzrlib.tests.test_cethread',
3794
4091
        'bzrlib.tests.test_timestamp',
3795
4092
        'bzrlib.tests.test_trace',
3796
4093
        'bzrlib.tests.test_transactions',
3799
4096
        'bzrlib.tests.test_transport_log',
3800
4097
        'bzrlib.tests.test_tree',
3801
4098
        'bzrlib.tests.test_treebuilder',
 
4099
        'bzrlib.tests.test_treeshape',
3802
4100
        'bzrlib.tests.test_tsort',
3803
4101
        'bzrlib.tests.test_tuned_gzip',
3804
4102
        'bzrlib.tests.test_ui',
3806
4104
        'bzrlib.tests.test_upgrade',
3807
4105
        'bzrlib.tests.test_upgrade_stacked',
3808
4106
        'bzrlib.tests.test_urlutils',
 
4107
        'bzrlib.tests.test_utextwrap',
3809
4108
        'bzrlib.tests.test_version',
3810
4109
        'bzrlib.tests.test_version_info',
 
4110
        'bzrlib.tests.test_versionedfile',
 
4111
        'bzrlib.tests.test_vf_search',
3811
4112
        'bzrlib.tests.test_weave',
3812
4113
        'bzrlib.tests.test_whitebox',
3813
4114
        'bzrlib.tests.test_win32utils',
3827
4128
        'bzrlib',
3828
4129
        'bzrlib.branchbuilder',
3829
4130
        'bzrlib.decorators',
3830
 
        'bzrlib.export',
3831
4131
        'bzrlib.inventory',
3832
4132
        'bzrlib.iterablefile',
3833
4133
        'bzrlib.lockdir',
3834
4134
        'bzrlib.merge3',
3835
4135
        'bzrlib.option',
 
4136
        'bzrlib.pyutils',
3836
4137
        'bzrlib.symbol_versioning',
3837
4138
        'bzrlib.tests',
 
4139
        'bzrlib.tests.fixtures',
3838
4140
        'bzrlib.timestamp',
 
4141
        'bzrlib.transport.http',
3839
4142
        'bzrlib.version_info_formats.format_custom',
3840
4143
        ]
3841
4144
 
3894
4197
        try:
3895
4198
            # note that this really does mean "report only" -- doctest
3896
4199
            # still runs the rest of the examples
3897
 
            doc_suite = doctest.DocTestSuite(mod,
3898
 
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4200
            doc_suite = IsolatedDocTestSuite(
 
4201
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3899
4202
        except ValueError, e:
3900
4203
            print '**failed to get doctest for: %s\n%s' % (mod, e)
3901
4204
            raise
3904
4207
        suite.addTest(doc_suite)
3905
4208
 
3906
4209
    default_encoding = sys.getdefaultencoding()
3907
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4210
    for name, plugin in _mod_plugin.plugins().items():
3908
4211
        if not interesting_module(plugin.module.__name__):
3909
4212
            continue
3910
4213
        plugin_suite = plugin.test_suite()
3916
4219
        if plugin_suite is not None:
3917
4220
            suite.addTest(plugin_suite)
3918
4221
        if default_encoding != sys.getdefaultencoding():
3919
 
            bzrlib.trace.warning(
 
4222
            trace.warning(
3920
4223
                'Plugin "%s" tried to reset default encoding to: %s', name,
3921
4224
                sys.getdefaultencoding())
3922
4225
            reload(sys)
3937
4240
            # Some tests mentioned in the list are not in the test suite. The
3938
4241
            # list may be out of date, report to the tester.
3939
4242
            for id in not_found:
3940
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4243
                trace.warning('"%s" not found in the test suite', id)
3941
4244
        for id in duplicates:
3942
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4245
            trace.warning('"%s" is used as an id by several tests', id)
3943
4246
 
3944
4247
    return suite
3945
4248
 
3946
4249
 
3947
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4250
def multiply_scenarios(*scenarios):
 
4251
    """Multiply two or more iterables of scenarios.
 
4252
 
 
4253
    It is safe to pass scenario generators or iterators.
 
4254
 
 
4255
    :returns: A list of compound scenarios: the cross-product of all 
 
4256
        scenarios, with the names concatenated and the parameters
 
4257
        merged together.
 
4258
    """
 
4259
    return reduce(_multiply_two_scenarios, map(list, scenarios))
 
4260
 
 
4261
 
 
4262
def _multiply_two_scenarios(scenarios_left, scenarios_right):
3948
4263
    """Multiply two sets of scenarios.
3949
4264
 
3950
4265
    :returns: the cartesian product of the two sets of scenarios, that is
3981
4296
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
3982
4297
    ...     [('one', dict(param=1)),
3983
4298
    ...      ('two', dict(param=2))],
3984
 
    ...     TestSuite())
 
4299
    ...     TestUtil.TestSuite())
3985
4300
    >>> tests = list(iter_suite_tests(r))
3986
4301
    >>> len(tests)
3987
4302
    2
4034
4349
    :param new_id: The id to assign to it.
4035
4350
    :return: The new test.
4036
4351
    """
4037
 
    new_test = copy(test)
 
4352
    new_test = copy.copy(test)
4038
4353
    new_test.id = lambda: new_id
 
4354
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4355
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4356
    # read the test output for parameterized tests, because tracebacks will be
 
4357
    # associated with irrelevant tests.
 
4358
    try:
 
4359
        details = new_test._TestCase__details
 
4360
    except AttributeError:
 
4361
        # must be a different version of testtools than expected.  Do nothing.
 
4362
        pass
 
4363
    else:
 
4364
        # Reset the '__details' dict.
 
4365
        new_test._TestCase__details = {}
4039
4366
    return new_test
4040
4367
 
4041
4368
 
4062
4389
        the module is available.
4063
4390
    """
4064
4391
 
4065
 
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4392
    from bzrlib.tests.features import ModuleAvailableFeature
 
4393
    py_module = pyutils.get_named_object(py_module_name)
4066
4394
    scenarios = [
4067
4395
        ('python', {'module': py_module}),
4068
4396
    ]
4101
4429
        if test_id != None:
4102
4430
            ui.ui_factory.clear_term()
4103
4431
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4432
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4433
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4434
                                    ).encode('ascii', 'replace')
4104
4435
        sys.stderr.write('Unable to remove testing dir %s\n%s'
4105
 
                         % (os.path.basename(dirname), e))
4106
 
 
4107
 
 
4108
 
class Feature(object):
4109
 
    """An operating system Feature."""
4110
 
 
4111
 
    def __init__(self):
4112
 
        self._available = None
4113
 
 
4114
 
    def available(self):
4115
 
        """Is the feature available?
4116
 
 
4117
 
        :return: True if the feature is available.
4118
 
        """
4119
 
        if self._available is None:
4120
 
            self._available = self._probe()
4121
 
        return self._available
4122
 
 
4123
 
    def _probe(self):
4124
 
        """Implement this method in concrete features.
4125
 
 
4126
 
        :return: True if the feature is available.
4127
 
        """
4128
 
        raise NotImplementedError
4129
 
 
4130
 
    def __str__(self):
4131
 
        if getattr(self, 'feature_name', None):
4132
 
            return self.feature_name()
4133
 
        return self.__class__.__name__
4134
 
 
4135
 
 
4136
 
class _SymlinkFeature(Feature):
4137
 
 
4138
 
    def _probe(self):
4139
 
        return osutils.has_symlinks()
4140
 
 
4141
 
    def feature_name(self):
4142
 
        return 'symlinks'
4143
 
 
4144
 
SymlinkFeature = _SymlinkFeature()
4145
 
 
4146
 
 
4147
 
class _HardlinkFeature(Feature):
4148
 
 
4149
 
    def _probe(self):
4150
 
        return osutils.has_hardlinks()
4151
 
 
4152
 
    def feature_name(self):
4153
 
        return 'hardlinks'
4154
 
 
4155
 
HardlinkFeature = _HardlinkFeature()
4156
 
 
4157
 
 
4158
 
class _OsFifoFeature(Feature):
4159
 
 
4160
 
    def _probe(self):
4161
 
        return getattr(os, 'mkfifo', None)
4162
 
 
4163
 
    def feature_name(self):
4164
 
        return 'filesystem fifos'
4165
 
 
4166
 
OsFifoFeature = _OsFifoFeature()
4167
 
 
4168
 
 
4169
 
class _UnicodeFilenameFeature(Feature):
4170
 
    """Does the filesystem support Unicode filenames?"""
4171
 
 
4172
 
    def _probe(self):
4173
 
        try:
4174
 
            # Check for character combinations unlikely to be covered by any
4175
 
            # single non-unicode encoding. We use the characters
4176
 
            # - greek small letter alpha (U+03B1) and
4177
 
            # - braille pattern dots-123456 (U+283F).
4178
 
            os.stat(u'\u03b1\u283f')
4179
 
        except UnicodeEncodeError:
4180
 
            return False
4181
 
        except (IOError, OSError):
4182
 
            # The filesystem allows the Unicode filename but the file doesn't
4183
 
            # exist.
4184
 
            return True
4185
 
        else:
4186
 
            # The filesystem allows the Unicode filename and the file exists,
4187
 
            # for some reason.
4188
 
            return True
4189
 
 
4190
 
UnicodeFilenameFeature = _UnicodeFilenameFeature()
4191
 
 
4192
 
 
4193
 
class _CompatabilityThunkFeature(Feature):
4194
 
    """This feature is just a thunk to another feature.
4195
 
 
4196
 
    It issues a deprecation warning if it is accessed, to let you know that you
4197
 
    should really use a different feature.
4198
 
    """
4199
 
 
4200
 
    def __init__(self, dep_version, module, name,
4201
 
                 replacement_name, replacement_module=None):
4202
 
        super(_CompatabilityThunkFeature, self).__init__()
4203
 
        self._module = module
4204
 
        if replacement_module is None:
4205
 
            replacement_module = module
4206
 
        self._replacement_module = replacement_module
4207
 
        self._name = name
4208
 
        self._replacement_name = replacement_name
4209
 
        self._dep_version = dep_version
4210
 
        self._feature = None
4211
 
 
4212
 
    def _ensure(self):
4213
 
        if self._feature is None:
4214
 
            depr_msg = self._dep_version % ('%s.%s'
4215
 
                                            % (self._module, self._name))
4216
 
            use_msg = ' Use %s.%s instead.' % (self._replacement_module,
4217
 
                                               self._replacement_name)
4218
 
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
4219
 
            # Import the new feature and use it as a replacement for the
4220
 
            # deprecated one.
4221
 
            mod = __import__(self._replacement_module, {}, {},
4222
 
                             [self._replacement_name])
4223
 
            self._feature = getattr(mod, self._replacement_name)
4224
 
 
4225
 
    def _probe(self):
4226
 
        self._ensure()
4227
 
        return self._feature._probe()
4228
 
 
4229
 
 
4230
 
class ModuleAvailableFeature(Feature):
4231
 
    """This is a feature than describes a module we want to be available.
4232
 
 
4233
 
    Declare the name of the module in __init__(), and then after probing, the
4234
 
    module will be available as 'self.module'.
4235
 
 
4236
 
    :ivar module: The module if it is available, else None.
4237
 
    """
4238
 
 
4239
 
    def __init__(self, module_name):
4240
 
        super(ModuleAvailableFeature, self).__init__()
4241
 
        self.module_name = module_name
4242
 
 
4243
 
    def _probe(self):
4244
 
        try:
4245
 
            self._module = __import__(self.module_name, {}, {}, [''])
4246
 
            return True
4247
 
        except ImportError:
4248
 
            return False
4249
 
 
4250
 
    @property
4251
 
    def module(self):
4252
 
        if self.available(): # Make sure the probe has been done
4253
 
            return self._module
4254
 
        return None
4255
 
 
4256
 
    def feature_name(self):
4257
 
        return self.module_name
4258
 
 
4259
 
 
4260
 
# This is kept here for compatibility, it is recommended to use
4261
 
# 'bzrlib.tests.feature.paramiko' instead
4262
 
ParamikoFeature = _CompatabilityThunkFeature(
4263
 
    deprecated_in((2,1,0)),
4264
 
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
 
4436
                         % (os.path.basename(dirname), printable_e))
4265
4437
 
4266
4438
 
4267
4439
def probe_unicode_in_user_encoding():
4297
4469
    return None
4298
4470
 
4299
4471
 
4300
 
class _HTTPSServerFeature(Feature):
4301
 
    """Some tests want an https Server, check if one is available.
4302
 
 
4303
 
    Right now, the only way this is available is under python2.6 which provides
4304
 
    an ssl module.
4305
 
    """
4306
 
 
4307
 
    def _probe(self):
4308
 
        try:
4309
 
            import ssl
4310
 
            return True
4311
 
        except ImportError:
4312
 
            return False
4313
 
 
4314
 
    def feature_name(self):
4315
 
        return 'HTTPSServer'
4316
 
 
4317
 
 
4318
 
HTTPSServerFeature = _HTTPSServerFeature()
4319
 
 
4320
 
 
4321
 
class _UnicodeFilename(Feature):
4322
 
    """Does the filesystem support Unicode filenames?"""
4323
 
 
4324
 
    def _probe(self):
4325
 
        try:
4326
 
            os.stat(u'\u03b1')
4327
 
        except UnicodeEncodeError:
4328
 
            return False
4329
 
        except (IOError, OSError):
4330
 
            # The filesystem allows the Unicode filename but the file doesn't
4331
 
            # exist.
4332
 
            return True
4333
 
        else:
4334
 
            # The filesystem allows the Unicode filename and the file exists,
4335
 
            # for some reason.
4336
 
            return True
4337
 
 
4338
 
UnicodeFilename = _UnicodeFilename()
4339
 
 
4340
 
 
4341
 
class _UTF8Filesystem(Feature):
4342
 
    """Is the filesystem UTF-8?"""
4343
 
 
4344
 
    def _probe(self):
4345
 
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
4346
 
            return True
4347
 
        return False
4348
 
 
4349
 
UTF8Filesystem = _UTF8Filesystem()
4350
 
 
4351
 
 
4352
 
class _BreakinFeature(Feature):
4353
 
    """Does this platform support the breakin feature?"""
4354
 
 
4355
 
    def _probe(self):
4356
 
        from bzrlib import breakin
4357
 
        if breakin.determine_signal() is None:
4358
 
            return False
4359
 
        if sys.platform == 'win32':
4360
 
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
4361
 
            # We trigger SIGBREAK via a Console api so we need ctypes to
4362
 
            # access the function
4363
 
            try:
4364
 
                import ctypes
4365
 
            except OSError:
4366
 
                return False
4367
 
        return True
4368
 
 
4369
 
    def feature_name(self):
4370
 
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
4371
 
 
4372
 
 
4373
 
BreakinFeature = _BreakinFeature()
4374
 
 
4375
 
 
4376
 
class _CaseInsCasePresFilenameFeature(Feature):
4377
 
    """Is the file-system case insensitive, but case-preserving?"""
4378
 
 
4379
 
    def _probe(self):
4380
 
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
4381
 
        try:
4382
 
            # first check truly case-preserving for created files, then check
4383
 
            # case insensitive when opening existing files.
4384
 
            name = osutils.normpath(name)
4385
 
            base, rel = osutils.split(name)
4386
 
            found_rel = osutils.canonical_relpath(base, name)
4387
 
            return (found_rel == rel
4388
 
                    and os.path.isfile(name.upper())
4389
 
                    and os.path.isfile(name.lower()))
4390
 
        finally:
4391
 
            os.close(fileno)
4392
 
            os.remove(name)
4393
 
 
4394
 
    def feature_name(self):
4395
 
        return "case-insensitive case-preserving filesystem"
4396
 
 
4397
 
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
4398
 
 
4399
 
 
4400
 
class _CaseInsensitiveFilesystemFeature(Feature):
4401
 
    """Check if underlying filesystem is case-insensitive but *not* case
4402
 
    preserving.
4403
 
    """
4404
 
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
4405
 
    # more likely to be case preserving, so this case is rare.
4406
 
 
4407
 
    def _probe(self):
4408
 
        if CaseInsCasePresFilenameFeature.available():
4409
 
            return False
4410
 
 
4411
 
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
4412
 
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
4413
 
            TestCaseWithMemoryTransport.TEST_ROOT = root
4414
 
        else:
4415
 
            root = TestCaseWithMemoryTransport.TEST_ROOT
4416
 
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
4417
 
            dir=root)
4418
 
        name_a = osutils.pathjoin(tdir, 'a')
4419
 
        name_A = osutils.pathjoin(tdir, 'A')
4420
 
        os.mkdir(name_a)
4421
 
        result = osutils.isdir(name_A)
4422
 
        _rmtree_temp_dir(tdir)
4423
 
        return result
4424
 
 
4425
 
    def feature_name(self):
4426
 
        return 'case-insensitive filesystem'
4427
 
 
4428
 
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
4429
 
 
4430
 
 
4431
 
class _CaseSensitiveFilesystemFeature(Feature):
4432
 
 
4433
 
    def _probe(self):
4434
 
        if CaseInsCasePresFilenameFeature.available():
4435
 
            return False
4436
 
        elif CaseInsensitiveFilesystemFeature.available():
4437
 
            return False
4438
 
        else:
4439
 
            return True
4440
 
 
4441
 
    def feature_name(self):
4442
 
        return 'case-sensitive filesystem'
4443
 
 
4444
 
# new coding style is for feature instances to be lowercase
4445
 
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
4446
 
 
4447
 
 
4448
 
# Kept for compatibility, use bzrlib.tests.features.subunit instead
4449
 
SubUnitFeature = _CompatabilityThunkFeature(
4450
 
    deprecated_in((2,1,0)),
4451
 
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
4452
4472
# Only define SubUnitBzrRunner if subunit is available.
4453
4473
try:
4454
4474
    from subunit import TestProtocolClient
4455
4475
    from subunit.test_results import AutoTimingTestResultDecorator
 
4476
    class SubUnitBzrProtocolClient(TestProtocolClient):
 
4477
 
 
4478
        def stopTest(self, test):
 
4479
            super(SubUnitBzrProtocolClient, self).stopTest(test)
 
4480
            _clear__type_equality_funcs(test)
 
4481
 
 
4482
        def addSuccess(self, test, details=None):
 
4483
            # The subunit client always includes the details in the subunit
 
4484
            # stream, but we don't want to include it in ours.
 
4485
            if details is not None and 'log' in details:
 
4486
                del details['log']
 
4487
            return super(SubUnitBzrProtocolClient, self).addSuccess(
 
4488
                test, details)
 
4489
 
4456
4490
    class SubUnitBzrRunner(TextTestRunner):
4457
4491
        def run(self, test):
4458
4492
            result = AutoTimingTestResultDecorator(
4459
 
                TestProtocolClient(self.stream))
 
4493
                SubUnitBzrProtocolClient(self.stream))
4460
4494
            test.run(result)
4461
4495
            return result
4462
4496
except ImportError:
4463
4497
    pass
4464
4498
 
4465
 
class _PosixPermissionsFeature(Feature):
4466
 
 
4467
 
    def _probe(self):
4468
 
        def has_perms():
4469
 
            # create temporary file and check if specified perms are maintained.
4470
 
            import tempfile
4471
 
 
4472
 
            write_perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
4473
 
            f = tempfile.mkstemp(prefix='bzr_perms_chk_')
4474
 
            fd, name = f
4475
 
            os.close(fd)
4476
 
            os.chmod(name, write_perms)
4477
 
 
4478
 
            read_perms = os.stat(name).st_mode & 0777
4479
 
            os.unlink(name)
4480
 
            return (write_perms == read_perms)
4481
 
 
4482
 
        return (os.name == 'posix') and has_perms()
4483
 
 
4484
 
    def feature_name(self):
4485
 
        return 'POSIX permissions support'
4486
 
 
4487
 
posix_permissions_feature = _PosixPermissionsFeature()
 
4499
 
 
4500
# API compatibility for old plugins; see bug 892622.
 
4501
for name in [
 
4502
    'Feature',
 
4503
    'HTTPServerFeature', 
 
4504
    'ModuleAvailableFeature',
 
4505
    'HTTPSServerFeature', 'SymlinkFeature', 'HardlinkFeature',
 
4506
    'OsFifoFeature', 'UnicodeFilenameFeature',
 
4507
    'ByteStringNamedFilesystem', 'UTF8Filesystem',
 
4508
    'BreakinFeature', 'CaseInsCasePresFilenameFeature',
 
4509
    'CaseInsensitiveFilesystemFeature', 'case_sensitive_filesystem_feature',
 
4510
    'posix_permissions_feature',
 
4511
    ]:
 
4512
    globals()[name] = _CompatabilityThunkFeature(
 
4513
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4514
        'bzrlib.tests', name,
 
4515
        name, 'bzrlib.tests.features')
 
4516
 
 
4517
 
 
4518
for (old_name, new_name) in [
 
4519
    ('UnicodeFilename', 'UnicodeFilenameFeature'),
 
4520
    ]:
 
4521
    globals()[name] = _CompatabilityThunkFeature(
 
4522
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4523
        'bzrlib.tests', old_name,
 
4524
        new_name, 'bzrlib.tests.features')