/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Patch Queue Manager
  • Date: 2012-03-12 12:35:59 UTC
  • mfrom: (6491.1.7 repo-verify-signatures)
  • Revision ID: pqm@pqm.ubuntu.com-20120312123559-g4tqzz3790kszu03
(jelmer) Various fixes for 'bzr verify-signatures'. (Jelmer Vernooij)

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
 
    bzrdir,
 
63
    controldir,
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
150
247
    different types of display.
151
248
 
152
249
    When a test finishes, in whatever way, it calls one of the addSuccess,
153
 
    addFailure or addError classes.  These in turn may redirect to a more
 
250
    addFailure or addError methods.  These in turn may redirect to a more
154
251
    specific case for the special test results supported by our extended
155
252
    tests.
156
253
 
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
        self._log_files = set()
 
1030
        # Each key in the ``_counters`` dict holds a value for a different
 
1031
        # counter. When the test ends, addDetail() should be used to output the
 
1032
        # counter values. This happens in install_counter_hook().
 
1033
        self._counters = {}
 
1034
        if 'config_stats' in selftest_debug_flags:
 
1035
            self._install_config_stats_hooks()
 
1036
        # Do not use i18n for tests (unless the test reverses this)
 
1037
        i18n.disable_i18n()
832
1038
 
833
1039
    def debug(self):
834
1040
        # debug a frame up.
835
1041
        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()
 
1042
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
1043
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
1044
                ).set_trace(sys._getframe().f_back)
 
1045
 
 
1046
    def discardDetail(self, name):
 
1047
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1048
 
 
1049
        eg. bzr always adds the 'log' detail at startup, but we don't want to
 
1050
        include it for skipped, xfail, etc tests.
 
1051
 
 
1052
        It is safe to call this for a detail that doesn't exist, in case this
 
1053
        gets called multiple times.
 
1054
        """
 
1055
        # We cheat. details is stored in __details which means we shouldn't
 
1056
        # touch it. but getDetails() returns the dict directly, so we can
 
1057
        # mutate it.
 
1058
        details = self.getDetails()
 
1059
        if name in details:
 
1060
            del details[name]
 
1061
 
 
1062
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1063
        """Install a counting hook.
 
1064
 
 
1065
        Any hook can be counted as long as it doesn't need to return a value.
 
1066
 
 
1067
        :param hooks: Where the hook should be installed.
 
1068
 
 
1069
        :param name: The hook name that will be counted.
 
1070
 
 
1071
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1072
            to ``name``.
 
1073
        """
 
1074
        _counters = self._counters # Avoid closing over self
 
1075
        if counter_name is None:
 
1076
            counter_name = name
 
1077
        if _counters.has_key(counter_name):
 
1078
            raise AssertionError('%s is already used as a counter name'
 
1079
                                  % (counter_name,))
 
1080
        _counters[counter_name] = 0
 
1081
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1082
            lambda: ['%d' % (_counters[counter_name],)]))
 
1083
        def increment_counter(*args, **kwargs):
 
1084
            _counters[counter_name] += 1
 
1085
        label = 'count %s calls' % (counter_name,)
 
1086
        hooks.install_named_hook(name, increment_counter, label)
 
1087
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1088
 
 
1089
    def _install_config_stats_hooks(self):
 
1090
        """Install config hooks to count hook calls.
 
1091
 
 
1092
        """
 
1093
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1094
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1095
                                       'config.%s' % (hook_name,))
 
1096
 
 
1097
        # The OldConfigHooks are private and need special handling to protect
 
1098
        # against recursive tests (tests that run other tests), so we just do
 
1099
        # manually what registering them into _builtin_known_hooks will provide
 
1100
        # us.
 
1101
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1102
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1103
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1104
                                      'old_config.%s' % (hook_name,))
852
1105
 
853
1106
    def _clear_debug_flags(self):
854
1107
        """Prevent externally set debug flags affecting tests.
865
1118
 
866
1119
    def _clear_hooks(self):
867
1120
        # prevent hooks affecting tests
 
1121
        known_hooks = hooks.known_hooks
868
1122
        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)
 
1123
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1124
            current_hooks = getattr(parent, name)
872
1125
            self._preserved_hooks[parent] = (name, current_hooks)
 
1126
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1127
        hooks._lazy_hooks = {}
873
1128
        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)
 
1129
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1130
            factory = known_hooks.get(key)
876
1131
            setattr(parent, name, factory())
877
1132
        # this hook should always be installed
878
1133
        request._install_hook()
907
1162
        # break some locks on purpose and should be taken into account by
908
1163
        # considering that breaking a lock is just a dirty way of releasing it.
909
1164
        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))
 
1165
            message = (
 
1166
                'Different number of acquired and '
 
1167
                'released or broken locks.\n'
 
1168
                'acquired=%s\n'
 
1169
                'released=%s\n'
 
1170
                'broken=%s\n' %
 
1171
                (acquired_locks, released_locks, broken_locks))
913
1172
            if not self._lock_check_thorough:
914
1173
                # Rather than fail, just warn
915
1174
                print "Broken test %s: %s" % (self, message)
943
1202
 
944
1203
    def permit_dir(self, name):
945
1204
        """Permit a directory to be used by this test. See permit_url."""
946
 
        name_transport = get_transport(name)
 
1205
        name_transport = _mod_transport.get_transport_from_path(name)
947
1206
        self.permit_url(name)
948
1207
        self.permit_url(name_transport.base)
949
1208
 
972
1231
            try:
973
1232
                workingtree.WorkingTree.open(path)
974
1233
            except (errors.NotBranchError, errors.NoWorkingTree):
975
 
                return
 
1234
                raise TestSkipped('Needs a working tree of bzr sources')
976
1235
        finally:
977
1236
            self.enable_directory_isolation()
978
1237
 
1028
1287
        self.addCleanup(transport_server.stop_server)
1029
1288
        # Obtain a real transport because if the server supplies a password, it
1030
1289
        # will be hidden from the base on the client side.
1031
 
        t = get_transport(transport_server.get_url())
 
1290
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1032
1291
        # Some transport servers effectively chroot the backing transport;
1033
1292
        # others like SFTPServer don't - users of the transport can walk up the
1034
1293
        # transport to read the entire backing transport. This wouldn't matter
1065
1324
        # hook into bzr dir opening. This leaves a small window of error for
1066
1325
        # transport tests, but they are well known, and we can improve on this
1067
1326
        # step.
1068
 
        bzrdir.BzrDir.hooks.install_named_hook("pre_open",
 
1327
        controldir.ControlDir.hooks.install_named_hook("pre_open",
1069
1328
            self._preopen_isolate_transport, "Check bzr directories are safe.")
1070
1329
 
1071
1330
    def _ndiff_strings(self, a, b):
1090
1349
        except UnicodeError, e:
1091
1350
            # If we can't compare without getting a UnicodeError, then
1092
1351
            # obviously they are different
1093
 
            mutter('UnicodeError: %s', e)
 
1352
            trace.mutter('UnicodeError: %s', e)
1094
1353
        if message:
1095
1354
            message += '\n'
1096
1355
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1097
1356
            % (message,
1098
 
               pformat(a), pformat(b)))
 
1357
               pprint.pformat(a), pprint.pformat(b)))
1099
1358
 
1100
1359
    assertEquals = assertEqual
1101
1360
 
1135
1394
                         'st_mtime did not match')
1136
1395
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1137
1396
                         'st_ctime did not match')
1138
 
        if sys.platform != 'win32':
 
1397
        if sys.platform == 'win32':
1139
1398
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1140
1399
            # 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
 
1400
            # odd. We just force it to always be 0 to avoid any problems.
 
1401
            self.assertEqual(0, expected.st_dev)
 
1402
            self.assertEqual(0, actual.st_dev)
 
1403
            self.assertEqual(0, expected.st_ino)
 
1404
            self.assertEqual(0, actual.st_ino)
 
1405
        else:
1143
1406
            self.assertEqual(expected.st_dev, actual.st_dev,
1144
1407
                             'st_dev did not match')
1145
1408
            self.assertEqual(expected.st_ino, actual.st_ino,
1154
1417
                length, len(obj_with_len), obj_with_len))
1155
1418
 
1156
1419
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1157
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1420
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1158
1421
        """
1159
 
        from bzrlib import trace
1160
1422
        captured = []
1161
1423
        orig_log_exception_quietly = trace.log_exception_quietly
1162
1424
        try:
1163
1425
            def capture():
1164
1426
                orig_log_exception_quietly()
1165
 
                captured.append(sys.exc_info())
 
1427
                captured.append(sys.exc_info()[1])
1166
1428
            trace.log_exception_quietly = capture
1167
1429
            func(*args, **kwargs)
1168
1430
        finally:
1169
1431
            trace.log_exception_quietly = orig_log_exception_quietly
1170
1432
        self.assertLength(1, captured)
1171
 
        err = captured[0][1]
 
1433
        err = captured[0]
1172
1434
        self.assertIsInstance(err, exception_class)
1173
1435
        return err
1174
1436
 
1211
1473
        if haystack.find(needle) == -1:
1212
1474
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1213
1475
 
 
1476
    def assertNotContainsString(self, haystack, needle):
 
1477
        if haystack.find(needle) != -1:
 
1478
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1479
 
1214
1480
    def assertSubset(self, sublist, superlist):
1215
1481
        """Assert that every entry in sublist is present in superlist."""
1216
1482
        missing = set(sublist) - set(superlist)
1305
1571
 
1306
1572
    def assertFileEqual(self, content, path):
1307
1573
        """Fail if path does not contain 'content'."""
1308
 
        self.failUnlessExists(path)
 
1574
        self.assertPathExists(path)
1309
1575
        f = file(path, 'rb')
1310
1576
        try:
1311
1577
            s = f.read()
1321
1587
        else:
1322
1588
            self.assertEqual(expected_docstring, obj.__doc__)
1323
1589
 
 
1590
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1324
1591
    def failUnlessExists(self, path):
 
1592
        return self.assertPathExists(path)
 
1593
 
 
1594
    def assertPathExists(self, path):
1325
1595
        """Fail unless path or paths, which may be abs or relative, exist."""
1326
1596
        if not isinstance(path, basestring):
1327
1597
            for p in path:
1328
 
                self.failUnlessExists(p)
 
1598
                self.assertPathExists(p)
1329
1599
        else:
1330
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1600
            self.assertTrue(osutils.lexists(path),
 
1601
                path + " does not exist")
1331
1602
 
 
1603
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1332
1604
    def failIfExists(self, path):
 
1605
        return self.assertPathDoesNotExist(path)
 
1606
 
 
1607
    def assertPathDoesNotExist(self, path):
1333
1608
        """Fail if path or paths, which may be abs or relative, exist."""
1334
1609
        if not isinstance(path, basestring):
1335
1610
            for p in path:
1336
 
                self.failIfExists(p)
 
1611
                self.assertPathDoesNotExist(p)
1337
1612
        else:
1338
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1613
            self.assertFalse(osutils.lexists(path),
 
1614
                path + " exists")
1339
1615
 
1340
1616
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1341
1617
        """A helper for callDeprecated and applyDeprecated.
1367
1643
        not other callers that go direct to the warning module.
1368
1644
 
1369
1645
        To test that a deprecated method raises an error, do something like
1370
 
        this::
 
1646
        this (remember that both assertRaises and applyDeprecated delays *args
 
1647
        and **kwargs passing)::
1371
1648
 
1372
1649
            self.assertRaises(errors.ReservedId,
1373
1650
                self.applyDeprecated,
1451
1728
        return result
1452
1729
 
1453
1730
    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
 
1731
        """Setup a in-memory target for bzr and testcase log messages"""
 
1732
        pseudo_log_file = StringIO()
 
1733
        def _get_log_contents_for_weird_testtools_api():
 
1734
            return [pseudo_log_file.getvalue().decode(
 
1735
                "utf-8", "replace").encode("utf-8")]
 
1736
        self.addDetail("log", content.Content(content.ContentType("text",
 
1737
            "plain", {"charset": "utf8"}),
 
1738
            _get_log_contents_for_weird_testtools_api))
 
1739
        self._log_file = pseudo_log_file
 
1740
        self._log_memento = trace.push_log_file(self._log_file)
1462
1741
        self.addCleanup(self._finishLogFile)
1463
1742
 
1464
1743
    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:
 
1744
        """Flush and dereference the in-memory log for this testcase"""
 
1745
        if trace._trace_file:
1470
1746
            # 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)
 
1747
            trace._trace_file.flush()
 
1748
        trace.pop_log_file(self._log_memento)
 
1749
        # The logging module now tracks references for cleanup so discard ours
 
1750
        del self._log_memento
1475
1751
 
1476
1752
    def thisFailsStrictLockCheck(self):
1477
1753
        """It is known that this test would fail with -Dstrict_locks.
1486
1762
        """
1487
1763
        debug.debug_flags.discard('strict_locks')
1488
1764
 
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
1765
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1498
1766
        """Overrides an object attribute restoring it after the test.
1499
1767
 
 
1768
        :note: This should be used with discretion; you should think about
 
1769
        whether it's better to make the code testable without monkey-patching.
 
1770
 
1500
1771
        :param obj: The object that will be mutated.
1501
1772
 
1502
1773
        :param attr_name: The attribute name we want to preserve/override in
1513
1784
            setattr(obj, attr_name, new)
1514
1785
        return value
1515
1786
 
 
1787
    def overrideEnv(self, name, new):
 
1788
        """Set an environment variable, and reset it after the test.
 
1789
 
 
1790
        :param name: The environment variable name.
 
1791
 
 
1792
        :param new: The value to set the variable to. If None, the 
 
1793
            variable is deleted from the environment.
 
1794
 
 
1795
        :returns: The actual variable value.
 
1796
        """
 
1797
        value = osutils.set_or_unset_env(name, new)
 
1798
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1799
        return value
 
1800
 
 
1801
    def recordCalls(self, obj, attr_name):
 
1802
        """Monkeypatch in a wrapper that will record calls.
 
1803
 
 
1804
        The monkeypatch is automatically removed when the test concludes.
 
1805
 
 
1806
        :param obj: The namespace holding the reference to be replaced;
 
1807
            typically a module, class, or object.
 
1808
        :param attr_name: A string for the name of the attribute to 
 
1809
            patch.
 
1810
        :returns: A list that will be extended with one item every time the
 
1811
            function is called, with a tuple of (args, kwargs).
 
1812
        """
 
1813
        calls = []
 
1814
 
 
1815
        def decorator(*args, **kwargs):
 
1816
            calls.append((args, kwargs))
 
1817
            return orig(*args, **kwargs)
 
1818
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1819
        return calls
 
1820
 
1516
1821
    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)
 
1822
        for name, value in isolated_environ.iteritems():
 
1823
            self.overrideEnv(name, value)
1577
1824
 
1578
1825
    def _restoreHooks(self):
1579
1826
        for klass, (name, hooks) in self._preserved_hooks.items():
1580
1827
            setattr(klass, name, hooks)
 
1828
        self._preserved_hooks.clear()
 
1829
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1830
        self._preserved_lazy_hooks.clear()
1581
1831
 
1582
1832
    def knownFailure(self, reason):
1583
 
        """This test has failed for some known reason."""
1584
 
        raise KnownFailure(reason)
 
1833
        """Declare that this test fails for a known reason
 
1834
 
 
1835
        Tests that are known to fail should generally be using expectedFailure
 
1836
        with an appropriate reverse assertion if a change could cause the test
 
1837
        to start passing. Conversely if the test has no immediate prospect of
 
1838
        succeeding then using skip is more suitable.
 
1839
 
 
1840
        When this method is called while an exception is being handled, that
 
1841
        traceback will be used, otherwise a new exception will be thrown to
 
1842
        provide one but won't be reported.
 
1843
        """
 
1844
        self._add_reason(reason)
 
1845
        try:
 
1846
            exc_info = sys.exc_info()
 
1847
            if exc_info != (None, None, None):
 
1848
                self._report_traceback(exc_info)
 
1849
            else:
 
1850
                try:
 
1851
                    raise self.failureException(reason)
 
1852
                except self.failureException:
 
1853
                    exc_info = sys.exc_info()
 
1854
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1855
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1856
        finally:
 
1857
            del exc_info
 
1858
 
 
1859
    def _suppress_log(self):
 
1860
        """Remove the log info from details."""
 
1861
        self.discardDetail('log')
1585
1862
 
1586
1863
    def _do_skip(self, result, reason):
 
1864
        self._suppress_log()
1587
1865
        addSkip = getattr(result, 'addSkip', None)
1588
1866
        if not callable(addSkip):
1589
1867
            result.addSuccess(result)
1592
1870
 
1593
1871
    @staticmethod
1594
1872
    def _do_known_failure(self, result, e):
 
1873
        self._suppress_log()
1595
1874
        err = sys.exc_info()
1596
1875
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1597
1876
        if addExpectedFailure is not None:
1605
1884
            reason = 'No reason given'
1606
1885
        else:
1607
1886
            reason = e.args[0]
 
1887
        self._suppress_log ()
1608
1888
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1609
1889
        if addNotApplicable is not None:
1610
1890
            result.addNotApplicable(self, reason)
1612
1892
            self._do_skip(result, reason)
1613
1893
 
1614
1894
    @staticmethod
 
1895
    def _report_skip(self, result, err):
 
1896
        """Override the default _report_skip.
 
1897
 
 
1898
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1899
        already been formatted into the 'reason' string, and we can't pull it
 
1900
        out again.
 
1901
        """
 
1902
        self._suppress_log()
 
1903
        super(TestCase, self)._report_skip(self, result, err)
 
1904
 
 
1905
    @staticmethod
 
1906
    def _report_expected_failure(self, result, err):
 
1907
        """Strip the log.
 
1908
 
 
1909
        See _report_skip for motivation.
 
1910
        """
 
1911
        self._suppress_log()
 
1912
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1913
 
 
1914
    @staticmethod
1615
1915
    def _do_unsupported_or_skip(self, result, e):
1616
1916
        reason = e.args[0]
 
1917
        self._suppress_log()
1617
1918
        addNotSupported = getattr(result, 'addNotSupported', None)
1618
1919
        if addNotSupported is not None:
1619
1920
            result.addNotSupported(self, reason)
1645
1946
            self._benchtime += time.time() - start
1646
1947
 
1647
1948
    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."
 
1949
        trace.mutter(*args)
1728
1950
 
1729
1951
    def get_log(self):
1730
1952
        """Get a unicode string containing the log from bzrlib.trace.
1766
1988
 
1767
1989
        self.log('run bzr: %r', args)
1768
1990
        # FIXME: don't call into logging here
1769
 
        handler = logging.StreamHandler(stderr)
1770
 
        handler.setLevel(logging.INFO)
 
1991
        handler = trace.EncodedStreamHandler(stderr, errors="replace",
 
1992
            level=logging.INFO)
1771
1993
        logger = logging.getLogger('')
1772
1994
        logger.addHandler(handler)
1773
1995
        old_ui_factory = ui.ui_factory
1780
2002
 
1781
2003
        try:
1782
2004
            try:
1783
 
                result = self.apply_redirected(ui.ui_factory.stdin,
 
2005
                result = self.apply_redirected(
 
2006
                    ui.ui_factory.stdin,
1784
2007
                    stdout, stderr,
1785
 
                    bzrlib.commands.run_bzr_catch_user_errors,
 
2008
                    _mod_commands.run_bzr_catch_user_errors,
1786
2009
                    args)
1787
2010
            except KeyboardInterrupt:
1788
2011
                # Reraise KeyboardInterrupt with contents of redirected stdout
1930
2153
    def start_bzr_subprocess(self, process_args, env_changes=None,
1931
2154
                             skip_if_plan_to_signal=False,
1932
2155
                             working_dir=None,
1933
 
                             allow_plugins=False):
 
2156
                             allow_plugins=False, stderr=subprocess.PIPE):
1934
2157
        """Start bzr in a subprocess for testing.
1935
2158
 
1936
2159
        This starts a new Python interpreter and runs bzr in there.
1945
2168
            variables. A value of None will unset the env variable.
1946
2169
            The values must be strings. The change will only occur in the
1947
2170
            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.
 
2171
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2172
            doesn't support signalling subprocesses.
1950
2173
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
2174
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2175
            are those valid for the stderr argument of `subprocess.Popen`.
 
2176
            Default value is ``subprocess.PIPE``.
1951
2177
 
1952
2178
        :returns: Popen object for the started process.
1953
2179
        """
1954
2180
        if skip_if_plan_to_signal:
1955
 
            if not getattr(os, 'kill', None):
1956
 
                raise TestSkipped("os.kill not available.")
 
2181
            if os.name != "posix":
 
2182
                raise TestSkipped("Sending signals not supported")
1957
2183
 
1958
2184
        if env_changes is None:
1959
2185
            env_changes = {}
 
2186
        # Because $HOME is set to a tempdir for the context of a test, modules
 
2187
        # installed in the user dir will not be found unless $PYTHONUSERBASE
 
2188
        # gets set to the computed directory of this parent process.
 
2189
        if site.USER_BASE is not None:
 
2190
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
1960
2191
        old_env = {}
1961
2192
 
1962
2193
        def cleanup_environment():
1979
2210
            # so we will avoid using it on all platforms, just to
1980
2211
            # make sure the code path is used, and we don't break on win32
1981
2212
            cleanup_environment()
 
2213
            # Include the subprocess's log file in the test details, in case
 
2214
            # the test fails due to an error in the subprocess.
 
2215
            self._add_subprocess_log(trace._get_bzr_log_filename())
1982
2216
            command = [sys.executable]
1983
2217
            # frozen executables don't need the path to bzr
1984
2218
            if getattr(sys, "frozen", None) is None:
1986
2220
            if not allow_plugins:
1987
2221
                command.append('--no-plugins')
1988
2222
            command.extend(process_args)
1989
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
2223
            process = self._popen(command, stdin=subprocess.PIPE,
 
2224
                                  stdout=subprocess.PIPE,
 
2225
                                  stderr=stderr)
1990
2226
        finally:
1991
2227
            restore_environment()
1992
2228
            if cwd is not None:
1994
2230
 
1995
2231
        return process
1996
2232
 
 
2233
    def _add_subprocess_log(self, log_file_path):
 
2234
        if len(self._log_files) == 0:
 
2235
            # Register an addCleanup func.  We do this on the first call to
 
2236
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2237
            # addCleanup is registered after any cleanups for tempdirs that
 
2238
            # subclasses might create, which will probably remove the log file
 
2239
            # we want to read.
 
2240
            self.addCleanup(self._subprocess_log_cleanup)
 
2241
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2242
        # twice.
 
2243
        self._log_files.add(log_file_path)
 
2244
 
 
2245
    def _subprocess_log_cleanup(self):
 
2246
        for count, log_file_path in enumerate(self._log_files):
 
2247
            # We use buffer_now=True to avoid holding the file open beyond
 
2248
            # the life of this function, which might interfere with e.g.
 
2249
            # cleaning tempdirs on Windows.
 
2250
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2251
            #detail_content = content.content_from_file(
 
2252
            #    log_file_path, buffer_now=True)
 
2253
            with open(log_file_path, 'rb') as log_file:
 
2254
                log_file_bytes = log_file.read()
 
2255
            detail_content = content.Content(content.ContentType("text",
 
2256
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2257
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2258
                detail_content)
 
2259
 
1997
2260
    def _popen(self, *args, **kwargs):
1998
2261
        """Place a call to Popen.
1999
2262
 
2000
2263
        Allows tests to override this method to intercept the calls made to
2001
2264
        Popen for introspection.
2002
2265
        """
2003
 
        return Popen(*args, **kwargs)
 
2266
        return subprocess.Popen(*args, **kwargs)
2004
2267
 
2005
2268
    def get_source_path(self):
2006
2269
        """Return the path of the directory containing bzrlib."""
2008
2271
 
2009
2272
    def get_bzr_path(self):
2010
2273
        """Return the path of the 'bzr' executable for this test suite."""
2011
 
        bzr_path = self.get_source_path()+'/bzr'
 
2274
        bzr_path = os.path.join(self.get_source_path(), "bzr")
2012
2275
        if not os.path.isfile(bzr_path):
2013
2276
            # We are probably installed. Assume sys.argv is the right file
2014
2277
            bzr_path = sys.argv[0]
2036
2299
        if retcode is not None and retcode != process.returncode:
2037
2300
            if process_args is None:
2038
2301
                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)
 
2302
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
 
2303
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
2041
2304
            self.fail('Command bzr %s failed with retcode %s != %s'
2042
2305
                      % (process_args, retcode, process.returncode))
2043
2306
        return [out, err]
2044
2307
 
2045
 
    def check_inventory_shape(self, inv, shape):
2046
 
        """Compare an inventory to a list of expected names.
 
2308
    def check_tree_shape(self, tree, shape):
 
2309
        """Compare a tree to a list of expected names.
2047
2310
 
2048
2311
        Fail if they are not precisely equal.
2049
2312
        """
2050
2313
        extras = []
2051
2314
        shape = list(shape)             # copy
2052
 
        for path, ie in inv.entries():
 
2315
        for path, ie in tree.iter_entries_by_dir():
2053
2316
            name = path.replace('\\', '/')
2054
2317
            if ie.kind == 'directory':
2055
2318
                name = name + '/'
2056
 
            if name in shape:
 
2319
            if name == "/":
 
2320
                pass # ignore root entry
 
2321
            elif name in shape:
2057
2322
                shape.remove(name)
2058
2323
            else:
2059
2324
                extras.append(name)
2100
2365
 
2101
2366
        Tests that expect to provoke LockContention errors should call this.
2102
2367
        """
2103
 
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2368
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2104
2369
 
2105
2370
    def make_utf8_encoded_stringio(self, encoding_type=None):
2106
2371
        """Return a StringIOWrapper instance, that will encode Unicode
2119
2384
        from bzrlib.smart import request
2120
2385
        request_handlers = request.request_handlers
2121
2386
        orig_method = request_handlers.get(verb)
 
2387
        orig_info = request_handlers.get_info(verb)
2122
2388
        request_handlers.remove(verb)
2123
 
        self.addCleanup(request_handlers.register, verb, orig_method)
 
2389
        self.addCleanup(request_handlers.register, verb, orig_method,
 
2390
            info=orig_info)
2124
2391
 
2125
2392
 
2126
2393
class CapturedCall(object):
2149
2416
class TestCaseWithMemoryTransport(TestCase):
2150
2417
    """Common test class for tests that do not need disk resources.
2151
2418
 
2152
 
    Tests that need disk resources should derive from TestCaseWithTransport.
 
2419
    Tests that need disk resources should derive from TestCaseInTempDir
 
2420
    orTestCaseWithTransport.
2153
2421
 
2154
2422
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2155
2423
 
2156
 
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
2424
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2157
2425
    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
 
2426
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2427
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2428
    defaults for the transport in tests, nor does it obey the command line
2161
2429
    override, so tests that accidentally write to the common directory should
2162
2430
    be rare.
2163
2431
 
2164
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
2165
 
    a .bzr directory that stops us ascending higher into the filesystem.
 
2432
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2433
        ``.bzr`` directory that stops us ascending higher into the filesystem.
2166
2434
    """
2167
2435
 
2168
2436
    TEST_ROOT = None
2186
2454
 
2187
2455
        :param relpath: a path relative to the base url.
2188
2456
        """
2189
 
        t = get_transport(self.get_url(relpath))
 
2457
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2190
2458
        self.assertFalse(t.is_readonly())
2191
2459
        return t
2192
2460
 
2198
2466
 
2199
2467
        :param relpath: a path relative to the base url.
2200
2468
        """
2201
 
        t = get_transport(self.get_readonly_url(relpath))
 
2469
        t = _mod_transport.get_transport_from_url(
 
2470
            self.get_readonly_url(relpath))
2202
2471
        self.assertTrue(t.is_readonly())
2203
2472
        return t
2204
2473
 
2325
2594
        real branch.
2326
2595
        """
2327
2596
        root = TestCaseWithMemoryTransport.TEST_ROOT
2328
 
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2597
        # Make sure we get a readable and accessible home for .bzr.log
 
2598
        # and/or config files, and not fallback to weird defaults (see
 
2599
        # http://pad.lv/825027).
 
2600
        self.assertIs(None, os.environ.get('BZR_HOME', None))
 
2601
        os.environ['BZR_HOME'] = root
 
2602
        wt = controldir.ControlDir.create_standalone_workingtree(root)
 
2603
        del os.environ['BZR_HOME']
 
2604
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2605
        # we don't need to re-open the wt to check it hasn't changed.
 
2606
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2607
            wt.control_transport.get_bytes('dirstate'))
2329
2608
 
2330
2609
    def _check_safety_net(self):
2331
2610
        """Check that the safety .bzr directory have not been touched.
2334
2613
        propagating. This method ensures than a test did not leaked.
2335
2614
        """
2336
2615
        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:':
 
2616
        t = _mod_transport.get_transport_from_path(root)
 
2617
        self.permit_url(t.base)
 
2618
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2619
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2341
2620
            # The current test have modified the /bzr directory, we need to
2342
2621
            # recreate a new one or all the followng tests will fail.
2343
2622
            # If you need to inspect its content uncomment the following line
2375
2654
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2376
2655
        self.permit_dir(self.test_dir)
2377
2656
 
2378
 
    def make_branch(self, relpath, format=None):
 
2657
    def make_branch(self, relpath, format=None, name=None):
2379
2658
        """Create a branch on the transport at relpath."""
2380
2659
        repo = self.make_repository(relpath, format=format)
2381
 
        return repo.bzrdir.create_branch()
 
2660
        return repo.bzrdir.create_branch(append_revisions_only=False,
 
2661
                                         name=name)
 
2662
 
 
2663
    def get_default_format(self):
 
2664
        return 'default'
 
2665
 
 
2666
    def resolve_format(self, format):
 
2667
        """Resolve an object to a ControlDir format object.
 
2668
 
 
2669
        The initial format object can either already be
 
2670
        a ControlDirFormat, None (for the default format),
 
2671
        or a string with the name of the control dir format.
 
2672
 
 
2673
        :param format: Object to resolve
 
2674
        :return A ControlDirFormat instance
 
2675
        """
 
2676
        if format is None:
 
2677
            format = self.get_default_format()
 
2678
        if isinstance(format, basestring):
 
2679
            format = controldir.format_registry.make_bzrdir(format)
 
2680
        return format
2382
2681
 
2383
2682
    def make_bzrdir(self, relpath, format=None):
2384
2683
        try:
2385
2684
            # might be a relative or absolute path
2386
2685
            maybe_a_url = self.get_url(relpath)
2387
2686
            segments = maybe_a_url.rsplit('/', 1)
2388
 
            t = get_transport(maybe_a_url)
 
2687
            t = _mod_transport.get_transport(maybe_a_url)
2389
2688
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2390
2689
                t.ensure_base()
2391
 
            if format is None:
2392
 
                format = 'default'
2393
 
            if isinstance(format, basestring):
2394
 
                format = bzrdir.format_registry.make_bzrdir(format)
 
2690
            format = self.resolve_format(format)
2395
2691
            return format.initialize_on_transport(t)
2396
2692
        except errors.UninitializableFormat:
2397
2693
            raise TestSkipped("Format %s is not initializable." % format)
2398
2694
 
2399
 
    def make_repository(self, relpath, shared=False, format=None):
 
2695
    def make_repository(self, relpath, shared=None, format=None):
2400
2696
        """Create a repository on our default transport at relpath.
2401
2697
 
2402
2698
        Note that relpath must be a relative path, not a full url.
2408
2704
        made_control = self.make_bzrdir(relpath, format=format)
2409
2705
        return made_control.create_repository(shared=shared)
2410
2706
 
2411
 
    def make_smart_server(self, path):
 
2707
    def make_smart_server(self, path, backing_server=None):
 
2708
        if backing_server is None:
 
2709
            backing_server = self.get_server()
2412
2710
        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)
 
2711
        self.start_server(smart_server, backing_server)
 
2712
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
 
2713
                                                   ).clone(path)
2415
2714
        return remote_transport
2416
2715
 
2417
2716
    def make_branch_and_memory_tree(self, relpath, format=None):
2427
2726
        test_home_dir = self.test_home_dir
2428
2727
        if isinstance(test_home_dir, unicode):
2429
2728
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2430
 
        os.environ['HOME'] = test_home_dir
2431
 
        os.environ['BZR_HOME'] = test_home_dir
 
2729
        self.overrideEnv('HOME', test_home_dir)
 
2730
        self.overrideEnv('BZR_HOME', test_home_dir)
2432
2731
 
2433
2732
    def setUp(self):
2434
2733
        super(TestCaseWithMemoryTransport, self).setUp()
 
2734
 
 
2735
        def _add_disconnect_cleanup(transport):
 
2736
            """Schedule disconnection of given transport at test cleanup
 
2737
 
 
2738
            This needs to happen for all connected transports or leaks occur.
 
2739
 
 
2740
            Note reconnections may mean we call disconnect multiple times per
 
2741
            transport which is suboptimal but seems harmless.
 
2742
            """
 
2743
            self.addCleanup(transport.disconnect)
 
2744
 
 
2745
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
 
2746
            _add_disconnect_cleanup, None)
 
2747
 
2435
2748
        self._make_test_root()
2436
2749
        self.addCleanup(os.chdir, os.getcwdu())
2437
2750
        self.makeAndChdirToTestDir()
2443
2756
    def setup_smart_server_with_call_log(self):
2444
2757
        """Sets up a smart server as the transport server with a call log."""
2445
2758
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2759
        self.hpss_connections = []
2446
2760
        self.hpss_calls = []
2447
2761
        import traceback
2448
2762
        # Skip the current stack down to the caller of
2451
2765
        def capture_hpss_call(params):
2452
2766
            self.hpss_calls.append(
2453
2767
                CapturedCall(params, prefix_length))
 
2768
        def capture_connect(transport):
 
2769
            self.hpss_connections.append(transport)
2454
2770
        client._SmartClient.hooks.install_named_hook(
2455
2771
            'call', capture_hpss_call, None)
 
2772
        _mod_transport.Transport.hooks.install_named_hook(
 
2773
            'post_connect', capture_connect, None)
2456
2774
 
2457
2775
    def reset_smart_call_log(self):
2458
2776
        self.hpss_calls = []
 
2777
        self.hpss_connections = []
2459
2778
 
2460
2779
 
2461
2780
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2480
2799
 
2481
2800
    OVERRIDE_PYTHON = 'python'
2482
2801
 
 
2802
    def setUp(self):
 
2803
        super(TestCaseInTempDir, self).setUp()
 
2804
        # Remove the protection set in isolated_environ, we have a proper
 
2805
        # access to disk resources now.
 
2806
        self.overrideEnv('BZR_LOG', None)
 
2807
 
2483
2808
    def check_file_contents(self, filename, expect):
2484
2809
        self.log("check contents of file %s" % filename)
2485
 
        contents = file(filename, 'r').read()
 
2810
        f = file(filename)
 
2811
        try:
 
2812
            contents = f.read()
 
2813
        finally:
 
2814
            f.close()
2486
2815
        if contents != expect:
2487
2816
            self.log("expected: %r" % expect)
2488
2817
            self.log("actually: %r" % contents)
2521
2850
        # stacking policy to honour; create a bzr dir with an unshared
2522
2851
        # repository (but not a branch - our code would be trying to escape
2523
2852
        # then!) to stop them, and permit it to be read.
2524
 
        # control = bzrdir.BzrDir.create(self.test_base_dir)
 
2853
        # control = controldir.ControlDir.create(self.test_base_dir)
2525
2854
        # control.create_repository()
2526
2855
        self.test_home_dir = self.test_base_dir + '/home'
2527
2856
        os.mkdir(self.test_home_dir)
2562
2891
                "a list or a tuple. Got %r instead" % (shape,))
2563
2892
        # It's OK to just create them using forward slashes on windows.
2564
2893
        if transport is None or transport.is_readonly():
2565
 
            transport = get_transport(".")
 
2894
            transport = _mod_transport.get_transport_from_path(".")
2566
2895
        for name in shape:
2567
2896
            self.assertIsInstance(name, basestring)
2568
2897
            if name[-1] == '/':
2578
2907
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2579
2908
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2580
2909
 
2581
 
    def build_tree_contents(self, shape):
2582
 
        build_tree_contents(shape)
 
2910
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2583
2911
 
2584
2912
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2585
2913
        """Assert whether path or paths are in the WorkingTree"""
2654
2982
        # this obviously requires a format that supports branch references
2655
2983
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2656
2984
        # RBC 20060208
 
2985
        format = self.resolve_format(format=format)
 
2986
        if not format.supports_workingtrees:
 
2987
            b = self.make_branch(relpath+'.branch', format=format)
 
2988
            return b.create_checkout(relpath, lightweight=True)
2657
2989
        b = self.make_branch(relpath, format=format)
2658
2990
        try:
2659
2991
            return b.bzrdir.create_workingtree()
2664
2996
            if self.vfs_transport_factory is test_server.LocalURLServer:
2665
2997
                # the branch is colocated on disk, we cannot create a checkout.
2666
2998
                # hopefully callers will expect this.
2667
 
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
 
2999
                local_controldir = controldir.ControlDir.open(
 
3000
                    self.get_vfs_only_url(relpath))
2668
3001
                wt = local_controldir.create_workingtree()
2669
3002
                if wt.branch._format != b._format:
2670
3003
                    wt._branch = b
2726
3059
    """
2727
3060
 
2728
3061
    def setUp(self):
 
3062
        from bzrlib.tests import http_server
2729
3063
        super(ChrootedTestCase, self).setUp()
2730
3064
        if not self.vfs_transport_factory == memory.MemoryServer:
2731
 
            self.transport_readonly_server = HttpServer
 
3065
            self.transport_readonly_server = http_server.HttpServer
2732
3066
 
2733
3067
 
2734
3068
def condition_id_re(pattern):
2737
3071
    :param pattern: A regular expression string.
2738
3072
    :return: A callable that returns True if the re matches.
2739
3073
    """
2740
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2741
 
        'test filter')
 
3074
    filter_re = re.compile(pattern, 0)
2742
3075
    def condition(test):
2743
3076
        test_id = test.id()
2744
3077
        return filter_re.search(test_id)
2958
3291
                            result_decorators=result_decorators,
2959
3292
                            )
2960
3293
    runner.stop_on_failure=stop_on_failure
 
3294
    if isinstance(suite, unittest.TestSuite):
 
3295
        # Empty out _tests list of passed suite and populate new TestSuite
 
3296
        suite._tests[:], suite = [], TestSuite(suite)
2961
3297
    # built in decorator factories:
2962
3298
    decorators = [
2963
3299
        random_order(random_seed, runner),
2996
3332
 
2997
3333
 
2998
3334
def fork_decorator(suite):
 
3335
    if getattr(os, "fork", None) is None:
 
3336
        raise errors.BzrCommandError("platform does not support fork,"
 
3337
            " try --parallel=subprocess instead.")
2999
3338
    concurrency = osutils.local_concurrency()
3000
3339
    if concurrency == 1:
3001
3340
        return suite
3056
3395
    return suite
3057
3396
 
3058
3397
 
3059
 
class TestDecorator(TestSuite):
 
3398
class TestDecorator(TestUtil.TestSuite):
3060
3399
    """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().
 
3400
 
 
3401
    Contains rather than flattening suite passed on construction
3065
3402
    """
3066
3403
 
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
 
3404
    def __init__(self, suite=None):
 
3405
        super(TestDecorator, self).__init__()
 
3406
        if suite is not None:
 
3407
            self.addTest(suite)
 
3408
 
 
3409
    # Don't need subclass run method with suite emptying
 
3410
    run = unittest.TestSuite.run
3089
3411
 
3090
3412
 
3091
3413
class CountingDecorator(TestDecorator):
3102
3424
    """A decorator which excludes test matching an exclude pattern."""
3103
3425
 
3104
3426
    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)
 
3427
        super(ExcludeDecorator, self).__init__(
 
3428
            exclude_tests_by_re(suite, exclude_pattern))
3117
3429
 
3118
3430
 
3119
3431
class FilterTestsDecorator(TestDecorator):
3120
3432
    """A decorator which filters tests to those matching a pattern."""
3121
3433
 
3122
3434
    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)
 
3435
        super(FilterTestsDecorator, self).__init__(
 
3436
            filter_suite_by_re(suite, pattern))
3135
3437
 
3136
3438
 
3137
3439
class RandomDecorator(TestDecorator):
3138
3440
    """A decorator which randomises the order of its tests."""
3139
3441
 
3140
3442
    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()))
 
3443
        random_seed = self.actual_seed(random_seed)
 
3444
        stream.write("Randomizing test order using seed %s\n\n" %
 
3445
            (random_seed,))
3152
3446
        # 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)
 
3447
        random.seed(random_seed)
 
3448
        super(RandomDecorator, self).__init__(randomize_suite(suite))
3158
3449
 
3159
 
    def actual_seed(self):
3160
 
        if self.random_seed == "now":
 
3450
    @staticmethod
 
3451
    def actual_seed(seed):
 
3452
        if seed == "now":
3161
3453
            # We convert the seed to a long to make it reuseable across
3162
3454
            # invocations (because the user can reenter it).
3163
 
            self.random_seed = long(time.time())
 
3455
            return long(time.time())
3164
3456
        else:
3165
3457
            # Convert the seed to a long if we can
3166
3458
            try:
3167
 
                self.random_seed = long(self.random_seed)
3168
 
            except:
 
3459
                return long(seed)
 
3460
            except (TypeError, ValueError):
3169
3461
                pass
3170
 
        return self.random_seed
 
3462
        return seed
3171
3463
 
3172
3464
 
3173
3465
class TestFirstDecorator(TestDecorator):
3174
3466
    """A decorator which moves named tests to the front."""
3175
3467
 
3176
3468
    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)
 
3469
        super(TestFirstDecorator, self).__init__()
 
3470
        self.addTests(split_suite_by_re(suite, pattern))
3189
3471
 
3190
3472
 
3191
3473
def partition_tests(suite, count):
3192
3474
    """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
 
3475
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3476
    # splits up blocks of related tests that might run faster if they shared
 
3477
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3478
    # just one partition.  So the slowest partition shouldn't be much slower
 
3479
    # than the fastest.
 
3480
    partitions = [list() for i in range(count)]
 
3481
    tests = iter_suite_tests(suite)
 
3482
    for partition, test in itertools.izip(itertools.cycle(partitions), tests):
 
3483
        partition.append(test)
 
3484
    return partitions
3202
3485
 
3203
3486
 
3204
3487
def workaround_zealous_crypto_random():
3222
3505
    """
3223
3506
    concurrency = osutils.local_concurrency()
3224
3507
    result = []
3225
 
    from subunit import TestProtocolClient, ProtocolTestCase
 
3508
    from subunit import ProtocolTestCase
3226
3509
    from subunit.test_results import AutoTimingTestResultDecorator
3227
3510
    class TestInOtherProcess(ProtocolTestCase):
3228
3511
        # Should be in subunit, I think. RBC.
3234
3517
            try:
3235
3518
                ProtocolTestCase.run(self, result)
3236
3519
            finally:
3237
 
                os.waitpid(self.pid, 0)
 
3520
                pid, status = os.waitpid(self.pid, 0)
 
3521
            # GZ 2011-10-18: If status is nonzero, should report to the result
 
3522
            #                that something went wrong.
3238
3523
 
3239
3524
    test_blocks = partition_tests(suite, concurrency)
 
3525
    # Clear the tests from the original suite so it doesn't keep them alive
 
3526
    suite._tests[:] = []
3240
3527
    for process_tests in test_blocks:
3241
 
        process_suite = TestSuite()
3242
 
        process_suite.addTests(process_tests)
 
3528
        process_suite = TestUtil.TestSuite(process_tests)
 
3529
        # Also clear each split list so new suite has only reference
 
3530
        process_tests[:] = []
3243
3531
        c2pread, c2pwrite = os.pipe()
3244
3532
        pid = os.fork()
3245
3533
        if pid == 0:
3246
 
            workaround_zealous_crypto_random()
3247
3534
            try:
 
3535
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3536
                workaround_zealous_crypto_random()
3248
3537
                os.close(c2pread)
3249
3538
                # Leave stderr and stdout open so we can see test noise
3250
3539
                # Close stdin so that the child goes away if it decides to
3251
3540
                # read from stdin (otherwise its a roulette to see what
3252
3541
                # child actually gets keystrokes for pdb etc).
3253
3542
                sys.stdin.close()
3254
 
                sys.stdin = None
3255
 
                stream = os.fdopen(c2pwrite, 'wb', 1)
3256
3543
                subunit_result = AutoTimingTestResultDecorator(
3257
 
                    TestProtocolClient(stream))
 
3544
                    SubUnitBzrProtocolClient(stream))
3258
3545
                process_suite.run(subunit_result)
3259
 
            finally:
3260
 
                os._exit(0)
 
3546
            except:
 
3547
                # Try and report traceback on stream, but exit with error even
 
3548
                # if stream couldn't be created or something else goes wrong.
 
3549
                # The traceback is formatted to a string and written in one go
 
3550
                # to avoid interleaving lines from multiple failing children.
 
3551
                try:
 
3552
                    stream.write(traceback.format_exc())
 
3553
                finally:
 
3554
                    os._exit(1)
 
3555
            os._exit(0)
3261
3556
        else:
3262
3557
            os.close(c2pwrite)
3263
3558
            stream = os.fdopen(c2pread, 'rb', 1)
3310
3605
                '--subunit']
3311
3606
            if '--no-plugins' in sys.argv:
3312
3607
                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)
 
3608
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3609
            # noise on stderr it can interrupt the subunit protocol.
 
3610
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3611
                                      stdout=subprocess.PIPE,
 
3612
                                      stderr=subprocess.PIPE,
 
3613
                                      bufsize=1)
3317
3614
            test = TestInSubprocess(process, test_list_file_name)
3318
3615
            result.append(test)
3319
3616
        except:
3322
3619
    return result
3323
3620
 
3324
3621
 
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):
 
3622
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3358
3623
    """Generate profiling data for all activity between start and success.
3359
3624
    
3360
3625
    The profile data is appended to the test's _benchcalls attribute and can
3368
3633
 
3369
3634
    def startTest(self, test):
3370
3635
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3636
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3637
        # unavoidably fail.
 
3638
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3371
3639
        self.profiler.start()
3372
 
        ForwardingResult.startTest(self, test)
 
3640
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3373
3641
 
3374
3642
    def addSuccess(self, test):
3375
3643
        stats = self.profiler.stop()
3379
3647
            test._benchcalls = []
3380
3648
            calls = test._benchcalls
3381
3649
        calls.append(((test.id(), "", ""), stats))
3382
 
        ForwardingResult.addSuccess(self, test)
 
3650
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3383
3651
 
3384
3652
    def stopTest(self, test):
3385
 
        ForwardingResult.stopTest(self, test)
 
3653
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3386
3654
        self.profiler = None
3387
3655
 
3388
3656
 
3394
3662
#                           rather than failing tests. And no longer raise
3395
3663
#                           LockContention when fctnl locks are not being used
3396
3664
#                           with proper exclusion rules.
 
3665
#   -Ethreads               Will display thread ident at creation/join time to
 
3666
#                           help track thread leaks
 
3667
#   -Euncollected_cases     Display the identity of any test cases that weren't
 
3668
#                           deallocated after being completed.
 
3669
#   -Econfig_stats          Will collect statistics using addDetail
3397
3670
selftest_debug_flags = set()
3398
3671
 
3399
3672
 
3593
3866
                key, obj, help=help, info=info, override_existing=False)
3594
3867
        except KeyError:
3595
3868
            actual = self.get(key)
3596
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3597
 
                 % (key, actual, obj))
 
3869
            trace.note(
 
3870
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3871
                % (key, actual, obj))
3598
3872
 
3599
3873
    def resolve_alias(self, id_start):
3600
3874
        """Replace the alias by the prefix in the given string.
3632
3906
        'bzrlib.doc',
3633
3907
        'bzrlib.tests.blackbox',
3634
3908
        'bzrlib.tests.commands',
 
3909
        'bzrlib.tests.doc_generate',
3635
3910
        'bzrlib.tests.per_branch',
3636
3911
        'bzrlib.tests.per_bzrdir',
3637
 
        'bzrlib.tests.per_bzrdir_colo',
 
3912
        'bzrlib.tests.per_controldir',
 
3913
        'bzrlib.tests.per_controldir_colo',
3638
3914
        'bzrlib.tests.per_foreign_vcs',
3639
3915
        'bzrlib.tests.per_interrepository',
3640
3916
        'bzrlib.tests.per_intertree',
3648
3924
        'bzrlib.tests.per_repository',
3649
3925
        'bzrlib.tests.per_repository_chk',
3650
3926
        'bzrlib.tests.per_repository_reference',
 
3927
        'bzrlib.tests.per_repository_vf',
3651
3928
        'bzrlib.tests.per_uifactory',
3652
3929
        'bzrlib.tests.per_versionedfile',
3653
3930
        'bzrlib.tests.per_workingtree',
3654
3931
        'bzrlib.tests.test__annotator',
3655
3932
        'bzrlib.tests.test__bencode',
 
3933
        'bzrlib.tests.test__btree_serializer',
3656
3934
        'bzrlib.tests.test__chk_map',
3657
3935
        'bzrlib.tests.test__dirstate_helpers',
3658
3936
        'bzrlib.tests.test__groupcompress',
3686
3964
        'bzrlib.tests.test_commit_merge',
3687
3965
        'bzrlib.tests.test_config',
3688
3966
        'bzrlib.tests.test_conflicts',
 
3967
        'bzrlib.tests.test_controldir',
3689
3968
        'bzrlib.tests.test_counted_lock',
3690
3969
        'bzrlib.tests.test_crash',
3691
3970
        'bzrlib.tests.test_decorators',
3692
3971
        'bzrlib.tests.test_delta',
3693
3972
        'bzrlib.tests.test_debug',
3694
 
        'bzrlib.tests.test_deprecated_graph',
3695
3973
        'bzrlib.tests.test_diff',
3696
3974
        'bzrlib.tests.test_directory_service',
3697
3975
        'bzrlib.tests.test_dirstate',
3698
3976
        'bzrlib.tests.test_email_message',
3699
3977
        'bzrlib.tests.test_eol_filters',
3700
3978
        'bzrlib.tests.test_errors',
 
3979
        'bzrlib.tests.test_estimate_compressed_size',
3701
3980
        'bzrlib.tests.test_export',
 
3981
        'bzrlib.tests.test_export_pot',
3702
3982
        'bzrlib.tests.test_extract',
 
3983
        'bzrlib.tests.test_features',
3703
3984
        'bzrlib.tests.test_fetch',
 
3985
        'bzrlib.tests.test_fixtures',
3704
3986
        'bzrlib.tests.test_fifo_cache',
3705
3987
        'bzrlib.tests.test_filters',
 
3988
        'bzrlib.tests.test_filter_tree',
3706
3989
        'bzrlib.tests.test_ftp_transport',
3707
3990
        'bzrlib.tests.test_foreign',
3708
3991
        'bzrlib.tests.test_generate_docs',
3717
4000
        'bzrlib.tests.test_http',
3718
4001
        'bzrlib.tests.test_http_response',
3719
4002
        'bzrlib.tests.test_https_ca_bundle',
 
4003
        'bzrlib.tests.test_https_urllib',
 
4004
        'bzrlib.tests.test_i18n',
3720
4005
        'bzrlib.tests.test_identitymap',
3721
4006
        'bzrlib.tests.test_ignores',
3722
4007
        'bzrlib.tests.test_index',
3727
4012
        'bzrlib.tests.test_knit',
3728
4013
        'bzrlib.tests.test_lazy_import',
3729
4014
        'bzrlib.tests.test_lazy_regex',
 
4015
        'bzrlib.tests.test_library_state',
3730
4016
        'bzrlib.tests.test_lock',
3731
4017
        'bzrlib.tests.test_lockable_files',
3732
4018
        'bzrlib.tests.test_lockdir',
3740
4026
        'bzrlib.tests.test_merge3',
3741
4027
        'bzrlib.tests.test_merge_core',
3742
4028
        'bzrlib.tests.test_merge_directive',
 
4029
        'bzrlib.tests.test_mergetools',
3743
4030
        'bzrlib.tests.test_missing',
3744
4031
        'bzrlib.tests.test_msgeditor',
3745
4032
        'bzrlib.tests.test_multiparent',
3754
4041
        'bzrlib.tests.test_permissions',
3755
4042
        'bzrlib.tests.test_plugins',
3756
4043
        'bzrlib.tests.test_progress',
 
4044
        'bzrlib.tests.test_pyutils',
3757
4045
        'bzrlib.tests.test_read_bundle',
3758
4046
        'bzrlib.tests.test_reconcile',
3759
4047
        'bzrlib.tests.test_reconfigure',
3767
4055
        'bzrlib.tests.test_revisiontree',
3768
4056
        'bzrlib.tests.test_rio',
3769
4057
        'bzrlib.tests.test_rules',
 
4058
        'bzrlib.tests.test_url_policy_open',
3770
4059
        'bzrlib.tests.test_sampler',
 
4060
        'bzrlib.tests.test_scenarios',
3771
4061
        'bzrlib.tests.test_script',
3772
4062
        'bzrlib.tests.test_selftest',
3773
4063
        'bzrlib.tests.test_serializer',
3778
4068
        'bzrlib.tests.test_smart',
3779
4069
        'bzrlib.tests.test_smart_add',
3780
4070
        'bzrlib.tests.test_smart_request',
 
4071
        'bzrlib.tests.test_smart_signals',
3781
4072
        'bzrlib.tests.test_smart_transport',
3782
4073
        'bzrlib.tests.test_smtp_connection',
3783
4074
        'bzrlib.tests.test_source',
3789
4080
        'bzrlib.tests.test_switch',
3790
4081
        'bzrlib.tests.test_symbol_versioning',
3791
4082
        'bzrlib.tests.test_tag',
 
4083
        'bzrlib.tests.test_test_server',
3792
4084
        'bzrlib.tests.test_testament',
3793
4085
        'bzrlib.tests.test_textfile',
3794
4086
        'bzrlib.tests.test_textmerge',
 
4087
        'bzrlib.tests.test_cethread',
3795
4088
        'bzrlib.tests.test_timestamp',
3796
4089
        'bzrlib.tests.test_trace',
3797
4090
        'bzrlib.tests.test_transactions',
3800
4093
        'bzrlib.tests.test_transport_log',
3801
4094
        'bzrlib.tests.test_tree',
3802
4095
        'bzrlib.tests.test_treebuilder',
 
4096
        'bzrlib.tests.test_treeshape',
3803
4097
        'bzrlib.tests.test_tsort',
3804
4098
        'bzrlib.tests.test_tuned_gzip',
3805
4099
        'bzrlib.tests.test_ui',
3807
4101
        'bzrlib.tests.test_upgrade',
3808
4102
        'bzrlib.tests.test_upgrade_stacked',
3809
4103
        'bzrlib.tests.test_urlutils',
 
4104
        'bzrlib.tests.test_utextwrap',
3810
4105
        'bzrlib.tests.test_version',
3811
4106
        'bzrlib.tests.test_version_info',
 
4107
        'bzrlib.tests.test_versionedfile',
 
4108
        'bzrlib.tests.test_vf_search',
3812
4109
        'bzrlib.tests.test_weave',
3813
4110
        'bzrlib.tests.test_whitebox',
3814
4111
        'bzrlib.tests.test_win32utils',
3828
4125
        'bzrlib',
3829
4126
        'bzrlib.branchbuilder',
3830
4127
        'bzrlib.decorators',
3831
 
        'bzrlib.export',
3832
4128
        'bzrlib.inventory',
3833
4129
        'bzrlib.iterablefile',
3834
4130
        'bzrlib.lockdir',
3835
4131
        'bzrlib.merge3',
3836
4132
        'bzrlib.option',
 
4133
        'bzrlib.pyutils',
3837
4134
        'bzrlib.symbol_versioning',
3838
4135
        'bzrlib.tests',
 
4136
        'bzrlib.tests.fixtures',
3839
4137
        'bzrlib.timestamp',
 
4138
        'bzrlib.transport.http',
3840
4139
        'bzrlib.version_info_formats.format_custom',
3841
4140
        ]
3842
4141
 
3895
4194
        try:
3896
4195
            # note that this really does mean "report only" -- doctest
3897
4196
            # still runs the rest of the examples
3898
 
            doc_suite = doctest.DocTestSuite(mod,
3899
 
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4197
            doc_suite = IsolatedDocTestSuite(
 
4198
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3900
4199
        except ValueError, e:
3901
4200
            print '**failed to get doctest for: %s\n%s' % (mod, e)
3902
4201
            raise
3905
4204
        suite.addTest(doc_suite)
3906
4205
 
3907
4206
    default_encoding = sys.getdefaultencoding()
3908
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4207
    for name, plugin in _mod_plugin.plugins().items():
3909
4208
        if not interesting_module(plugin.module.__name__):
3910
4209
            continue
3911
4210
        plugin_suite = plugin.test_suite()
3917
4216
        if plugin_suite is not None:
3918
4217
            suite.addTest(plugin_suite)
3919
4218
        if default_encoding != sys.getdefaultencoding():
3920
 
            bzrlib.trace.warning(
 
4219
            trace.warning(
3921
4220
                'Plugin "%s" tried to reset default encoding to: %s', name,
3922
4221
                sys.getdefaultencoding())
3923
4222
            reload(sys)
3938
4237
            # Some tests mentioned in the list are not in the test suite. The
3939
4238
            # list may be out of date, report to the tester.
3940
4239
            for id in not_found:
3941
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4240
                trace.warning('"%s" not found in the test suite', id)
3942
4241
        for id in duplicates:
3943
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4242
            trace.warning('"%s" is used as an id by several tests', id)
3944
4243
 
3945
4244
    return suite
3946
4245
 
3947
4246
 
3948
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4247
def multiply_scenarios(*scenarios):
 
4248
    """Multiply two or more iterables of scenarios.
 
4249
 
 
4250
    It is safe to pass scenario generators or iterators.
 
4251
 
 
4252
    :returns: A list of compound scenarios: the cross-product of all 
 
4253
        scenarios, with the names concatenated and the parameters
 
4254
        merged together.
 
4255
    """
 
4256
    return reduce(_multiply_two_scenarios, map(list, scenarios))
 
4257
 
 
4258
 
 
4259
def _multiply_two_scenarios(scenarios_left, scenarios_right):
3949
4260
    """Multiply two sets of scenarios.
3950
4261
 
3951
4262
    :returns: the cartesian product of the two sets of scenarios, that is
3982
4293
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
3983
4294
    ...     [('one', dict(param=1)),
3984
4295
    ...      ('two', dict(param=2))],
3985
 
    ...     TestSuite())
 
4296
    ...     TestUtil.TestSuite())
3986
4297
    >>> tests = list(iter_suite_tests(r))
3987
4298
    >>> len(tests)
3988
4299
    2
4035
4346
    :param new_id: The id to assign to it.
4036
4347
    :return: The new test.
4037
4348
    """
4038
 
    new_test = copy(test)
 
4349
    new_test = copy.copy(test)
4039
4350
    new_test.id = lambda: new_id
 
4351
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4352
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4353
    # read the test output for parameterized tests, because tracebacks will be
 
4354
    # associated with irrelevant tests.
 
4355
    try:
 
4356
        details = new_test._TestCase__details
 
4357
    except AttributeError:
 
4358
        # must be a different version of testtools than expected.  Do nothing.
 
4359
        pass
 
4360
    else:
 
4361
        # Reset the '__details' dict.
 
4362
        new_test._TestCase__details = {}
4040
4363
    return new_test
4041
4364
 
4042
4365
 
4063
4386
        the module is available.
4064
4387
    """
4065
4388
 
4066
 
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4389
    from bzrlib.tests.features import ModuleAvailableFeature
 
4390
    py_module = pyutils.get_named_object(py_module_name)
4067
4391
    scenarios = [
4068
4392
        ('python', {'module': py_module}),
4069
4393
    ]
4102
4426
        if test_id != None:
4103
4427
            ui.ui_factory.clear_term()
4104
4428
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4429
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4430
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4431
                                    ).encode('ascii', 'replace')
4105
4432
        sys.stderr.write('Unable to remove testing dir %s\n%s'
4106
 
                         % (os.path.basename(dirname), e))
4107
 
 
4108
 
 
4109
 
class Feature(object):
4110
 
    """An operating system Feature."""
4111
 
 
4112
 
    def __init__(self):
4113
 
        self._available = None
4114
 
 
4115
 
    def available(self):
4116
 
        """Is the feature available?
4117
 
 
4118
 
        :return: True if the feature is available.
4119
 
        """
4120
 
        if self._available is None:
4121
 
            self._available = self._probe()
4122
 
        return self._available
4123
 
 
4124
 
    def _probe(self):
4125
 
        """Implement this method in concrete features.
4126
 
 
4127
 
        :return: True if the feature is available.
4128
 
        """
4129
 
        raise NotImplementedError
4130
 
 
4131
 
    def __str__(self):
4132
 
        if getattr(self, 'feature_name', None):
4133
 
            return self.feature_name()
4134
 
        return self.__class__.__name__
4135
 
 
4136
 
 
4137
 
class _SymlinkFeature(Feature):
4138
 
 
4139
 
    def _probe(self):
4140
 
        return osutils.has_symlinks()
4141
 
 
4142
 
    def feature_name(self):
4143
 
        return 'symlinks'
4144
 
 
4145
 
SymlinkFeature = _SymlinkFeature()
4146
 
 
4147
 
 
4148
 
class _HardlinkFeature(Feature):
4149
 
 
4150
 
    def _probe(self):
4151
 
        return osutils.has_hardlinks()
4152
 
 
4153
 
    def feature_name(self):
4154
 
        return 'hardlinks'
4155
 
 
4156
 
HardlinkFeature = _HardlinkFeature()
4157
 
 
4158
 
 
4159
 
class _OsFifoFeature(Feature):
4160
 
 
4161
 
    def _probe(self):
4162
 
        return getattr(os, 'mkfifo', None)
4163
 
 
4164
 
    def feature_name(self):
4165
 
        return 'filesystem fifos'
4166
 
 
4167
 
OsFifoFeature = _OsFifoFeature()
4168
 
 
4169
 
 
4170
 
class _UnicodeFilenameFeature(Feature):
4171
 
    """Does the filesystem support Unicode filenames?"""
4172
 
 
4173
 
    def _probe(self):
4174
 
        try:
4175
 
            # Check for character combinations unlikely to be covered by any
4176
 
            # single non-unicode encoding. We use the characters
4177
 
            # - greek small letter alpha (U+03B1) and
4178
 
            # - braille pattern dots-123456 (U+283F).
4179
 
            os.stat(u'\u03b1\u283f')
4180
 
        except UnicodeEncodeError:
4181
 
            return False
4182
 
        except (IOError, OSError):
4183
 
            # The filesystem allows the Unicode filename but the file doesn't
4184
 
            # exist.
4185
 
            return True
4186
 
        else:
4187
 
            # The filesystem allows the Unicode filename and the file exists,
4188
 
            # for some reason.
4189
 
            return True
4190
 
 
4191
 
UnicodeFilenameFeature = _UnicodeFilenameFeature()
4192
 
 
4193
 
 
4194
 
class _CompatabilityThunkFeature(Feature):
4195
 
    """This feature is just a thunk to another feature.
4196
 
 
4197
 
    It issues a deprecation warning if it is accessed, to let you know that you
4198
 
    should really use a different feature.
4199
 
    """
4200
 
 
4201
 
    def __init__(self, dep_version, module, name,
4202
 
                 replacement_name, replacement_module=None):
4203
 
        super(_CompatabilityThunkFeature, self).__init__()
4204
 
        self._module = module
4205
 
        if replacement_module is None:
4206
 
            replacement_module = module
4207
 
        self._replacement_module = replacement_module
4208
 
        self._name = name
4209
 
        self._replacement_name = replacement_name
4210
 
        self._dep_version = dep_version
4211
 
        self._feature = None
4212
 
 
4213
 
    def _ensure(self):
4214
 
        if self._feature is None:
4215
 
            depr_msg = self._dep_version % ('%s.%s'
4216
 
                                            % (self._module, self._name))
4217
 
            use_msg = ' Use %s.%s instead.' % (self._replacement_module,
4218
 
                                               self._replacement_name)
4219
 
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
4220
 
            # Import the new feature and use it as a replacement for the
4221
 
            # deprecated one.
4222
 
            mod = __import__(self._replacement_module, {}, {},
4223
 
                             [self._replacement_name])
4224
 
            self._feature = getattr(mod, self._replacement_name)
4225
 
 
4226
 
    def _probe(self):
4227
 
        self._ensure()
4228
 
        return self._feature._probe()
4229
 
 
4230
 
 
4231
 
class ModuleAvailableFeature(Feature):
4232
 
    """This is a feature than describes a module we want to be available.
4233
 
 
4234
 
    Declare the name of the module in __init__(), and then after probing, the
4235
 
    module will be available as 'self.module'.
4236
 
 
4237
 
    :ivar module: The module if it is available, else None.
4238
 
    """
4239
 
 
4240
 
    def __init__(self, module_name):
4241
 
        super(ModuleAvailableFeature, self).__init__()
4242
 
        self.module_name = module_name
4243
 
 
4244
 
    def _probe(self):
4245
 
        try:
4246
 
            self._module = __import__(self.module_name, {}, {}, [''])
4247
 
            return True
4248
 
        except ImportError:
4249
 
            return False
4250
 
 
4251
 
    @property
4252
 
    def module(self):
4253
 
        if self.available(): # Make sure the probe has been done
4254
 
            return self._module
4255
 
        return None
4256
 
 
4257
 
    def feature_name(self):
4258
 
        return self.module_name
4259
 
 
4260
 
 
4261
 
# This is kept here for compatibility, it is recommended to use
4262
 
# 'bzrlib.tests.feature.paramiko' instead
4263
 
ParamikoFeature = _CompatabilityThunkFeature(
4264
 
    deprecated_in((2,1,0)),
4265
 
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
 
4433
                         % (os.path.basename(dirname), printable_e))
4266
4434
 
4267
4435
 
4268
4436
def probe_unicode_in_user_encoding():
4298
4466
    return None
4299
4467
 
4300
4468
 
4301
 
class _HTTPSServerFeature(Feature):
4302
 
    """Some tests want an https Server, check if one is available.
4303
 
 
4304
 
    Right now, the only way this is available is under python2.6 which provides
4305
 
    an ssl module.
4306
 
    """
4307
 
 
4308
 
    def _probe(self):
4309
 
        try:
4310
 
            import ssl
4311
 
            return True
4312
 
        except ImportError:
4313
 
            return False
4314
 
 
4315
 
    def feature_name(self):
4316
 
        return 'HTTPSServer'
4317
 
 
4318
 
 
4319
 
HTTPSServerFeature = _HTTPSServerFeature()
4320
 
 
4321
 
 
4322
 
class _UnicodeFilename(Feature):
4323
 
    """Does the filesystem support Unicode filenames?"""
4324
 
 
4325
 
    def _probe(self):
4326
 
        try:
4327
 
            os.stat(u'\u03b1')
4328
 
        except UnicodeEncodeError:
4329
 
            return False
4330
 
        except (IOError, OSError):
4331
 
            # The filesystem allows the Unicode filename but the file doesn't
4332
 
            # exist.
4333
 
            return True
4334
 
        else:
4335
 
            # The filesystem allows the Unicode filename and the file exists,
4336
 
            # for some reason.
4337
 
            return True
4338
 
 
4339
 
UnicodeFilename = _UnicodeFilename()
4340
 
 
4341
 
 
4342
 
class _UTF8Filesystem(Feature):
4343
 
    """Is the filesystem UTF-8?"""
4344
 
 
4345
 
    def _probe(self):
4346
 
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
4347
 
            return True
4348
 
        return False
4349
 
 
4350
 
UTF8Filesystem = _UTF8Filesystem()
4351
 
 
4352
 
 
4353
 
class _BreakinFeature(Feature):
4354
 
    """Does this platform support the breakin feature?"""
4355
 
 
4356
 
    def _probe(self):
4357
 
        from bzrlib import breakin
4358
 
        if breakin.determine_signal() is None:
4359
 
            return False
4360
 
        if sys.platform == 'win32':
4361
 
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
4362
 
            # We trigger SIGBREAK via a Console api so we need ctypes to
4363
 
            # access the function
4364
 
            try:
4365
 
                import ctypes
4366
 
            except OSError:
4367
 
                return False
4368
 
        return True
4369
 
 
4370
 
    def feature_name(self):
4371
 
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
4372
 
 
4373
 
 
4374
 
BreakinFeature = _BreakinFeature()
4375
 
 
4376
 
 
4377
 
class _CaseInsCasePresFilenameFeature(Feature):
4378
 
    """Is the file-system case insensitive, but case-preserving?"""
4379
 
 
4380
 
    def _probe(self):
4381
 
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
4382
 
        try:
4383
 
            # first check truly case-preserving for created files, then check
4384
 
            # case insensitive when opening existing files.
4385
 
            name = osutils.normpath(name)
4386
 
            base, rel = osutils.split(name)
4387
 
            found_rel = osutils.canonical_relpath(base, name)
4388
 
            return (found_rel == rel
4389
 
                    and os.path.isfile(name.upper())
4390
 
                    and os.path.isfile(name.lower()))
4391
 
        finally:
4392
 
            os.close(fileno)
4393
 
            os.remove(name)
4394
 
 
4395
 
    def feature_name(self):
4396
 
        return "case-insensitive case-preserving filesystem"
4397
 
 
4398
 
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
4399
 
 
4400
 
 
4401
 
class _CaseInsensitiveFilesystemFeature(Feature):
4402
 
    """Check if underlying filesystem is case-insensitive but *not* case
4403
 
    preserving.
4404
 
    """
4405
 
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
4406
 
    # more likely to be case preserving, so this case is rare.
4407
 
 
4408
 
    def _probe(self):
4409
 
        if CaseInsCasePresFilenameFeature.available():
4410
 
            return False
4411
 
 
4412
 
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
4413
 
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
4414
 
            TestCaseWithMemoryTransport.TEST_ROOT = root
4415
 
        else:
4416
 
            root = TestCaseWithMemoryTransport.TEST_ROOT
4417
 
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
4418
 
            dir=root)
4419
 
        name_a = osutils.pathjoin(tdir, 'a')
4420
 
        name_A = osutils.pathjoin(tdir, 'A')
4421
 
        os.mkdir(name_a)
4422
 
        result = osutils.isdir(name_A)
4423
 
        _rmtree_temp_dir(tdir)
4424
 
        return result
4425
 
 
4426
 
    def feature_name(self):
4427
 
        return 'case-insensitive filesystem'
4428
 
 
4429
 
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
4430
 
 
4431
 
 
4432
 
class _CaseSensitiveFilesystemFeature(Feature):
4433
 
 
4434
 
    def _probe(self):
4435
 
        if CaseInsCasePresFilenameFeature.available():
4436
 
            return False
4437
 
        elif CaseInsensitiveFilesystemFeature.available():
4438
 
            return False
4439
 
        else:
4440
 
            return True
4441
 
 
4442
 
    def feature_name(self):
4443
 
        return 'case-sensitive filesystem'
4444
 
 
4445
 
# new coding style is for feature instances to be lowercase
4446
 
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
4447
 
 
4448
 
 
4449
 
# Kept for compatibility, use bzrlib.tests.features.subunit instead
4450
 
SubUnitFeature = _CompatabilityThunkFeature(
4451
 
    deprecated_in((2,1,0)),
4452
 
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
4453
4469
# Only define SubUnitBzrRunner if subunit is available.
4454
4470
try:
4455
4471
    from subunit import TestProtocolClient
4456
4472
    from subunit.test_results import AutoTimingTestResultDecorator
 
4473
    class SubUnitBzrProtocolClient(TestProtocolClient):
 
4474
 
 
4475
        def stopTest(self, test):
 
4476
            super(SubUnitBzrProtocolClient, self).stopTest(test)
 
4477
            _clear__type_equality_funcs(test)
 
4478
 
 
4479
        def addSuccess(self, test, details=None):
 
4480
            # The subunit client always includes the details in the subunit
 
4481
            # stream, but we don't want to include it in ours.
 
4482
            if details is not None and 'log' in details:
 
4483
                del details['log']
 
4484
            return super(SubUnitBzrProtocolClient, self).addSuccess(
 
4485
                test, details)
 
4486
 
4457
4487
    class SubUnitBzrRunner(TextTestRunner):
4458
4488
        def run(self, test):
4459
4489
            result = AutoTimingTestResultDecorator(
4460
 
                TestProtocolClient(self.stream))
 
4490
                SubUnitBzrProtocolClient(self.stream))
4461
4491
            test.run(result)
4462
4492
            return result
4463
4493
except ImportError:
4464
4494
    pass
4465
4495
 
4466
 
class _PosixPermissionsFeature(Feature):
4467
 
 
4468
 
    def _probe(self):
4469
 
        def has_perms():
4470
 
            # create temporary file and check if specified perms are maintained.
4471
 
            import tempfile
4472
 
 
4473
 
            write_perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
4474
 
            f = tempfile.mkstemp(prefix='bzr_perms_chk_')
4475
 
            fd, name = f
4476
 
            os.close(fd)
4477
 
            os.chmod(name, write_perms)
4478
 
 
4479
 
            read_perms = os.stat(name).st_mode & 0777
4480
 
            os.unlink(name)
4481
 
            return (write_perms == read_perms)
4482
 
 
4483
 
        return (os.name == 'posix') and has_perms()
4484
 
 
4485
 
    def feature_name(self):
4486
 
        return 'POSIX permissions support'
4487
 
 
4488
 
posix_permissions_feature = _PosixPermissionsFeature()
 
4496
 
 
4497
# API compatibility for old plugins; see bug 892622.
 
4498
for name in [
 
4499
    'Feature',
 
4500
    'HTTPServerFeature', 
 
4501
    'ModuleAvailableFeature',
 
4502
    'HTTPSServerFeature', 'SymlinkFeature', 'HardlinkFeature',
 
4503
    'OsFifoFeature', 'UnicodeFilenameFeature',
 
4504
    'ByteStringNamedFilesystem', 'UTF8Filesystem',
 
4505
    'BreakinFeature', 'CaseInsCasePresFilenameFeature',
 
4506
    'CaseInsensitiveFilesystemFeature', 'case_sensitive_filesystem_feature',
 
4507
    'posix_permissions_feature',
 
4508
    ]:
 
4509
    globals()[name] = _CompatabilityThunkFeature(
 
4510
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4511
        'bzrlib.tests', name,
 
4512
        name, 'bzrlib.tests.features')
 
4513
 
 
4514
 
 
4515
for (old_name, new_name) in [
 
4516
    ('UnicodeFilename', 'UnicodeFilenameFeature'),
 
4517
    ]:
 
4518
    globals()[name] = _CompatabilityThunkFeature(
 
4519
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4520
        'bzrlib.tests', old_name,
 
4521
        new_name, 'bzrlib.tests.features')