~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Wouter van Heyst
  • Date: 2012-01-25 19:07:22 UTC
  • mfrom: (6437.19.2 2.5)
  • mto: (6437.3.27 2.5)
  • mto: This revision was merged to the branch mainline in revision 6451.
  • Revision ID: larstiq@larstiq.dyndns.org-20120125190722-1bf3j0d6my1zd8v1
ensure files actually hit the disk under pypy

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
    # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
 
141
    # tests do check our impls match APPDATA
 
142
    'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
143
    'VISUAL': None,
 
144
    'EDITOR': None,
 
145
    'BZR_EMAIL': None,
 
146
    'BZREMAIL': None, # may still be present in the environment
 
147
    'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
 
148
    'BZR_PROGRESS_BAR': None,
 
149
    # This should trap leaks to ~/.bzr.log. This occurs when tests use TestCase
 
150
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
 
151
    # TestCase should not use disk resources, BZR_LOG is one.
 
152
    'BZR_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
153
    'BZR_PLUGIN_PATH': None,
 
154
    'BZR_DISABLE_PLUGINS': None,
 
155
    'BZR_PLUGINS_AT': None,
 
156
    'BZR_CONCURRENCY': None,
 
157
    # Make sure that any text ui tests are consistent regardless of
 
158
    # the environment the test case is run in; you may want tests that
 
159
    # test other combinations.  'dumb' is a reasonable guess for tests
 
160
    # going to a pipe or a StringIO.
 
161
    'TERM': 'dumb',
 
162
    'LINES': '25',
 
163
    'COLUMNS': '80',
 
164
    'BZR_COLUMNS': '80',
 
165
    # Disable SSH Agent
 
166
    'SSH_AUTH_SOCK': None,
 
167
    # Proxies
 
168
    'http_proxy': None,
 
169
    'HTTP_PROXY': None,
 
170
    'https_proxy': None,
 
171
    'HTTPS_PROXY': None,
 
172
    'no_proxy': None,
 
173
    'NO_PROXY': None,
 
174
    'all_proxy': None,
 
175
    'ALL_PROXY': None,
 
176
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
177
    # least. If you do (care), please update this comment
 
178
    # -- vila 20080401
 
179
    'ftp_proxy': None,
 
180
    'FTP_PROXY': None,
 
181
    'BZR_REMOTE_PATH': None,
 
182
    # Generally speaking, we don't want apport reporting on crashes in
 
183
    # the test envirnoment unless we're specifically testing apport,
 
184
    # so that it doesn't leak into the real system environment.  We
 
185
    # use an env var so it propagates to subprocesses.
 
186
    'APPORT_DISABLE': '1',
 
187
    }
 
188
 
 
189
 
 
190
def override_os_environ(test, env=None):
 
191
    """Modify os.environ keeping a copy.
 
192
    
 
193
    :param test: A test instance
 
194
 
 
195
    :param env: A dict containing variable definitions to be installed
 
196
    """
 
197
    if env is None:
 
198
        env = isolated_environ
 
199
    test._original_os_environ = dict([(var, value)
 
200
                                      for var, value in os.environ.iteritems()])
 
201
    for var, value in env.iteritems():
 
202
        osutils.set_or_unset_env(var, value)
 
203
        if var not in test._original_os_environ:
 
204
            # The var is new, add it with a value of None, so
 
205
            # restore_os_environ will delete it
 
206
            test._original_os_environ[var] = None
 
207
 
 
208
 
 
209
def restore_os_environ(test):
 
210
    """Restore os.environ to its original state.
 
211
 
 
212
    :param test: A test instance previously passed to override_os_environ.
 
213
    """
 
214
    for var, value in test._original_os_environ.iteritems():
 
215
        # Restore the original value (or delete it if the value has been set to
 
216
        # None in override_os_environ).
 
217
        osutils.set_or_unset_env(var, value)
 
218
 
 
219
 
 
220
def _clear__type_equality_funcs(test):
 
221
    """Cleanup bound methods stored on TestCase instances
 
222
 
 
223
    Clear the dict breaking a few (mostly) harmless cycles in the affected
 
224
    unittests released with Python 2.6 and initial Python 2.7 versions.
 
225
 
 
226
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
 
227
    shipped in Oneiric, an object with no clear method was used, hence the
 
228
    extra complications, see bug 809048 for details.
 
229
    """
 
230
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
231
    if type_equality_funcs is not None:
 
232
        tef_clear = getattr(type_equality_funcs, "clear", None)
 
233
        if tef_clear is None:
 
234
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
 
235
            if tef_instance_dict is not None:
 
236
                tef_clear = tef_instance_dict.clear
 
237
        if tef_clear is not None:
 
238
            tef_clear()
 
239
 
 
240
 
 
241
class ExtendedTestResult(testtools.TextTestResult):
145
242
    """Accepts, reports and accumulates the results of running tests.
146
243
 
147
244
    Compared to the unittest version this class adds support for
168
265
        :param bench_history: Optionally, a writable file object to accumulate
169
266
            benchmark results.
170
267
        """
171
 
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
268
        testtools.TextTestResult.__init__(self, stream)
172
269
        if bench_history is not None:
173
270
            from bzrlib.version import _get_bzr_source_tree
174
271
            src_tree = _get_bzr_source_tree()
195
292
        self.count = 0
196
293
        self._overall_start_time = time.time()
197
294
        self._strict = strict
 
295
        self._first_thread_leaker_id = None
 
296
        self._tests_leaking_threads_count = 0
 
297
        self._traceback_from_test = None
198
298
 
199
299
    def stopTestRun(self):
200
300
        run = self.testsRun
201
301
        actionTaken = "Ran"
202
302
        stopTime = time.time()
203
303
        timeTaken = stopTime - self.startTime
204
 
        self.printErrors()
205
 
        self.stream.writeln(self.separator2)
206
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
304
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
 
305
        #                the parent class method is similar have to duplicate
 
306
        self._show_list('ERROR', self.errors)
 
307
        self._show_list('FAIL', self.failures)
 
308
        self.stream.write(self.sep2)
 
309
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
207
310
                            run, run != 1 and "s" or "", timeTaken))
208
 
        self.stream.writeln()
209
311
        if not self.wasSuccessful():
210
312
            self.stream.write("FAILED (")
211
313
            failed, errored = map(len, (self.failures, self.errors))
218
320
                if failed or errored: self.stream.write(", ")
219
321
                self.stream.write("known_failure_count=%d" %
220
322
                    self.known_failure_count)
221
 
            self.stream.writeln(")")
 
323
            self.stream.write(")\n")
222
324
        else:
223
325
            if self.known_failure_count:
224
 
                self.stream.writeln("OK (known_failures=%d)" %
 
326
                self.stream.write("OK (known_failures=%d)\n" %
225
327
                    self.known_failure_count)
226
328
            else:
227
 
                self.stream.writeln("OK")
 
329
                self.stream.write("OK\n")
228
330
        if self.skip_count > 0:
229
331
            skipped = self.skip_count
230
 
            self.stream.writeln('%d test%s skipped' %
 
332
            self.stream.write('%d test%s skipped\n' %
231
333
                                (skipped, skipped != 1 and "s" or ""))
232
334
        if self.unsupported:
233
335
            for feature, count in sorted(self.unsupported.items()):
234
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
336
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
235
337
                    (feature, count))
236
338
        if self._strict:
237
339
            ok = self.wasStrictlySuccessful()
238
340
        else:
239
341
            ok = self.wasSuccessful()
240
 
        if TestCase._first_thread_leaker_id:
 
342
        if self._first_thread_leaker_id:
241
343
            self.stream.write(
242
344
                '%s is leaking threads among %d leaking tests.\n' % (
243
 
                TestCase._first_thread_leaker_id,
244
 
                TestCase._leaking_threads_tests))
 
345
                self._first_thread_leaker_id,
 
346
                self._tests_leaking_threads_count))
245
347
            # We don't report the main thread as an active one.
246
348
            self.stream.write(
247
349
                '%d non-main threads were left active in the end.\n'
248
 
                % (TestCase._active_threads - 1))
 
350
                % (len(self._active_threads) - 1))
249
351
 
250
352
    def getDescription(self, test):
251
353
        return test.id()
258
360
 
259
361
    def _elapsedTestTimeString(self):
260
362
        """Return a time string for the overall time the current test has taken."""
261
 
        return self._formatTime(time.time() - self._start_time)
 
363
        return self._formatTime(self._delta_to_float(
 
364
            self._now() - self._start_datetime))
262
365
 
263
366
    def _testTimeString(self, testCase):
264
367
        benchmark_time = self._extractBenchmarkTime(testCase)
275
378
 
276
379
    def _shortened_test_description(self, test):
277
380
        what = test.id()
278
 
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
381
        what = re.sub(r'^bzrlib\.tests\.', '', what)
279
382
        return what
280
383
 
 
384
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
385
    #                multiple times in a row, because the handler is added for
 
386
    #                each test but the container list is shared between cases.
 
387
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
388
    def _record_traceback_from_test(self, exc_info):
 
389
        """Store the traceback from passed exc_info tuple till"""
 
390
        self._traceback_from_test = exc_info[2]
 
391
 
281
392
    def startTest(self, test):
282
 
        unittest.TestResult.startTest(self, test)
 
393
        super(ExtendedTestResult, self).startTest(test)
283
394
        if self.count == 0:
284
395
            self.startTests()
 
396
        self.count += 1
285
397
        self.report_test_start(test)
286
398
        test.number = self.count
287
399
        self._recordTestStartTime()
 
400
        # Make testtools cases give us the real traceback on failure
 
401
        addOnException = getattr(test, "addOnException", None)
 
402
        if addOnException is not None:
 
403
            addOnException(self._record_traceback_from_test)
 
404
        # Only check for thread leaks on bzrlib derived test cases
 
405
        if isinstance(test, TestCase):
 
406
            test.addCleanup(self._check_leaked_threads, test)
 
407
 
 
408
    def stopTest(self, test):
 
409
        super(ExtendedTestResult, self).stopTest(test)
 
410
        # Manually break cycles, means touching various private things but hey
 
411
        getDetails = getattr(test, "getDetails", None)
 
412
        if getDetails is not None:
 
413
            getDetails().clear()
 
414
        _clear__type_equality_funcs(test)
 
415
        self._traceback_from_test = None
288
416
 
289
417
    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')
 
418
        self.report_tests_starting()
 
419
        self._active_threads = threading.enumerate()
 
420
 
 
421
    def _check_leaked_threads(self, test):
 
422
        """See if any threads have leaked since last call
 
423
 
 
424
        A sample of live threads is stored in the _active_threads attribute,
 
425
        when this method runs it compares the current live threads and any not
 
426
        in the previous sample are treated as having leaked.
 
427
        """
 
428
        now_active_threads = set(threading.enumerate())
 
429
        threads_leaked = now_active_threads.difference(self._active_threads)
 
430
        if threads_leaked:
 
431
            self._report_thread_leak(test, threads_leaked, now_active_threads)
 
432
            self._tests_leaking_threads_count += 1
 
433
            if self._first_thread_leaker_id is None:
 
434
                self._first_thread_leaker_id = test.id()
 
435
            self._active_threads = now_active_threads
307
436
 
308
437
    def _recordTestStartTime(self):
309
438
        """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()
 
439
        self._start_datetime = self._now()
318
440
 
319
441
    def addError(self, test, err):
320
442
        """Tell result that test finished with an error.
322
444
        Called from the TestCase run() method when the test
323
445
        fails with an unexpected error.
324
446
        """
325
 
        self._post_mortem()
326
 
        unittest.TestResult.addError(self, test, err)
 
447
        self._post_mortem(self._traceback_from_test)
 
448
        super(ExtendedTestResult, self).addError(test, err)
327
449
        self.error_count += 1
328
450
        self.report_error(test, err)
329
451
        if self.stop_early:
330
452
            self.stop()
331
 
        self._cleanupLogFile(test)
332
453
 
333
454
    def addFailure(self, test, err):
334
455
        """Tell result that test failed.
336
457
        Called from the TestCase run() method when the test
337
458
        fails because e.g. an assert() method failed.
338
459
        """
339
 
        self._post_mortem()
340
 
        unittest.TestResult.addFailure(self, test, err)
 
460
        self._post_mortem(self._traceback_from_test)
 
461
        super(ExtendedTestResult, self).addFailure(test, err)
341
462
        self.failure_count += 1
342
463
        self.report_failure(test, err)
343
464
        if self.stop_early:
344
465
            self.stop()
345
 
        self._cleanupLogFile(test)
346
466
 
347
467
    def addSuccess(self, test, details=None):
348
468
        """Tell result that test completed successfully.
356
476
                    self._formatTime(benchmark_time),
357
477
                    test.id()))
358
478
        self.report_success(test)
359
 
        self._cleanupLogFile(test)
360
 
        unittest.TestResult.addSuccess(self, test)
 
479
        super(ExtendedTestResult, self).addSuccess(test)
361
480
        test._log_contents = ''
362
481
 
363
482
    def addExpectedFailure(self, test, err):
364
483
        self.known_failure_count += 1
365
484
        self.report_known_failure(test, err)
366
485
 
 
486
    def addUnexpectedSuccess(self, test, details=None):
 
487
        """Tell result the test unexpectedly passed, counting as a failure
 
488
 
 
489
        When the minimum version of testtools required becomes 0.9.8 this
 
490
        can be updated to use the new handling there.
 
491
        """
 
492
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
493
        self.failure_count += 1
 
494
        self.report_unexpected_success(test,
 
495
            "".join(details["reason"].iter_text()))
 
496
        if self.stop_early:
 
497
            self.stop()
 
498
 
367
499
    def addNotSupported(self, test, feature):
368
500
        """The test will not be run because of a missing feature.
369
501
        """
386
518
        self.not_applicable_count += 1
387
519
        self.report_not_applicable(test, reason)
388
520
 
389
 
    def _post_mortem(self):
 
521
    def _count_stored_tests(self):
 
522
        """Count of tests instances kept alive due to not succeeding"""
 
523
        return self.error_count + self.failure_count + self.known_failure_count
 
524
 
 
525
    def _post_mortem(self, tb=None):
390
526
        """Start a PDB post mortem session."""
391
527
        if os.environ.get('BZR_TEST_PDB', None):
392
 
            import pdb;pdb.post_mortem()
 
528
            import pdb
 
529
            pdb.post_mortem(tb)
393
530
 
394
531
    def progress(self, offset, whence):
395
532
        """The test is adjusting the count of tests to run."""
400
537
        else:
401
538
            raise errors.BzrError("Unknown whence %r" % whence)
402
539
 
403
 
    def report_cleaning_up(self):
404
 
        pass
 
540
    def report_tests_starting(self):
 
541
        """Display information before the test run begins"""
 
542
        if getattr(sys, 'frozen', None) is None:
 
543
            bzr_path = osutils.realpath(sys.argv[0])
 
544
        else:
 
545
            bzr_path = sys.executable
 
546
        self.stream.write(
 
547
            'bzr selftest: %s\n' % (bzr_path,))
 
548
        self.stream.write(
 
549
            '   %s\n' % (
 
550
                    bzrlib.__path__[0],))
 
551
        self.stream.write(
 
552
            '   bzr-%s python-%s %s\n' % (
 
553
                    bzrlib.version_string,
 
554
                    bzrlib._format_version_tuple(sys.version_info),
 
555
                    platform.platform(aliased=1),
 
556
                    ))
 
557
        self.stream.write('\n')
 
558
 
 
559
    def report_test_start(self, test):
 
560
        """Display information on the test just about to be run"""
 
561
 
 
562
    def _report_thread_leak(self, test, leaked_threads, active_threads):
 
563
        """Display information on a test that leaked one or more threads"""
 
564
        # GZ 2010-09-09: A leak summary reported separately from the general
 
565
        #                thread debugging would be nice. Tests under subunit
 
566
        #                need something not using stream, perhaps adding a
 
567
        #                testtools details object would be fitting.
 
568
        if 'threads' in selftest_debug_flags:
 
569
            self.stream.write('%s is leaking, active is now %d\n' %
 
570
                (test.id(), len(active_threads)))
405
571
 
406
572
    def startTestRun(self):
407
573
        self.startTime = time.time()
444
610
        self.pb.finished()
445
611
        super(TextTestResult, self).stopTestRun()
446
612
 
447
 
    def startTestRun(self):
448
 
        super(TextTestResult, self).startTestRun()
 
613
    def report_tests_starting(self):
 
614
        super(TextTestResult, self).report_tests_starting()
449
615
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
450
616
 
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
617
    def _progress_prefix_text(self):
457
618
        # the longer this text, the less space we have to show the test
458
619
        # name...
480
641
        return a
481
642
 
482
643
    def report_test_start(self, test):
483
 
        self.count += 1
484
644
        self.pb.update(
485
645
                self._progress_prefix_text()
486
646
                + ' '
504
664
    def report_known_failure(self, test, err):
505
665
        pass
506
666
 
 
667
    def report_unexpected_success(self, test, reason):
 
668
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
 
669
            self._test_description(test),
 
670
            "Unexpected success. Should have failed",
 
671
            reason,
 
672
            ))
 
673
 
507
674
    def report_skip(self, test, reason):
508
675
        pass
509
676
 
513
680
    def report_unsupported(self, test, feature):
514
681
        """test cannot be run because feature is missing."""
515
682
 
516
 
    def report_cleaning_up(self):
517
 
        self.pb.update('Cleaning up')
518
 
 
519
683
 
520
684
class VerboseTestResult(ExtendedTestResult):
521
685
    """Produce long output, with one line per test run plus times"""
528
692
            result = a_string
529
693
        return result.ljust(final_width)
530
694
 
531
 
    def startTestRun(self):
532
 
        super(VerboseTestResult, self).startTestRun()
 
695
    def report_tests_starting(self):
533
696
        self.stream.write('running %d tests...\n' % self.num_tests)
 
697
        super(VerboseTestResult, self).report_tests_starting()
534
698
 
535
699
    def report_test_start(self, test):
536
 
        self.count += 1
537
700
        name = self._shortened_test_description(test)
538
701
        width = osutils.terminal_width()
539
702
        if width is not None:
551
714
        return '%s%s' % (indent, err[1])
552
715
 
553
716
    def report_error(self, test, err):
554
 
        self.stream.writeln('ERROR %s\n%s'
 
717
        self.stream.write('ERROR %s\n%s\n'
555
718
                % (self._testTimeString(test),
556
719
                   self._error_summary(err)))
557
720
 
558
721
    def report_failure(self, test, err):
559
 
        self.stream.writeln(' FAIL %s\n%s'
 
722
        self.stream.write(' FAIL %s\n%s\n'
560
723
                % (self._testTimeString(test),
561
724
                   self._error_summary(err)))
562
725
 
563
726
    def report_known_failure(self, test, err):
564
 
        self.stream.writeln('XFAIL %s\n%s'
 
727
        self.stream.write('XFAIL %s\n%s\n'
565
728
                % (self._testTimeString(test),
566
729
                   self._error_summary(err)))
567
730
 
 
731
    def report_unexpected_success(self, test, reason):
 
732
        self.stream.write(' FAIL %s\n%s: %s\n'
 
733
                % (self._testTimeString(test),
 
734
                   "Unexpected success. Should have failed",
 
735
                   reason))
 
736
 
568
737
    def report_success(self, test):
569
 
        self.stream.writeln('   OK %s' % self._testTimeString(test))
 
738
        self.stream.write('   OK %s\n' % self._testTimeString(test))
570
739
        for bench_called, stats in getattr(test, '_benchcalls', []):
571
 
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
740
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
572
741
            stats.pprint(file=self.stream)
573
742
        # flush the stream so that we get smooth output. This verbose mode is
574
743
        # used to show the output in PQM.
575
744
        self.stream.flush()
576
745
 
577
746
    def report_skip(self, test, reason):
578
 
        self.stream.writeln(' SKIP %s\n%s'
 
747
        self.stream.write(' SKIP %s\n%s\n'
579
748
                % (self._testTimeString(test), reason))
580
749
 
581
750
    def report_not_applicable(self, test, reason):
582
 
        self.stream.writeln('  N/A %s\n    %s'
 
751
        self.stream.write('  N/A %s\n    %s\n'
583
752
                % (self._testTimeString(test), reason))
584
753
 
585
754
    def report_unsupported(self, test, feature):
586
755
        """test cannot be run because feature is missing."""
587
 
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
 
756
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
588
757
                %(self._testTimeString(test), feature))
589
758
 
590
759
 
617
786
            encode = codec[0]
618
787
        else:
619
788
            encode = codec.encode
620
 
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream)
 
789
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
790
        #                so should swap to the plain codecs.StreamWriter
 
791
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
792
            "backslashreplace")
621
793
        stream.encoding = new_encoding
622
 
        self.stream = unittest._WritelnDecorator(stream)
 
794
        self.stream = stream
623
795
        self.descriptions = descriptions
624
796
        self.verbosity = verbosity
625
797
        self._bench_history = bench_history
749
921
    # XXX: Should probably unify more with CannedInputUIFactory or a
750
922
    # particular configuration of TextUIFactory, or otherwise have a clearer
751
923
    # idea of how they're supposed to be different.
752
 
    # See https://bugs.edge.launchpad.net/bzr/+bug/408213
 
924
    # See https://bugs.launchpad.net/bzr/+bug/408213
753
925
 
754
926
    def __init__(self, stdout=None, stderr=None, stdin=None):
755
927
        if stdin is not None:
773
945
        return NullProgressView()
774
946
 
775
947
 
 
948
def isolated_doctest_setUp(test):
 
949
    override_os_environ(test)
 
950
 
 
951
 
 
952
def isolated_doctest_tearDown(test):
 
953
    restore_os_environ(test)
 
954
 
 
955
 
 
956
def IsolatedDocTestSuite(*args, **kwargs):
 
957
    """Overrides doctest.DocTestSuite to handle isolation.
 
958
 
 
959
    The method is really a factory and users are expected to use it as such.
 
960
    """
 
961
 
 
962
    kwargs['setUp'] = isolated_doctest_setUp
 
963
    kwargs['tearDown'] = isolated_doctest_tearDown
 
964
    return doctest.DocTestSuite(*args, **kwargs)
 
965
 
 
966
 
776
967
class TestCase(testtools.TestCase):
777
968
    """Base class for bzr unit tests.
778
969
 
789
980
    routine, and to build and check bzr trees.
790
981
 
791
982
    In addition to the usual method of overriding tearDown(), this class also
792
 
    allows subclasses to register functions into the _cleanups list, which is
 
983
    allows subclasses to register cleanup functions via addCleanup, which are
793
984
    run in order as the object is torn down.  It's less likely this will be
794
985
    accidentally overlooked.
795
986
    """
796
987
 
797
 
    _active_threads = None
798
 
    _leaking_threads_tests = 0
799
 
    _first_thread_leaker_id = None
800
 
    _log_file_name = None
 
988
    _log_file = None
801
989
    # record lsprof data when performing benchmark calls.
802
990
    _gather_lsprof_in_benchmarks = False
803
991
 
804
992
    def __init__(self, methodName='testMethod'):
805
993
        super(TestCase, self).__init__(methodName)
806
 
        self._cleanups = []
807
994
        self._directory_isolation = True
808
995
        self.exception_handlers.insert(0,
809
996
            (UnavailableFeature, self._do_unsupported_or_skip))
812
999
 
813
1000
    def setUp(self):
814
1001
        super(TestCase, self).setUp()
 
1002
 
 
1003
        timeout = config.GlobalStack().get('selftest.timeout')
 
1004
        if timeout:
 
1005
            timeout_fixture = fixtures.TimeoutFixture(timeout)
 
1006
            timeout_fixture.setUp()
 
1007
            self.addCleanup(timeout_fixture.cleanUp)
 
1008
 
815
1009
        for feature in getattr(self, '_test_needs_features', []):
816
1010
            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
1011
        self._cleanEnvironment()
 
1012
 
 
1013
        if bzrlib.global_state is not None:
 
1014
            self.overrideAttr(bzrlib.global_state, 'cmdline_overrides',
 
1015
                              config.CommandLineStore())
 
1016
 
822
1017
        self._silenceUI()
823
1018
        self._startLogFile()
824
1019
        self._benchcalls = []
827
1022
        self._track_transports()
828
1023
        self._track_locks()
829
1024
        self._clear_debug_flags()
830
 
        TestCase._active_threads = threading.activeCount()
831
 
        self.addCleanup(self._check_leaked_threads)
 
1025
        # Isolate global verbosity level, to make sure it's reproducible
 
1026
        # between tests.  We should get rid of this altogether: bug 656694. --
 
1027
        # mbp 20101008
 
1028
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
 
1029
        # Isolate config option expansion until its default value for bzrlib is
 
1030
        # settled on or a the FIXME associated with _get_expand_default_value
 
1031
        # is addressed -- vila 20110219
 
1032
        self.overrideAttr(config, '_expand_default_value', None)
 
1033
        self._log_files = set()
 
1034
        # Each key in the ``_counters`` dict holds a value for a different
 
1035
        # counter. When the test ends, addDetail() should be used to output the
 
1036
        # counter values. This happens in install_counter_hook().
 
1037
        self._counters = {}
 
1038
        if 'config_stats' in selftest_debug_flags:
 
1039
            self._install_config_stats_hooks()
 
1040
        # Do not use i18n for tests (unless the test reverses this)
 
1041
        i18n.disable_i18n()
832
1042
 
833
1043
    def debug(self):
834
1044
        # debug a frame up.
835
1045
        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()
 
1046
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
1047
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
1048
                ).set_trace(sys._getframe().f_back)
 
1049
 
 
1050
    def discardDetail(self, name):
 
1051
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1052
 
 
1053
        eg. bzr always adds the 'log' detail at startup, but we don't want to
 
1054
        include it for skipped, xfail, etc tests.
 
1055
 
 
1056
        It is safe to call this for a detail that doesn't exist, in case this
 
1057
        gets called multiple times.
 
1058
        """
 
1059
        # We cheat. details is stored in __details which means we shouldn't
 
1060
        # touch it. but getDetails() returns the dict directly, so we can
 
1061
        # mutate it.
 
1062
        details = self.getDetails()
 
1063
        if name in details:
 
1064
            del details[name]
 
1065
 
 
1066
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1067
        """Install a counting hook.
 
1068
 
 
1069
        Any hook can be counted as long as it doesn't need to return a value.
 
1070
 
 
1071
        :param hooks: Where the hook should be installed.
 
1072
 
 
1073
        :param name: The hook name that will be counted.
 
1074
 
 
1075
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1076
            to ``name``.
 
1077
        """
 
1078
        _counters = self._counters # Avoid closing over self
 
1079
        if counter_name is None:
 
1080
            counter_name = name
 
1081
        if _counters.has_key(counter_name):
 
1082
            raise AssertionError('%s is already used as a counter name'
 
1083
                                  % (counter_name,))
 
1084
        _counters[counter_name] = 0
 
1085
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1086
            lambda: ['%d' % (_counters[counter_name],)]))
 
1087
        def increment_counter(*args, **kwargs):
 
1088
            _counters[counter_name] += 1
 
1089
        label = 'count %s calls' % (counter_name,)
 
1090
        hooks.install_named_hook(name, increment_counter, label)
 
1091
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1092
 
 
1093
    def _install_config_stats_hooks(self):
 
1094
        """Install config hooks to count hook calls.
 
1095
 
 
1096
        """
 
1097
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1098
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1099
                                       'config.%s' % (hook_name,))
 
1100
 
 
1101
        # The OldConfigHooks are private and need special handling to protect
 
1102
        # against recursive tests (tests that run other tests), so we just do
 
1103
        # manually what registering them into _builtin_known_hooks will provide
 
1104
        # us.
 
1105
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1106
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1107
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1108
                                      'old_config.%s' % (hook_name,))
852
1109
 
853
1110
    def _clear_debug_flags(self):
854
1111
        """Prevent externally set debug flags affecting tests.
865
1122
 
866
1123
    def _clear_hooks(self):
867
1124
        # prevent hooks affecting tests
 
1125
        known_hooks = hooks.known_hooks
868
1126
        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)
 
1127
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1128
            current_hooks = getattr(parent, name)
872
1129
            self._preserved_hooks[parent] = (name, current_hooks)
 
1130
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1131
        hooks._lazy_hooks = {}
873
1132
        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)
 
1133
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1134
            factory = known_hooks.get(key)
876
1135
            setattr(parent, name, factory())
877
1136
        # this hook should always be installed
878
1137
        request._install_hook()
907
1166
        # break some locks on purpose and should be taken into account by
908
1167
        # considering that breaking a lock is just a dirty way of releasing it.
909
1168
        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))
 
1169
            message = (
 
1170
                'Different number of acquired and '
 
1171
                'released or broken locks.\n'
 
1172
                'acquired=%s\n'
 
1173
                'released=%s\n'
 
1174
                'broken=%s\n' %
 
1175
                (acquired_locks, released_locks, broken_locks))
913
1176
            if not self._lock_check_thorough:
914
1177
                # Rather than fail, just warn
915
1178
                print "Broken test %s: %s" % (self, message)
943
1206
 
944
1207
    def permit_dir(self, name):
945
1208
        """Permit a directory to be used by this test. See permit_url."""
946
 
        name_transport = get_transport(name)
 
1209
        name_transport = _mod_transport.get_transport_from_path(name)
947
1210
        self.permit_url(name)
948
1211
        self.permit_url(name_transport.base)
949
1212
 
972
1235
            try:
973
1236
                workingtree.WorkingTree.open(path)
974
1237
            except (errors.NotBranchError, errors.NoWorkingTree):
975
 
                return
 
1238
                raise TestSkipped('Needs a working tree of bzr sources')
976
1239
        finally:
977
1240
            self.enable_directory_isolation()
978
1241
 
1028
1291
        self.addCleanup(transport_server.stop_server)
1029
1292
        # Obtain a real transport because if the server supplies a password, it
1030
1293
        # will be hidden from the base on the client side.
1031
 
        t = get_transport(transport_server.get_url())
 
1294
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1032
1295
        # Some transport servers effectively chroot the backing transport;
1033
1296
        # others like SFTPServer don't - users of the transport can walk up the
1034
1297
        # transport to read the entire backing transport. This wouldn't matter
1090
1353
        except UnicodeError, e:
1091
1354
            # If we can't compare without getting a UnicodeError, then
1092
1355
            # obviously they are different
1093
 
            mutter('UnicodeError: %s', e)
 
1356
            trace.mutter('UnicodeError: %s', e)
1094
1357
        if message:
1095
1358
            message += '\n'
1096
1359
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1097
1360
            % (message,
1098
 
               pformat(a), pformat(b)))
 
1361
               pprint.pformat(a), pprint.pformat(b)))
1099
1362
 
1100
1363
    assertEquals = assertEqual
1101
1364
 
1135
1398
                         'st_mtime did not match')
1136
1399
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1137
1400
                         'st_ctime did not match')
1138
 
        if sys.platform != 'win32':
 
1401
        if sys.platform == 'win32':
1139
1402
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1140
1403
            # 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
 
1404
            # odd. We just force it to always be 0 to avoid any problems.
 
1405
            self.assertEqual(0, expected.st_dev)
 
1406
            self.assertEqual(0, actual.st_dev)
 
1407
            self.assertEqual(0, expected.st_ino)
 
1408
            self.assertEqual(0, actual.st_ino)
 
1409
        else:
1143
1410
            self.assertEqual(expected.st_dev, actual.st_dev,
1144
1411
                             'st_dev did not match')
1145
1412
            self.assertEqual(expected.st_ino, actual.st_ino,
1154
1421
                length, len(obj_with_len), obj_with_len))
1155
1422
 
1156
1423
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1157
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1424
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1158
1425
        """
1159
 
        from bzrlib import trace
1160
1426
        captured = []
1161
1427
        orig_log_exception_quietly = trace.log_exception_quietly
1162
1428
        try:
1163
1429
            def capture():
1164
1430
                orig_log_exception_quietly()
1165
 
                captured.append(sys.exc_info())
 
1431
                captured.append(sys.exc_info()[1])
1166
1432
            trace.log_exception_quietly = capture
1167
1433
            func(*args, **kwargs)
1168
1434
        finally:
1169
1435
            trace.log_exception_quietly = orig_log_exception_quietly
1170
1436
        self.assertLength(1, captured)
1171
 
        err = captured[0][1]
 
1437
        err = captured[0]
1172
1438
        self.assertIsInstance(err, exception_class)
1173
1439
        return err
1174
1440
 
1211
1477
        if haystack.find(needle) == -1:
1212
1478
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1213
1479
 
 
1480
    def assertNotContainsString(self, haystack, needle):
 
1481
        if haystack.find(needle) != -1:
 
1482
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1483
 
1214
1484
    def assertSubset(self, sublist, superlist):
1215
1485
        """Assert that every entry in sublist is present in superlist."""
1216
1486
        missing = set(sublist) - set(superlist)
1305
1575
 
1306
1576
    def assertFileEqual(self, content, path):
1307
1577
        """Fail if path does not contain 'content'."""
1308
 
        self.failUnlessExists(path)
 
1578
        self.assertPathExists(path)
1309
1579
        f = file(path, 'rb')
1310
1580
        try:
1311
1581
            s = f.read()
1321
1591
        else:
1322
1592
            self.assertEqual(expected_docstring, obj.__doc__)
1323
1593
 
 
1594
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1324
1595
    def failUnlessExists(self, path):
 
1596
        return self.assertPathExists(path)
 
1597
 
 
1598
    def assertPathExists(self, path):
1325
1599
        """Fail unless path or paths, which may be abs or relative, exist."""
1326
1600
        if not isinstance(path, basestring):
1327
1601
            for p in path:
1328
 
                self.failUnlessExists(p)
 
1602
                self.assertPathExists(p)
1329
1603
        else:
1330
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1604
            self.assertTrue(osutils.lexists(path),
 
1605
                path + " does not exist")
1331
1606
 
 
1607
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1332
1608
    def failIfExists(self, path):
 
1609
        return self.assertPathDoesNotExist(path)
 
1610
 
 
1611
    def assertPathDoesNotExist(self, path):
1333
1612
        """Fail if path or paths, which may be abs or relative, exist."""
1334
1613
        if not isinstance(path, basestring):
1335
1614
            for p in path:
1336
 
                self.failIfExists(p)
 
1615
                self.assertPathDoesNotExist(p)
1337
1616
        else:
1338
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1617
            self.assertFalse(osutils.lexists(path),
 
1618
                path + " exists")
1339
1619
 
1340
1620
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1341
1621
        """A helper for callDeprecated and applyDeprecated.
1367
1647
        not other callers that go direct to the warning module.
1368
1648
 
1369
1649
        To test that a deprecated method raises an error, do something like
1370
 
        this::
 
1650
        this (remember that both assertRaises and applyDeprecated delays *args
 
1651
        and **kwargs passing)::
1371
1652
 
1372
1653
            self.assertRaises(errors.ReservedId,
1373
1654
                self.applyDeprecated,
1451
1732
        return result
1452
1733
 
1453
1734
    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
 
1735
        """Setup a in-memory target for bzr and testcase log messages"""
 
1736
        pseudo_log_file = StringIO()
 
1737
        def _get_log_contents_for_weird_testtools_api():
 
1738
            return [pseudo_log_file.getvalue().decode(
 
1739
                "utf-8", "replace").encode("utf-8")]
 
1740
        self.addDetail("log", content.Content(content.ContentType("text",
 
1741
            "plain", {"charset": "utf8"}),
 
1742
            _get_log_contents_for_weird_testtools_api))
 
1743
        self._log_file = pseudo_log_file
 
1744
        self._log_memento = trace.push_log_file(self._log_file)
1462
1745
        self.addCleanup(self._finishLogFile)
1463
1746
 
1464
1747
    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:
 
1748
        """Flush and dereference the in-memory log for this testcase"""
 
1749
        if trace._trace_file:
1470
1750
            # 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)
 
1751
            trace._trace_file.flush()
 
1752
        trace.pop_log_file(self._log_memento)
 
1753
        # The logging module now tracks references for cleanup so discard ours
 
1754
        del self._log_memento
1475
1755
 
1476
1756
    def thisFailsStrictLockCheck(self):
1477
1757
        """It is known that this test would fail with -Dstrict_locks.
1486
1766
        """
1487
1767
        debug.debug_flags.discard('strict_locks')
1488
1768
 
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
1769
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1498
1770
        """Overrides an object attribute restoring it after the test.
1499
1771
 
 
1772
        :note: This should be used with discretion; you should think about
 
1773
        whether it's better to make the code testable without monkey-patching.
 
1774
 
1500
1775
        :param obj: The object that will be mutated.
1501
1776
 
1502
1777
        :param attr_name: The attribute name we want to preserve/override in
1513
1788
            setattr(obj, attr_name, new)
1514
1789
        return value
1515
1790
 
 
1791
    def overrideEnv(self, name, new):
 
1792
        """Set an environment variable, and reset it after the test.
 
1793
 
 
1794
        :param name: The environment variable name.
 
1795
 
 
1796
        :param new: The value to set the variable to. If None, the 
 
1797
            variable is deleted from the environment.
 
1798
 
 
1799
        :returns: The actual variable value.
 
1800
        """
 
1801
        value = osutils.set_or_unset_env(name, new)
 
1802
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1803
        return value
 
1804
 
 
1805
    def recordCalls(self, obj, attr_name):
 
1806
        """Monkeypatch in a wrapper that will record calls.
 
1807
 
 
1808
        The monkeypatch is automatically removed when the test concludes.
 
1809
 
 
1810
        :param obj: The namespace holding the reference to be replaced;
 
1811
            typically a module, class, or object.
 
1812
        :param attr_name: A string for the name of the attribute to 
 
1813
            patch.
 
1814
        :returns: A list that will be extended with one item every time the
 
1815
            function is called, with a tuple of (args, kwargs).
 
1816
        """
 
1817
        calls = []
 
1818
 
 
1819
        def decorator(*args, **kwargs):
 
1820
            calls.append((args, kwargs))
 
1821
            return orig(*args, **kwargs)
 
1822
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1823
        return calls
 
1824
 
1516
1825
    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)
 
1826
        for name, value in isolated_environ.iteritems():
 
1827
            self.overrideEnv(name, value)
1577
1828
 
1578
1829
    def _restoreHooks(self):
1579
1830
        for klass, (name, hooks) in self._preserved_hooks.items():
1580
1831
            setattr(klass, name, hooks)
 
1832
        self._preserved_hooks.clear()
 
1833
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1834
        self._preserved_lazy_hooks.clear()
1581
1835
 
1582
1836
    def knownFailure(self, reason):
1583
 
        """This test has failed for some known reason."""
1584
 
        raise KnownFailure(reason)
 
1837
        """Declare that this test fails for a known reason
 
1838
 
 
1839
        Tests that are known to fail should generally be using expectedFailure
 
1840
        with an appropriate reverse assertion if a change could cause the test
 
1841
        to start passing. Conversely if the test has no immediate prospect of
 
1842
        succeeding then using skip is more suitable.
 
1843
 
 
1844
        When this method is called while an exception is being handled, that
 
1845
        traceback will be used, otherwise a new exception will be thrown to
 
1846
        provide one but won't be reported.
 
1847
        """
 
1848
        self._add_reason(reason)
 
1849
        try:
 
1850
            exc_info = sys.exc_info()
 
1851
            if exc_info != (None, None, None):
 
1852
                self._report_traceback(exc_info)
 
1853
            else:
 
1854
                try:
 
1855
                    raise self.failureException(reason)
 
1856
                except self.failureException:
 
1857
                    exc_info = sys.exc_info()
 
1858
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1859
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1860
        finally:
 
1861
            del exc_info
 
1862
 
 
1863
    def _suppress_log(self):
 
1864
        """Remove the log info from details."""
 
1865
        self.discardDetail('log')
1585
1866
 
1586
1867
    def _do_skip(self, result, reason):
 
1868
        self._suppress_log()
1587
1869
        addSkip = getattr(result, 'addSkip', None)
1588
1870
        if not callable(addSkip):
1589
1871
            result.addSuccess(result)
1592
1874
 
1593
1875
    @staticmethod
1594
1876
    def _do_known_failure(self, result, e):
 
1877
        self._suppress_log()
1595
1878
        err = sys.exc_info()
1596
1879
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1597
1880
        if addExpectedFailure is not None:
1605
1888
            reason = 'No reason given'
1606
1889
        else:
1607
1890
            reason = e.args[0]
 
1891
        self._suppress_log ()
1608
1892
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1609
1893
        if addNotApplicable is not None:
1610
1894
            result.addNotApplicable(self, reason)
1612
1896
            self._do_skip(result, reason)
1613
1897
 
1614
1898
    @staticmethod
 
1899
    def _report_skip(self, result, err):
 
1900
        """Override the default _report_skip.
 
1901
 
 
1902
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1903
        already been formatted into the 'reason' string, and we can't pull it
 
1904
        out again.
 
1905
        """
 
1906
        self._suppress_log()
 
1907
        super(TestCase, self)._report_skip(self, result, err)
 
1908
 
 
1909
    @staticmethod
 
1910
    def _report_expected_failure(self, result, err):
 
1911
        """Strip the log.
 
1912
 
 
1913
        See _report_skip for motivation.
 
1914
        """
 
1915
        self._suppress_log()
 
1916
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1917
 
 
1918
    @staticmethod
1615
1919
    def _do_unsupported_or_skip(self, result, e):
1616
1920
        reason = e.args[0]
 
1921
        self._suppress_log()
1617
1922
        addNotSupported = getattr(result, 'addNotSupported', None)
1618
1923
        if addNotSupported is not None:
1619
1924
            result.addNotSupported(self, reason)
1645
1950
            self._benchtime += time.time() - start
1646
1951
 
1647
1952
    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."
 
1953
        trace.mutter(*args)
1728
1954
 
1729
1955
    def get_log(self):
1730
1956
        """Get a unicode string containing the log from bzrlib.trace.
1766
1992
 
1767
1993
        self.log('run bzr: %r', args)
1768
1994
        # FIXME: don't call into logging here
1769
 
        handler = logging.StreamHandler(stderr)
1770
 
        handler.setLevel(logging.INFO)
 
1995
        handler = trace.EncodedStreamHandler(stderr, errors="replace",
 
1996
            level=logging.INFO)
1771
1997
        logger = logging.getLogger('')
1772
1998
        logger.addHandler(handler)
1773
1999
        old_ui_factory = ui.ui_factory
1780
2006
 
1781
2007
        try:
1782
2008
            try:
1783
 
                result = self.apply_redirected(ui.ui_factory.stdin,
 
2009
                result = self.apply_redirected(
 
2010
                    ui.ui_factory.stdin,
1784
2011
                    stdout, stderr,
1785
 
                    bzrlib.commands.run_bzr_catch_user_errors,
 
2012
                    _mod_commands.run_bzr_catch_user_errors,
1786
2013
                    args)
1787
2014
            except KeyboardInterrupt:
1788
2015
                # Reraise KeyboardInterrupt with contents of redirected stdout
1930
2157
    def start_bzr_subprocess(self, process_args, env_changes=None,
1931
2158
                             skip_if_plan_to_signal=False,
1932
2159
                             working_dir=None,
1933
 
                             allow_plugins=False):
 
2160
                             allow_plugins=False, stderr=subprocess.PIPE):
1934
2161
        """Start bzr in a subprocess for testing.
1935
2162
 
1936
2163
        This starts a new Python interpreter and runs bzr in there.
1945
2172
            variables. A value of None will unset the env variable.
1946
2173
            The values must be strings. The change will only occur in the
1947
2174
            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.
 
2175
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2176
            doesn't support signalling subprocesses.
1950
2177
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
2178
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2179
            are those valid for the stderr argument of `subprocess.Popen`.
 
2180
            Default value is ``subprocess.PIPE``.
1951
2181
 
1952
2182
        :returns: Popen object for the started process.
1953
2183
        """
1954
2184
        if skip_if_plan_to_signal:
1955
 
            if not getattr(os, 'kill', None):
1956
 
                raise TestSkipped("os.kill not available.")
 
2185
            if os.name != "posix":
 
2186
                raise TestSkipped("Sending signals not supported")
1957
2187
 
1958
2188
        if env_changes is None:
1959
2189
            env_changes = {}
 
2190
        # Because $HOME is set to a tempdir for the context of a test, modules
 
2191
        # installed in the user dir will not be found unless $PYTHONUSERBASE
 
2192
        # gets set to the computed directory of this parent process.
 
2193
        if site.USER_BASE is not None:
 
2194
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
1960
2195
        old_env = {}
1961
2196
 
1962
2197
        def cleanup_environment():
1979
2214
            # so we will avoid using it on all platforms, just to
1980
2215
            # make sure the code path is used, and we don't break on win32
1981
2216
            cleanup_environment()
 
2217
            # Include the subprocess's log file in the test details, in case
 
2218
            # the test fails due to an error in the subprocess.
 
2219
            self._add_subprocess_log(trace._get_bzr_log_filename())
1982
2220
            command = [sys.executable]
1983
2221
            # frozen executables don't need the path to bzr
1984
2222
            if getattr(sys, "frozen", None) is None:
1986
2224
            if not allow_plugins:
1987
2225
                command.append('--no-plugins')
1988
2226
            command.extend(process_args)
1989
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
2227
            process = self._popen(command, stdin=subprocess.PIPE,
 
2228
                                  stdout=subprocess.PIPE,
 
2229
                                  stderr=stderr)
1990
2230
        finally:
1991
2231
            restore_environment()
1992
2232
            if cwd is not None:
1994
2234
 
1995
2235
        return process
1996
2236
 
 
2237
    def _add_subprocess_log(self, log_file_path):
 
2238
        if len(self._log_files) == 0:
 
2239
            # Register an addCleanup func.  We do this on the first call to
 
2240
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2241
            # addCleanup is registered after any cleanups for tempdirs that
 
2242
            # subclasses might create, which will probably remove the log file
 
2243
            # we want to read.
 
2244
            self.addCleanup(self._subprocess_log_cleanup)
 
2245
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2246
        # twice.
 
2247
        self._log_files.add(log_file_path)
 
2248
 
 
2249
    def _subprocess_log_cleanup(self):
 
2250
        for count, log_file_path in enumerate(self._log_files):
 
2251
            # We use buffer_now=True to avoid holding the file open beyond
 
2252
            # the life of this function, which might interfere with e.g.
 
2253
            # cleaning tempdirs on Windows.
 
2254
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2255
            #detail_content = content.content_from_file(
 
2256
            #    log_file_path, buffer_now=True)
 
2257
            with open(log_file_path, 'rb') as log_file:
 
2258
                log_file_bytes = log_file.read()
 
2259
            detail_content = content.Content(content.ContentType("text",
 
2260
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2261
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2262
                detail_content)
 
2263
 
1997
2264
    def _popen(self, *args, **kwargs):
1998
2265
        """Place a call to Popen.
1999
2266
 
2000
2267
        Allows tests to override this method to intercept the calls made to
2001
2268
        Popen for introspection.
2002
2269
        """
2003
 
        return Popen(*args, **kwargs)
 
2270
        return subprocess.Popen(*args, **kwargs)
2004
2271
 
2005
2272
    def get_source_path(self):
2006
2273
        """Return the path of the directory containing bzrlib."""
2008
2275
 
2009
2276
    def get_bzr_path(self):
2010
2277
        """Return the path of the 'bzr' executable for this test suite."""
2011
 
        bzr_path = self.get_source_path()+'/bzr'
 
2278
        bzr_path = os.path.join(self.get_source_path(), "bzr")
2012
2279
        if not os.path.isfile(bzr_path):
2013
2280
            # We are probably installed. Assume sys.argv is the right file
2014
2281
            bzr_path = sys.argv[0]
2036
2303
        if retcode is not None and retcode != process.returncode:
2037
2304
            if process_args is None:
2038
2305
                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)
 
2306
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
 
2307
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
2041
2308
            self.fail('Command bzr %s failed with retcode %s != %s'
2042
2309
                      % (process_args, retcode, process.returncode))
2043
2310
        return [out, err]
2044
2311
 
2045
 
    def check_inventory_shape(self, inv, shape):
2046
 
        """Compare an inventory to a list of expected names.
 
2312
    def check_tree_shape(self, tree, shape):
 
2313
        """Compare a tree to a list of expected names.
2047
2314
 
2048
2315
        Fail if they are not precisely equal.
2049
2316
        """
2050
2317
        extras = []
2051
2318
        shape = list(shape)             # copy
2052
 
        for path, ie in inv.entries():
 
2319
        for path, ie in tree.iter_entries_by_dir():
2053
2320
            name = path.replace('\\', '/')
2054
2321
            if ie.kind == 'directory':
2055
2322
                name = name + '/'
2056
 
            if name in shape:
 
2323
            if name == "/":
 
2324
                pass # ignore root entry
 
2325
            elif name in shape:
2057
2326
                shape.remove(name)
2058
2327
            else:
2059
2328
                extras.append(name)
2100
2369
 
2101
2370
        Tests that expect to provoke LockContention errors should call this.
2102
2371
        """
2103
 
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2372
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2104
2373
 
2105
2374
    def make_utf8_encoded_stringio(self, encoding_type=None):
2106
2375
        """Return a StringIOWrapper instance, that will encode Unicode
2119
2388
        from bzrlib.smart import request
2120
2389
        request_handlers = request.request_handlers
2121
2390
        orig_method = request_handlers.get(verb)
 
2391
        orig_info = request_handlers.get_info(verb)
2122
2392
        request_handlers.remove(verb)
2123
 
        self.addCleanup(request_handlers.register, verb, orig_method)
 
2393
        self.addCleanup(request_handlers.register, verb, orig_method,
 
2394
            info=orig_info)
2124
2395
 
2125
2396
 
2126
2397
class CapturedCall(object):
2149
2420
class TestCaseWithMemoryTransport(TestCase):
2150
2421
    """Common test class for tests that do not need disk resources.
2151
2422
 
2152
 
    Tests that need disk resources should derive from TestCaseWithTransport.
 
2423
    Tests that need disk resources should derive from TestCaseInTempDir
 
2424
    orTestCaseWithTransport.
2153
2425
 
2154
2426
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2155
2427
 
2156
 
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
2428
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2157
2429
    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
 
2430
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2431
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2432
    defaults for the transport in tests, nor does it obey the command line
2161
2433
    override, so tests that accidentally write to the common directory should
2162
2434
    be rare.
2163
2435
 
2164
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
2165
 
    a .bzr directory that stops us ascending higher into the filesystem.
 
2436
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2437
        ``.bzr`` directory that stops us ascending higher into the filesystem.
2166
2438
    """
2167
2439
 
2168
2440
    TEST_ROOT = None
2186
2458
 
2187
2459
        :param relpath: a path relative to the base url.
2188
2460
        """
2189
 
        t = get_transport(self.get_url(relpath))
 
2461
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2190
2462
        self.assertFalse(t.is_readonly())
2191
2463
        return t
2192
2464
 
2198
2470
 
2199
2471
        :param relpath: a path relative to the base url.
2200
2472
        """
2201
 
        t = get_transport(self.get_readonly_url(relpath))
 
2473
        t = _mod_transport.get_transport_from_url(
 
2474
            self.get_readonly_url(relpath))
2202
2475
        self.assertTrue(t.is_readonly())
2203
2476
        return t
2204
2477
 
2325
2598
        real branch.
2326
2599
        """
2327
2600
        root = TestCaseWithMemoryTransport.TEST_ROOT
2328
 
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2601
        # Make sure we get a readable and accessible home for .bzr.log
 
2602
        # and/or config files, and not fallback to weird defaults (see
 
2603
        # http://pad.lv/825027).
 
2604
        self.assertIs(None, os.environ.get('BZR_HOME', None))
 
2605
        os.environ['BZR_HOME'] = root
 
2606
        wt = bzrdir.BzrDir.create_standalone_workingtree(root)
 
2607
        del os.environ['BZR_HOME']
 
2608
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2609
        # we don't need to re-open the wt to check it hasn't changed.
 
2610
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2611
            wt.control_transport.get_bytes('dirstate'))
2329
2612
 
2330
2613
    def _check_safety_net(self):
2331
2614
        """Check that the safety .bzr directory have not been touched.
2334
2617
        propagating. This method ensures than a test did not leaked.
2335
2618
        """
2336
2619
        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:':
 
2620
        t = _mod_transport.get_transport_from_path(root)
 
2621
        self.permit_url(t.base)
 
2622
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2623
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2341
2624
            # The current test have modified the /bzr directory, we need to
2342
2625
            # recreate a new one or all the followng tests will fail.
2343
2626
            # If you need to inspect its content uncomment the following line
2378
2661
    def make_branch(self, relpath, format=None):
2379
2662
        """Create a branch on the transport at relpath."""
2380
2663
        repo = self.make_repository(relpath, format=format)
2381
 
        return repo.bzrdir.create_branch()
 
2664
        return repo.bzrdir.create_branch(append_revisions_only=False)
 
2665
 
 
2666
    def get_default_format(self):
 
2667
        return 'default'
 
2668
 
 
2669
    def resolve_format(self, format):
 
2670
        """Resolve an object to a ControlDir format object.
 
2671
 
 
2672
        The initial format object can either already be
 
2673
        a ControlDirFormat, None (for the default format),
 
2674
        or a string with the name of the control dir format.
 
2675
 
 
2676
        :param format: Object to resolve
 
2677
        :return A ControlDirFormat instance
 
2678
        """
 
2679
        if format is None:
 
2680
            format = self.get_default_format()
 
2681
        if isinstance(format, basestring):
 
2682
            format = bzrdir.format_registry.make_bzrdir(format)
 
2683
        return format
2382
2684
 
2383
2685
    def make_bzrdir(self, relpath, format=None):
2384
2686
        try:
2385
2687
            # might be a relative or absolute path
2386
2688
            maybe_a_url = self.get_url(relpath)
2387
2689
            segments = maybe_a_url.rsplit('/', 1)
2388
 
            t = get_transport(maybe_a_url)
 
2690
            t = _mod_transport.get_transport(maybe_a_url)
2389
2691
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2390
2692
                t.ensure_base()
2391
 
            if format is None:
2392
 
                format = 'default'
2393
 
            if isinstance(format, basestring):
2394
 
                format = bzrdir.format_registry.make_bzrdir(format)
 
2693
            format = self.resolve_format(format)
2395
2694
            return format.initialize_on_transport(t)
2396
2695
        except errors.UninitializableFormat:
2397
2696
            raise TestSkipped("Format %s is not initializable." % format)
2398
2697
 
2399
 
    def make_repository(self, relpath, shared=False, format=None):
 
2698
    def make_repository(self, relpath, shared=None, format=None):
2400
2699
        """Create a repository on our default transport at relpath.
2401
2700
 
2402
2701
        Note that relpath must be a relative path, not a full url.
2408
2707
        made_control = self.make_bzrdir(relpath, format=format)
2409
2708
        return made_control.create_repository(shared=shared)
2410
2709
 
2411
 
    def make_smart_server(self, path):
 
2710
    def make_smart_server(self, path, backing_server=None):
 
2711
        if backing_server is None:
 
2712
            backing_server = self.get_server()
2412
2713
        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)
 
2714
        self.start_server(smart_server, backing_server)
 
2715
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
 
2716
                                                   ).clone(path)
2415
2717
        return remote_transport
2416
2718
 
2417
2719
    def make_branch_and_memory_tree(self, relpath, format=None):
2427
2729
        test_home_dir = self.test_home_dir
2428
2730
        if isinstance(test_home_dir, unicode):
2429
2731
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2430
 
        os.environ['HOME'] = test_home_dir
2431
 
        os.environ['BZR_HOME'] = test_home_dir
 
2732
        self.overrideEnv('HOME', test_home_dir)
 
2733
        self.overrideEnv('BZR_HOME', test_home_dir)
2432
2734
 
2433
2735
    def setUp(self):
2434
2736
        super(TestCaseWithMemoryTransport, self).setUp()
 
2737
 
 
2738
        def _add_disconnect_cleanup(transport):
 
2739
            """Schedule disconnection of given transport at test cleanup
 
2740
 
 
2741
            This needs to happen for all connected transports or leaks occur.
 
2742
 
 
2743
            Note reconnections may mean we call disconnect multiple times per
 
2744
            transport which is suboptimal but seems harmless.
 
2745
            """
 
2746
            self.addCleanup(transport.disconnect)
 
2747
 
 
2748
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
 
2749
            _add_disconnect_cleanup, None)
 
2750
 
2435
2751
        self._make_test_root()
2436
2752
        self.addCleanup(os.chdir, os.getcwdu())
2437
2753
        self.makeAndChdirToTestDir()
2443
2759
    def setup_smart_server_with_call_log(self):
2444
2760
        """Sets up a smart server as the transport server with a call log."""
2445
2761
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2762
        self.hpss_connections = []
2446
2763
        self.hpss_calls = []
2447
2764
        import traceback
2448
2765
        # Skip the current stack down to the caller of
2451
2768
        def capture_hpss_call(params):
2452
2769
            self.hpss_calls.append(
2453
2770
                CapturedCall(params, prefix_length))
 
2771
        def capture_connect(transport):
 
2772
            self.hpss_connections.append(transport)
2454
2773
        client._SmartClient.hooks.install_named_hook(
2455
2774
            'call', capture_hpss_call, None)
 
2775
        _mod_transport.Transport.hooks.install_named_hook(
 
2776
            'post_connect', capture_connect, None)
2456
2777
 
2457
2778
    def reset_smart_call_log(self):
2458
2779
        self.hpss_calls = []
 
2780
        self.hpss_connections = []
2459
2781
 
2460
2782
 
2461
2783
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2480
2802
 
2481
2803
    OVERRIDE_PYTHON = 'python'
2482
2804
 
 
2805
    def setUp(self):
 
2806
        super(TestCaseInTempDir, self).setUp()
 
2807
        # Remove the protection set in isolated_environ, we have a proper
 
2808
        # access to disk resources now.
 
2809
        self.overrideEnv('BZR_LOG', None)
 
2810
 
2483
2811
    def check_file_contents(self, filename, expect):
2484
2812
        self.log("check contents of file %s" % filename)
2485
 
        contents = file(filename, 'r').read()
 
2813
        f = file(filename)
 
2814
        try:
 
2815
            contents = f.read()
 
2816
        finally:
 
2817
            f.close()
2486
2818
        if contents != expect:
2487
2819
            self.log("expected: %r" % expect)
2488
2820
            self.log("actually: %r" % contents)
2562
2894
                "a list or a tuple. Got %r instead" % (shape,))
2563
2895
        # It's OK to just create them using forward slashes on windows.
2564
2896
        if transport is None or transport.is_readonly():
2565
 
            transport = get_transport(".")
 
2897
            transport = _mod_transport.get_transport_from_path(".")
2566
2898
        for name in shape:
2567
2899
            self.assertIsInstance(name, basestring)
2568
2900
            if name[-1] == '/':
2578
2910
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2579
2911
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2580
2912
 
2581
 
    def build_tree_contents(self, shape):
2582
 
        build_tree_contents(shape)
 
2913
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2583
2914
 
2584
2915
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2585
2916
        """Assert whether path or paths are in the WorkingTree"""
2654
2985
        # this obviously requires a format that supports branch references
2655
2986
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2656
2987
        # RBC 20060208
 
2988
        format = self.resolve_format(format=format)
 
2989
        if not format.supports_workingtrees:
 
2990
            b = self.make_branch(relpath+'.branch', format=format)
 
2991
            return b.create_checkout(relpath, lightweight=True)
2657
2992
        b = self.make_branch(relpath, format=format)
2658
2993
        try:
2659
2994
            return b.bzrdir.create_workingtree()
2726
3061
    """
2727
3062
 
2728
3063
    def setUp(self):
 
3064
        from bzrlib.tests import http_server
2729
3065
        super(ChrootedTestCase, self).setUp()
2730
3066
        if not self.vfs_transport_factory == memory.MemoryServer:
2731
 
            self.transport_readonly_server = HttpServer
 
3067
            self.transport_readonly_server = http_server.HttpServer
2732
3068
 
2733
3069
 
2734
3070
def condition_id_re(pattern):
2737
3073
    :param pattern: A regular expression string.
2738
3074
    :return: A callable that returns True if the re matches.
2739
3075
    """
2740
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2741
 
        'test filter')
 
3076
    filter_re = re.compile(pattern, 0)
2742
3077
    def condition(test):
2743
3078
        test_id = test.id()
2744
3079
        return filter_re.search(test_id)
2958
3293
                            result_decorators=result_decorators,
2959
3294
                            )
2960
3295
    runner.stop_on_failure=stop_on_failure
 
3296
    if isinstance(suite, unittest.TestSuite):
 
3297
        # Empty out _tests list of passed suite and populate new TestSuite
 
3298
        suite._tests[:], suite = [], TestSuite(suite)
2961
3299
    # built in decorator factories:
2962
3300
    decorators = [
2963
3301
        random_order(random_seed, runner),
2996
3334
 
2997
3335
 
2998
3336
def fork_decorator(suite):
 
3337
    if getattr(os, "fork", None) is None:
 
3338
        raise errors.BzrCommandError("platform does not support fork,"
 
3339
            " try --parallel=subprocess instead.")
2999
3340
    concurrency = osutils.local_concurrency()
3000
3341
    if concurrency == 1:
3001
3342
        return suite
3056
3397
    return suite
3057
3398
 
3058
3399
 
3059
 
class TestDecorator(TestSuite):
 
3400
class TestDecorator(TestUtil.TestSuite):
3060
3401
    """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().
 
3402
 
 
3403
    Contains rather than flattening suite passed on construction
3065
3404
    """
3066
3405
 
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
 
3406
    def __init__(self, suite=None):
 
3407
        super(TestDecorator, self).__init__()
 
3408
        if suite is not None:
 
3409
            self.addTest(suite)
 
3410
 
 
3411
    # Don't need subclass run method with suite emptying
 
3412
    run = unittest.TestSuite.run
3089
3413
 
3090
3414
 
3091
3415
class CountingDecorator(TestDecorator):
3102
3426
    """A decorator which excludes test matching an exclude pattern."""
3103
3427
 
3104
3428
    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)
 
3429
        super(ExcludeDecorator, self).__init__(
 
3430
            exclude_tests_by_re(suite, exclude_pattern))
3117
3431
 
3118
3432
 
3119
3433
class FilterTestsDecorator(TestDecorator):
3120
3434
    """A decorator which filters tests to those matching a pattern."""
3121
3435
 
3122
3436
    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)
 
3437
        super(FilterTestsDecorator, self).__init__(
 
3438
            filter_suite_by_re(suite, pattern))
3135
3439
 
3136
3440
 
3137
3441
class RandomDecorator(TestDecorator):
3138
3442
    """A decorator which randomises the order of its tests."""
3139
3443
 
3140
3444
    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()))
 
3445
        random_seed = self.actual_seed(random_seed)
 
3446
        stream.write("Randomizing test order using seed %s\n\n" %
 
3447
            (random_seed,))
3152
3448
        # 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)
 
3449
        random.seed(random_seed)
 
3450
        super(RandomDecorator, self).__init__(randomize_suite(suite))
3158
3451
 
3159
 
    def actual_seed(self):
3160
 
        if self.random_seed == "now":
 
3452
    @staticmethod
 
3453
    def actual_seed(seed):
 
3454
        if seed == "now":
3161
3455
            # We convert the seed to a long to make it reuseable across
3162
3456
            # invocations (because the user can reenter it).
3163
 
            self.random_seed = long(time.time())
 
3457
            return long(time.time())
3164
3458
        else:
3165
3459
            # Convert the seed to a long if we can
3166
3460
            try:
3167
 
                self.random_seed = long(self.random_seed)
3168
 
            except:
 
3461
                return long(seed)
 
3462
            except (TypeError, ValueError):
3169
3463
                pass
3170
 
        return self.random_seed
 
3464
        return seed
3171
3465
 
3172
3466
 
3173
3467
class TestFirstDecorator(TestDecorator):
3174
3468
    """A decorator which moves named tests to the front."""
3175
3469
 
3176
3470
    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)
 
3471
        super(TestFirstDecorator, self).__init__()
 
3472
        self.addTests(split_suite_by_re(suite, pattern))
3189
3473
 
3190
3474
 
3191
3475
def partition_tests(suite, count):
3192
3476
    """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
 
3477
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3478
    # splits up blocks of related tests that might run faster if they shared
 
3479
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3480
    # just one partition.  So the slowest partition shouldn't be much slower
 
3481
    # than the fastest.
 
3482
    partitions = [list() for i in range(count)]
 
3483
    tests = iter_suite_tests(suite)
 
3484
    for partition, test in itertools.izip(itertools.cycle(partitions), tests):
 
3485
        partition.append(test)
 
3486
    return partitions
3202
3487
 
3203
3488
 
3204
3489
def workaround_zealous_crypto_random():
3222
3507
    """
3223
3508
    concurrency = osutils.local_concurrency()
3224
3509
    result = []
3225
 
    from subunit import TestProtocolClient, ProtocolTestCase
 
3510
    from subunit import ProtocolTestCase
3226
3511
    from subunit.test_results import AutoTimingTestResultDecorator
3227
3512
    class TestInOtherProcess(ProtocolTestCase):
3228
3513
        # Should be in subunit, I think. RBC.
3234
3519
            try:
3235
3520
                ProtocolTestCase.run(self, result)
3236
3521
            finally:
3237
 
                os.waitpid(self.pid, 0)
 
3522
                pid, status = os.waitpid(self.pid, 0)
 
3523
            # GZ 2011-10-18: If status is nonzero, should report to the result
 
3524
            #                that something went wrong.
3238
3525
 
3239
3526
    test_blocks = partition_tests(suite, concurrency)
 
3527
    # Clear the tests from the original suite so it doesn't keep them alive
 
3528
    suite._tests[:] = []
3240
3529
    for process_tests in test_blocks:
3241
 
        process_suite = TestSuite()
3242
 
        process_suite.addTests(process_tests)
 
3530
        process_suite = TestUtil.TestSuite(process_tests)
 
3531
        # Also clear each split list so new suite has only reference
 
3532
        process_tests[:] = []
3243
3533
        c2pread, c2pwrite = os.pipe()
3244
3534
        pid = os.fork()
3245
3535
        if pid == 0:
3246
 
            workaround_zealous_crypto_random()
3247
3536
            try:
 
3537
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3538
                workaround_zealous_crypto_random()
3248
3539
                os.close(c2pread)
3249
3540
                # Leave stderr and stdout open so we can see test noise
3250
3541
                # Close stdin so that the child goes away if it decides to
3251
3542
                # read from stdin (otherwise its a roulette to see what
3252
3543
                # child actually gets keystrokes for pdb etc).
3253
3544
                sys.stdin.close()
3254
 
                sys.stdin = None
3255
 
                stream = os.fdopen(c2pwrite, 'wb', 1)
3256
3545
                subunit_result = AutoTimingTestResultDecorator(
3257
 
                    TestProtocolClient(stream))
 
3546
                    SubUnitBzrProtocolClient(stream))
3258
3547
                process_suite.run(subunit_result)
3259
 
            finally:
3260
 
                os._exit(0)
 
3548
            except:
 
3549
                # Try and report traceback on stream, but exit with error even
 
3550
                # if stream couldn't be created or something else goes wrong.
 
3551
                # The traceback is formatted to a string and written in one go
 
3552
                # to avoid interleaving lines from multiple failing children.
 
3553
                try:
 
3554
                    stream.write(traceback.format_exc())
 
3555
                finally:
 
3556
                    os._exit(1)
 
3557
            os._exit(0)
3261
3558
        else:
3262
3559
            os.close(c2pwrite)
3263
3560
            stream = os.fdopen(c2pread, 'rb', 1)
3310
3607
                '--subunit']
3311
3608
            if '--no-plugins' in sys.argv:
3312
3609
                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)
 
3610
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3611
            # noise on stderr it can interrupt the subunit protocol.
 
3612
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3613
                                      stdout=subprocess.PIPE,
 
3614
                                      stderr=subprocess.PIPE,
 
3615
                                      bufsize=1)
3317
3616
            test = TestInSubprocess(process, test_list_file_name)
3318
3617
            result.append(test)
3319
3618
        except:
3322
3621
    return result
3323
3622
 
3324
3623
 
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):
 
3624
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3358
3625
    """Generate profiling data for all activity between start and success.
3359
3626
    
3360
3627
    The profile data is appended to the test's _benchcalls attribute and can
3368
3635
 
3369
3636
    def startTest(self, test):
3370
3637
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3638
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3639
        # unavoidably fail.
 
3640
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3371
3641
        self.profiler.start()
3372
 
        ForwardingResult.startTest(self, test)
 
3642
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3373
3643
 
3374
3644
    def addSuccess(self, test):
3375
3645
        stats = self.profiler.stop()
3379
3649
            test._benchcalls = []
3380
3650
            calls = test._benchcalls
3381
3651
        calls.append(((test.id(), "", ""), stats))
3382
 
        ForwardingResult.addSuccess(self, test)
 
3652
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3383
3653
 
3384
3654
    def stopTest(self, test):
3385
 
        ForwardingResult.stopTest(self, test)
 
3655
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3386
3656
        self.profiler = None
3387
3657
 
3388
3658
 
3394
3664
#                           rather than failing tests. And no longer raise
3395
3665
#                           LockContention when fctnl locks are not being used
3396
3666
#                           with proper exclusion rules.
 
3667
#   -Ethreads               Will display thread ident at creation/join time to
 
3668
#                           help track thread leaks
 
3669
#   -Euncollected_cases     Display the identity of any test cases that weren't
 
3670
#                           deallocated after being completed.
 
3671
#   -Econfig_stats          Will collect statistics using addDetail
3397
3672
selftest_debug_flags = set()
3398
3673
 
3399
3674
 
3593
3868
                key, obj, help=help, info=info, override_existing=False)
3594
3869
        except KeyError:
3595
3870
            actual = self.get(key)
3596
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3597
 
                 % (key, actual, obj))
 
3871
            trace.note(
 
3872
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3873
                % (key, actual, obj))
3598
3874
 
3599
3875
    def resolve_alias(self, id_start):
3600
3876
        """Replace the alias by the prefix in the given string.
3632
3908
        'bzrlib.doc',
3633
3909
        'bzrlib.tests.blackbox',
3634
3910
        'bzrlib.tests.commands',
 
3911
        'bzrlib.tests.doc_generate',
3635
3912
        'bzrlib.tests.per_branch',
3636
3913
        'bzrlib.tests.per_bzrdir',
3637
 
        'bzrlib.tests.per_bzrdir_colo',
 
3914
        'bzrlib.tests.per_controldir',
 
3915
        'bzrlib.tests.per_controldir_colo',
3638
3916
        'bzrlib.tests.per_foreign_vcs',
3639
3917
        'bzrlib.tests.per_interrepository',
3640
3918
        'bzrlib.tests.per_intertree',
3648
3926
        'bzrlib.tests.per_repository',
3649
3927
        'bzrlib.tests.per_repository_chk',
3650
3928
        'bzrlib.tests.per_repository_reference',
 
3929
        'bzrlib.tests.per_repository_vf',
3651
3930
        'bzrlib.tests.per_uifactory',
3652
3931
        'bzrlib.tests.per_versionedfile',
3653
3932
        'bzrlib.tests.per_workingtree',
3654
3933
        'bzrlib.tests.test__annotator',
3655
3934
        'bzrlib.tests.test__bencode',
 
3935
        'bzrlib.tests.test__btree_serializer',
3656
3936
        'bzrlib.tests.test__chk_map',
3657
3937
        'bzrlib.tests.test__dirstate_helpers',
3658
3938
        'bzrlib.tests.test__groupcompress',
3686
3966
        'bzrlib.tests.test_commit_merge',
3687
3967
        'bzrlib.tests.test_config',
3688
3968
        'bzrlib.tests.test_conflicts',
 
3969
        'bzrlib.tests.test_controldir',
3689
3970
        'bzrlib.tests.test_counted_lock',
3690
3971
        'bzrlib.tests.test_crash',
3691
3972
        'bzrlib.tests.test_decorators',
3692
3973
        'bzrlib.tests.test_delta',
3693
3974
        'bzrlib.tests.test_debug',
3694
 
        'bzrlib.tests.test_deprecated_graph',
3695
3975
        'bzrlib.tests.test_diff',
3696
3976
        'bzrlib.tests.test_directory_service',
3697
3977
        'bzrlib.tests.test_dirstate',
3698
3978
        'bzrlib.tests.test_email_message',
3699
3979
        'bzrlib.tests.test_eol_filters',
3700
3980
        'bzrlib.tests.test_errors',
 
3981
        'bzrlib.tests.test_estimate_compressed_size',
3701
3982
        'bzrlib.tests.test_export',
 
3983
        'bzrlib.tests.test_export_pot',
3702
3984
        'bzrlib.tests.test_extract',
 
3985
        'bzrlib.tests.test_features',
3703
3986
        'bzrlib.tests.test_fetch',
 
3987
        'bzrlib.tests.test_fixtures',
3704
3988
        'bzrlib.tests.test_fifo_cache',
3705
3989
        'bzrlib.tests.test_filters',
 
3990
        'bzrlib.tests.test_filter_tree',
3706
3991
        'bzrlib.tests.test_ftp_transport',
3707
3992
        'bzrlib.tests.test_foreign',
3708
3993
        'bzrlib.tests.test_generate_docs',
3717
4002
        'bzrlib.tests.test_http',
3718
4003
        'bzrlib.tests.test_http_response',
3719
4004
        'bzrlib.tests.test_https_ca_bundle',
 
4005
        'bzrlib.tests.test_https_urllib',
 
4006
        'bzrlib.tests.test_i18n',
3720
4007
        'bzrlib.tests.test_identitymap',
3721
4008
        'bzrlib.tests.test_ignores',
3722
4009
        'bzrlib.tests.test_index',
3727
4014
        'bzrlib.tests.test_knit',
3728
4015
        'bzrlib.tests.test_lazy_import',
3729
4016
        'bzrlib.tests.test_lazy_regex',
 
4017
        'bzrlib.tests.test_library_state',
3730
4018
        'bzrlib.tests.test_lock',
3731
4019
        'bzrlib.tests.test_lockable_files',
3732
4020
        'bzrlib.tests.test_lockdir',
3734
4022
        'bzrlib.tests.test_lru_cache',
3735
4023
        'bzrlib.tests.test_lsprof',
3736
4024
        'bzrlib.tests.test_mail_client',
 
4025
        'bzrlib.tests.test_matchers',
3737
4026
        'bzrlib.tests.test_memorytree',
3738
4027
        'bzrlib.tests.test_merge',
3739
4028
        'bzrlib.tests.test_merge3',
3740
4029
        'bzrlib.tests.test_merge_core',
3741
4030
        'bzrlib.tests.test_merge_directive',
 
4031
        'bzrlib.tests.test_mergetools',
3742
4032
        'bzrlib.tests.test_missing',
3743
4033
        'bzrlib.tests.test_msgeditor',
3744
4034
        'bzrlib.tests.test_multiparent',
3753
4043
        'bzrlib.tests.test_permissions',
3754
4044
        'bzrlib.tests.test_plugins',
3755
4045
        'bzrlib.tests.test_progress',
 
4046
        'bzrlib.tests.test_pyutils',
3756
4047
        'bzrlib.tests.test_read_bundle',
3757
4048
        'bzrlib.tests.test_reconcile',
3758
4049
        'bzrlib.tests.test_reconfigure',
3767
4058
        'bzrlib.tests.test_rio',
3768
4059
        'bzrlib.tests.test_rules',
3769
4060
        'bzrlib.tests.test_sampler',
 
4061
        'bzrlib.tests.test_scenarios',
3770
4062
        'bzrlib.tests.test_script',
3771
4063
        'bzrlib.tests.test_selftest',
3772
4064
        'bzrlib.tests.test_serializer',
3777
4069
        'bzrlib.tests.test_smart',
3778
4070
        'bzrlib.tests.test_smart_add',
3779
4071
        'bzrlib.tests.test_smart_request',
 
4072
        'bzrlib.tests.test_smart_signals',
3780
4073
        'bzrlib.tests.test_smart_transport',
3781
4074
        'bzrlib.tests.test_smtp_connection',
3782
4075
        'bzrlib.tests.test_source',
3788
4081
        'bzrlib.tests.test_switch',
3789
4082
        'bzrlib.tests.test_symbol_versioning',
3790
4083
        'bzrlib.tests.test_tag',
 
4084
        'bzrlib.tests.test_test_server',
3791
4085
        'bzrlib.tests.test_testament',
3792
4086
        'bzrlib.tests.test_textfile',
3793
4087
        'bzrlib.tests.test_textmerge',
 
4088
        'bzrlib.tests.test_cethread',
3794
4089
        'bzrlib.tests.test_timestamp',
3795
4090
        'bzrlib.tests.test_trace',
3796
4091
        'bzrlib.tests.test_transactions',
3799
4094
        'bzrlib.tests.test_transport_log',
3800
4095
        'bzrlib.tests.test_tree',
3801
4096
        'bzrlib.tests.test_treebuilder',
 
4097
        'bzrlib.tests.test_treeshape',
3802
4098
        'bzrlib.tests.test_tsort',
3803
4099
        'bzrlib.tests.test_tuned_gzip',
3804
4100
        'bzrlib.tests.test_ui',
3806
4102
        'bzrlib.tests.test_upgrade',
3807
4103
        'bzrlib.tests.test_upgrade_stacked',
3808
4104
        'bzrlib.tests.test_urlutils',
 
4105
        'bzrlib.tests.test_utextwrap',
3809
4106
        'bzrlib.tests.test_version',
3810
4107
        'bzrlib.tests.test_version_info',
 
4108
        'bzrlib.tests.test_versionedfile',
 
4109
        'bzrlib.tests.test_vf_search',
3811
4110
        'bzrlib.tests.test_weave',
3812
4111
        'bzrlib.tests.test_whitebox',
3813
4112
        'bzrlib.tests.test_win32utils',
3827
4126
        'bzrlib',
3828
4127
        'bzrlib.branchbuilder',
3829
4128
        'bzrlib.decorators',
3830
 
        'bzrlib.export',
3831
4129
        'bzrlib.inventory',
3832
4130
        'bzrlib.iterablefile',
3833
4131
        'bzrlib.lockdir',
3834
4132
        'bzrlib.merge3',
3835
4133
        'bzrlib.option',
 
4134
        'bzrlib.pyutils',
3836
4135
        'bzrlib.symbol_versioning',
3837
4136
        'bzrlib.tests',
 
4137
        'bzrlib.tests.fixtures',
3838
4138
        'bzrlib.timestamp',
 
4139
        'bzrlib.transport.http',
3839
4140
        'bzrlib.version_info_formats.format_custom',
3840
4141
        ]
3841
4142
 
3894
4195
        try:
3895
4196
            # note that this really does mean "report only" -- doctest
3896
4197
            # still runs the rest of the examples
3897
 
            doc_suite = doctest.DocTestSuite(mod,
3898
 
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4198
            doc_suite = IsolatedDocTestSuite(
 
4199
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3899
4200
        except ValueError, e:
3900
4201
            print '**failed to get doctest for: %s\n%s' % (mod, e)
3901
4202
            raise
3904
4205
        suite.addTest(doc_suite)
3905
4206
 
3906
4207
    default_encoding = sys.getdefaultencoding()
3907
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4208
    for name, plugin in _mod_plugin.plugins().items():
3908
4209
        if not interesting_module(plugin.module.__name__):
3909
4210
            continue
3910
4211
        plugin_suite = plugin.test_suite()
3916
4217
        if plugin_suite is not None:
3917
4218
            suite.addTest(plugin_suite)
3918
4219
        if default_encoding != sys.getdefaultencoding():
3919
 
            bzrlib.trace.warning(
 
4220
            trace.warning(
3920
4221
                'Plugin "%s" tried to reset default encoding to: %s', name,
3921
4222
                sys.getdefaultencoding())
3922
4223
            reload(sys)
3937
4238
            # Some tests mentioned in the list are not in the test suite. The
3938
4239
            # list may be out of date, report to the tester.
3939
4240
            for id in not_found:
3940
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4241
                trace.warning('"%s" not found in the test suite', id)
3941
4242
        for id in duplicates:
3942
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4243
            trace.warning('"%s" is used as an id by several tests', id)
3943
4244
 
3944
4245
    return suite
3945
4246
 
3946
4247
 
3947
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4248
def multiply_scenarios(*scenarios):
 
4249
    """Multiply two or more iterables of scenarios.
 
4250
 
 
4251
    It is safe to pass scenario generators or iterators.
 
4252
 
 
4253
    :returns: A list of compound scenarios: the cross-product of all 
 
4254
        scenarios, with the names concatenated and the parameters
 
4255
        merged together.
 
4256
    """
 
4257
    return reduce(_multiply_two_scenarios, map(list, scenarios))
 
4258
 
 
4259
 
 
4260
def _multiply_two_scenarios(scenarios_left, scenarios_right):
3948
4261
    """Multiply two sets of scenarios.
3949
4262
 
3950
4263
    :returns: the cartesian product of the two sets of scenarios, that is
3981
4294
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
3982
4295
    ...     [('one', dict(param=1)),
3983
4296
    ...      ('two', dict(param=2))],
3984
 
    ...     TestSuite())
 
4297
    ...     TestUtil.TestSuite())
3985
4298
    >>> tests = list(iter_suite_tests(r))
3986
4299
    >>> len(tests)
3987
4300
    2
4034
4347
    :param new_id: The id to assign to it.
4035
4348
    :return: The new test.
4036
4349
    """
4037
 
    new_test = copy(test)
 
4350
    new_test = copy.copy(test)
4038
4351
    new_test.id = lambda: new_id
 
4352
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4353
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4354
    # read the test output for parameterized tests, because tracebacks will be
 
4355
    # associated with irrelevant tests.
 
4356
    try:
 
4357
        details = new_test._TestCase__details
 
4358
    except AttributeError:
 
4359
        # must be a different version of testtools than expected.  Do nothing.
 
4360
        pass
 
4361
    else:
 
4362
        # Reset the '__details' dict.
 
4363
        new_test._TestCase__details = {}
4039
4364
    return new_test
4040
4365
 
4041
4366
 
4062
4387
        the module is available.
4063
4388
    """
4064
4389
 
4065
 
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4390
    from bzrlib.tests.features import ModuleAvailableFeature
 
4391
    py_module = pyutils.get_named_object(py_module_name)
4066
4392
    scenarios = [
4067
4393
        ('python', {'module': py_module}),
4068
4394
    ]
4101
4427
        if test_id != None:
4102
4428
            ui.ui_factory.clear_term()
4103
4429
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4430
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4431
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4432
                                    ).encode('ascii', 'replace')
4104
4433
        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')
 
4434
                         % (os.path.basename(dirname), printable_e))
4265
4435
 
4266
4436
 
4267
4437
def probe_unicode_in_user_encoding():
4297
4467
    return None
4298
4468
 
4299
4469
 
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
4470
# Only define SubUnitBzrRunner if subunit is available.
4453
4471
try:
4454
4472
    from subunit import TestProtocolClient
4455
4473
    from subunit.test_results import AutoTimingTestResultDecorator
 
4474
    class SubUnitBzrProtocolClient(TestProtocolClient):
 
4475
 
 
4476
        def stopTest(self, test):
 
4477
            super(SubUnitBzrProtocolClient, self).stopTest(test)
 
4478
            _clear__type_equality_funcs(test)
 
4479
 
 
4480
        def addSuccess(self, test, details=None):
 
4481
            # The subunit client always includes the details in the subunit
 
4482
            # stream, but we don't want to include it in ours.
 
4483
            if details is not None and 'log' in details:
 
4484
                del details['log']
 
4485
            return super(SubUnitBzrProtocolClient, self).addSuccess(
 
4486
                test, details)
 
4487
 
4456
4488
    class SubUnitBzrRunner(TextTestRunner):
4457
4489
        def run(self, test):
4458
4490
            result = AutoTimingTestResultDecorator(
4459
 
                TestProtocolClient(self.stream))
 
4491
                SubUnitBzrProtocolClient(self.stream))
4460
4492
            test.run(result)
4461
4493
            return result
4462
4494
except ImportError:
4463
4495
    pass
4464
4496
 
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()
 
4497
 
 
4498
# API compatibility for old plugins; see bug 892622.
 
4499
for name in [
 
4500
    'Feature',
 
4501
    'HTTPServerFeature', 
 
4502
    'ModuleAvailableFeature',
 
4503
    'HTTPSServerFeature', 'SymlinkFeature', 'HardlinkFeature',
 
4504
    'OsFifoFeature', 'UnicodeFilenameFeature',
 
4505
    'ByteStringNamedFilesystem', 'UTF8Filesystem',
 
4506
    'BreakinFeature', 'CaseInsCasePresFilenameFeature',
 
4507
    'CaseInsensitiveFilesystemFeature', 'case_sensitive_filesystem_feature',
 
4508
    'posix_permissions_feature',
 
4509
    ]:
 
4510
    globals()[name] = _CompatabilityThunkFeature(
 
4511
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4512
        'bzrlib.tests', name,
 
4513
        name, 'bzrlib.tests.features')
 
4514
 
 
4515
 
 
4516
for (old_name, new_name) in [
 
4517
    ('UnicodeFilename', 'UnicodeFilenameFeature'),
 
4518
    ]:
 
4519
    globals()[name] = _CompatabilityThunkFeature(
 
4520
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4521
        'bzrlib.tests', old_name,
 
4522
        new_name, 'bzrlib.tests.features')