~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

Merge bzr.dev, update to use new hooks.

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)
24
 
 
25
19
# NOTE: Some classes in here use camelCaseNaming() rather than
26
20
# underscore_naming().  That's for consistency with unittest; it's not the
27
21
# general style of bzrlib.  Please continue that consistency when adding e.g.
42
36
import random
43
37
import re
44
38
import shlex
 
39
import site
45
40
import stat
46
41
import subprocess
47
42
import sys
55
50
import testtools
56
51
# nb: check this before importing anything else from within it
57
52
_testtools_version = getattr(testtools, '__version__', ())
58
 
if _testtools_version < (0, 9, 2):
59
 
    raise ImportError("need at least testtools 0.9.2: %s is %r"
 
53
if _testtools_version < (0, 9, 5):
 
54
    raise ImportError("need at least testtools 0.9.5: %s is %r"
60
55
        % (testtools.__file__, _testtools_version))
61
56
from testtools import content
62
57
 
 
58
import bzrlib
63
59
from bzrlib import (
64
60
    branchbuilder,
65
61
    bzrdir,
66
62
    chk_map,
 
63
    commands as _mod_commands,
67
64
    config,
 
65
    i18n,
68
66
    debug,
69
67
    errors,
70
68
    hooks,
71
69
    lock as _mod_lock,
 
70
    lockdir,
72
71
    memorytree,
73
72
    osutils,
 
73
    plugin as _mod_plugin,
74
74
    pyutils,
75
75
    ui,
76
76
    urlutils,
77
77
    registry,
 
78
    symbol_versioning,
 
79
    trace,
78
80
    transport as _mod_transport,
79
81
    workingtree,
80
82
    )
81
 
import bzrlib.branch
82
 
import bzrlib.commands
83
 
import bzrlib.timestamp
84
 
import bzrlib.export
85
 
import bzrlib.inventory
86
 
import bzrlib.iterablefile
87
 
import bzrlib.lockdir
88
83
try:
89
84
    import bzrlib.lsprof
90
85
except ImportError:
91
86
    # lsprof not available
92
87
    pass
93
 
from bzrlib.merge import merge_inner
94
 
import bzrlib.merge3
95
 
import bzrlib.plugin
96
 
from bzrlib.smart import client, request, server
97
 
import bzrlib.store
98
 
from bzrlib import symbol_versioning
 
88
from bzrlib.smart import client, request
 
89
from bzrlib.transport import (
 
90
    memory,
 
91
    pathfilter,
 
92
    )
99
93
from bzrlib.symbol_versioning import (
100
 
    DEPRECATED_PARAMETER,
101
94
    deprecated_function,
102
95
    deprecated_in,
103
 
    deprecated_method,
104
 
    deprecated_passed,
105
 
    )
106
 
import bzrlib.trace
107
 
from bzrlib.transport import (
108
 
    memory,
109
 
    pathfilter,
110
 
    )
111
 
from bzrlib.trace import mutter, note
 
96
    )
112
97
from bzrlib.tests import (
 
98
    fixtures,
113
99
    test_server,
114
100
    TestUtil,
115
101
    treeshape,
116
102
    )
117
103
from bzrlib.ui import NullProgressView
118
104
from bzrlib.ui.text import TextUIFactory
119
 
import bzrlib.version_info_formats.format_custom
120
 
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
 
105
from bzrlib.tests.features import _CompatabilityThunkFeature
121
106
 
122
107
# Mark this python module as being part of the implementation
123
108
# of unittest: this gives us better tracebacks where the last
140
125
TestSuite = TestUtil.TestSuite
141
126
TestLoader = TestUtil.TestLoader
142
127
 
 
128
# Tests should run in a clean and clearly defined environment. The goal is to
 
129
# keep them isolated from the running environment as mush as possible. The test
 
130
# framework ensures the variables defined below are set (or deleted if the
 
131
# value is None) before a test is run and reset to their original value after
 
132
# the test is run. Generally if some code depends on an environment variable,
 
133
# the tests should start without this variable in the environment. There are a
 
134
# few exceptions but you shouldn't violate this rule lightly.
 
135
isolated_environ = {
 
136
    'BZR_HOME': None,
 
137
    'HOME': None,
 
138
    # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
 
139
    # tests do check our impls match APPDATA
 
140
    'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
141
    'VISUAL': None,
 
142
    'EDITOR': None,
 
143
    'BZR_EMAIL': None,
 
144
    'BZREMAIL': None, # may still be present in the environment
 
145
    'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
 
146
    'BZR_PROGRESS_BAR': None,
 
147
    # This should trap leaks to ~/.bzr.log. This occurs when tests use TestCase
 
148
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
 
149
    # TestCase should not use disk resources, BZR_LOG is one.
 
150
    'BZR_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
151
    'BZR_PLUGIN_PATH': None,
 
152
    'BZR_DISABLE_PLUGINS': None,
 
153
    'BZR_PLUGINS_AT': None,
 
154
    'BZR_CONCURRENCY': None,
 
155
    # Make sure that any text ui tests are consistent regardless of
 
156
    # the environment the test case is run in; you may want tests that
 
157
    # test other combinations.  'dumb' is a reasonable guess for tests
 
158
    # going to a pipe or a StringIO.
 
159
    'TERM': 'dumb',
 
160
    'LINES': '25',
 
161
    'COLUMNS': '80',
 
162
    'BZR_COLUMNS': '80',
 
163
    # Disable SSH Agent
 
164
    'SSH_AUTH_SOCK': None,
 
165
    # Proxies
 
166
    'http_proxy': None,
 
167
    'HTTP_PROXY': None,
 
168
    'https_proxy': None,
 
169
    'HTTPS_PROXY': None,
 
170
    'no_proxy': None,
 
171
    'NO_PROXY': None,
 
172
    'all_proxy': None,
 
173
    'ALL_PROXY': None,
 
174
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
175
    # least. If you do (care), please update this comment
 
176
    # -- vila 20080401
 
177
    'ftp_proxy': None,
 
178
    'FTP_PROXY': None,
 
179
    'BZR_REMOTE_PATH': None,
 
180
    # Generally speaking, we don't want apport reporting on crashes in
 
181
    # the test envirnoment unless we're specifically testing apport,
 
182
    # so that it doesn't leak into the real system environment.  We
 
183
    # use an env var so it propagates to subprocesses.
 
184
    'APPORT_DISABLE': '1',
 
185
    }
 
186
 
 
187
 
 
188
def override_os_environ(test, env=None):
 
189
    """Modify os.environ keeping a copy.
 
190
    
 
191
    :param test: A test instance
 
192
 
 
193
    :param env: A dict containing variable definitions to be installed
 
194
    """
 
195
    if env is None:
 
196
        env = isolated_environ
 
197
    test._original_os_environ = dict([(var, value)
 
198
                                      for var, value in os.environ.iteritems()])
 
199
    for var, value in env.iteritems():
 
200
        osutils.set_or_unset_env(var, value)
 
201
        if var not in test._original_os_environ:
 
202
            # The var is new, add it with a value of None, so
 
203
            # restore_os_environ will delete it
 
204
            test._original_os_environ[var] = None
 
205
 
 
206
 
 
207
def restore_os_environ(test):
 
208
    """Restore os.environ to its original state.
 
209
 
 
210
    :param test: A test instance previously passed to override_os_environ.
 
211
    """
 
212
    for var, value in test._original_os_environ.iteritems():
 
213
        # Restore the original value (or delete it if the value has been set to
 
214
        # None in override_os_environ).
 
215
        osutils.set_or_unset_env(var, value)
 
216
 
 
217
 
 
218
def _clear__type_equality_funcs(test):
 
219
    """Cleanup bound methods stored on TestCase instances
 
220
 
 
221
    Clear the dict breaking a few (mostly) harmless cycles in the affected
 
222
    unittests released with Python 2.6 and initial Python 2.7 versions.
 
223
 
 
224
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
 
225
    shipped in Oneiric, an object with no clear method was used, hence the
 
226
    extra complications, see bug 809048 for details.
 
227
    """
 
228
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
229
    if type_equality_funcs is not None:
 
230
        tef_clear = getattr(type_equality_funcs, "clear", None)
 
231
        if tef_clear is None:
 
232
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
 
233
            if tef_instance_dict is not None:
 
234
                tef_clear = tef_instance_dict.clear
 
235
        if tef_clear is not None:
 
236
            tef_clear()
 
237
 
 
238
 
143
239
class ExtendedTestResult(testtools.TextTestResult):
144
240
    """Accepts, reports and accumulates the results of running tests.
145
241
 
196
292
        self._strict = strict
197
293
        self._first_thread_leaker_id = None
198
294
        self._tests_leaking_threads_count = 0
 
295
        self._traceback_from_test = None
199
296
 
200
297
    def stopTestRun(self):
201
298
        run = self.testsRun
261
358
 
262
359
    def _elapsedTestTimeString(self):
263
360
        """Return a time string for the overall time the current test has taken."""
264
 
        return self._formatTime(time.time() - self._start_time)
 
361
        return self._formatTime(self._delta_to_float(
 
362
            self._now() - self._start_datetime))
265
363
 
266
364
    def _testTimeString(self, testCase):
267
365
        benchmark_time = self._extractBenchmarkTime(testCase)
281
379
        what = re.sub(r'^bzrlib\.tests\.', '', what)
282
380
        return what
283
381
 
 
382
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
383
    #                multiple times in a row, because the handler is added for
 
384
    #                each test but the container list is shared between cases.
 
385
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
386
    def _record_traceback_from_test(self, exc_info):
 
387
        """Store the traceback from passed exc_info tuple till"""
 
388
        self._traceback_from_test = exc_info[2]
 
389
 
284
390
    def startTest(self, test):
285
391
        super(ExtendedTestResult, self).startTest(test)
286
392
        if self.count == 0:
289
395
        self.report_test_start(test)
290
396
        test.number = self.count
291
397
        self._recordTestStartTime()
292
 
        # Only check for thread leaks if the test case supports cleanups
293
 
        addCleanup = getattr(test, "addCleanup", None)
294
 
        if addCleanup is not None:
295
 
            addCleanup(self._check_leaked_threads, test)
 
398
        # Make testtools cases give us the real traceback on failure
 
399
        addOnException = getattr(test, "addOnException", None)
 
400
        if addOnException is not None:
 
401
            addOnException(self._record_traceback_from_test)
 
402
        # Only check for thread leaks on bzrlib derived test cases
 
403
        if isinstance(test, TestCase):
 
404
            test.addCleanup(self._check_leaked_threads, test)
 
405
 
 
406
    def stopTest(self, test):
 
407
        super(ExtendedTestResult, self).stopTest(test)
 
408
        # Manually break cycles, means touching various private things but hey
 
409
        getDetails = getattr(test, "getDetails", None)
 
410
        if getDetails is not None:
 
411
            getDetails().clear()
 
412
        _clear__type_equality_funcs(test)
 
413
        self._traceback_from_test = None
296
414
 
297
415
    def startTests(self):
298
416
        self.report_tests_starting()
316
434
 
317
435
    def _recordTestStartTime(self):
318
436
        """Record that a test has started."""
319
 
        self._start_time = time.time()
 
437
        self._start_datetime = self._now()
320
438
 
321
439
    def addError(self, test, err):
322
440
        """Tell result that test finished with an error.
324
442
        Called from the TestCase run() method when the test
325
443
        fails with an unexpected error.
326
444
        """
327
 
        self._post_mortem()
 
445
        self._post_mortem(self._traceback_from_test)
328
446
        super(ExtendedTestResult, self).addError(test, err)
329
447
        self.error_count += 1
330
448
        self.report_error(test, err)
337
455
        Called from the TestCase run() method when the test
338
456
        fails because e.g. an assert() method failed.
339
457
        """
340
 
        self._post_mortem()
 
458
        self._post_mortem(self._traceback_from_test)
341
459
        super(ExtendedTestResult, self).addFailure(test, err)
342
460
        self.failure_count += 1
343
461
        self.report_failure(test, err)
363
481
        self.known_failure_count += 1
364
482
        self.report_known_failure(test, err)
365
483
 
 
484
    def addUnexpectedSuccess(self, test, details=None):
 
485
        """Tell result the test unexpectedly passed, counting as a failure
 
486
 
 
487
        When the minimum version of testtools required becomes 0.9.8 this
 
488
        can be updated to use the new handling there.
 
489
        """
 
490
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
491
        self.failure_count += 1
 
492
        self.report_unexpected_success(test,
 
493
            "".join(details["reason"].iter_text()))
 
494
        if self.stop_early:
 
495
            self.stop()
 
496
 
366
497
    def addNotSupported(self, test, feature):
367
498
        """The test will not be run because of a missing feature.
368
499
        """
385
516
        self.not_applicable_count += 1
386
517
        self.report_not_applicable(test, reason)
387
518
 
388
 
    def _post_mortem(self):
 
519
    def _count_stored_tests(self):
 
520
        """Count of tests instances kept alive due to not succeeding"""
 
521
        return self.error_count + self.failure_count + self.known_failure_count
 
522
 
 
523
    def _post_mortem(self, tb=None):
389
524
        """Start a PDB post mortem session."""
390
525
        if os.environ.get('BZR_TEST_PDB', None):
391
 
            import pdb;pdb.post_mortem()
 
526
            import pdb
 
527
            pdb.post_mortem(tb)
392
528
 
393
529
    def progress(self, offset, whence):
394
530
        """The test is adjusting the count of tests to run."""
526
662
    def report_known_failure(self, test, err):
527
663
        pass
528
664
 
 
665
    def report_unexpected_success(self, test, reason):
 
666
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
 
667
            self._test_description(test),
 
668
            "Unexpected success. Should have failed",
 
669
            reason,
 
670
            ))
 
671
 
529
672
    def report_skip(self, test, reason):
530
673
        pass
531
674
 
583
726
                % (self._testTimeString(test),
584
727
                   self._error_summary(err)))
585
728
 
 
729
    def report_unexpected_success(self, test, reason):
 
730
        self.stream.write(' FAIL %s\n%s: %s\n'
 
731
                % (self._testTimeString(test),
 
732
                   "Unexpected success. Should have failed",
 
733
                   reason))
 
734
 
586
735
    def report_success(self, test):
587
736
        self.stream.write('   OK %s\n' % self._testTimeString(test))
588
737
        for bench_called, stats in getattr(test, '_benchcalls', []):
635
784
            encode = codec[0]
636
785
        else:
637
786
            encode = codec.encode
638
 
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream)
 
787
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
788
        #                so should swap to the plain codecs.StreamWriter
 
789
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
790
            "backslashreplace")
639
791
        stream.encoding = new_encoding
640
792
        self.stream = stream
641
793
        self.descriptions = descriptions
791
943
        return NullProgressView()
792
944
 
793
945
 
 
946
def isolated_doctest_setUp(test):
 
947
    override_os_environ(test)
 
948
 
 
949
 
 
950
def isolated_doctest_tearDown(test):
 
951
    restore_os_environ(test)
 
952
 
 
953
 
 
954
def IsolatedDocTestSuite(*args, **kwargs):
 
955
    """Overrides doctest.DocTestSuite to handle isolation.
 
956
 
 
957
    The method is really a factory and users are expected to use it as such.
 
958
    """
 
959
 
 
960
    kwargs['setUp'] = isolated_doctest_setUp
 
961
    kwargs['tearDown'] = isolated_doctest_tearDown
 
962
    return doctest.DocTestSuite(*args, **kwargs)
 
963
 
 
964
 
794
965
class TestCase(testtools.TestCase):
795
966
    """Base class for bzr unit tests.
796
967
 
826
997
 
827
998
    def setUp(self):
828
999
        super(TestCase, self).setUp()
 
1000
 
 
1001
        timeout = config.GlobalStack().get('selftest.timeout')
 
1002
        if timeout:
 
1003
            timeout_fixture = fixtures.TimeoutFixture(timeout)
 
1004
            timeout_fixture.setUp()
 
1005
            self.addCleanup(timeout_fixture.cleanUp)
 
1006
 
829
1007
        for feature in getattr(self, '_test_needs_features', []):
830
1008
            self.requireFeature(feature)
831
 
        self._log_contents = None
832
 
        self.addDetail("log", content.Content(content.ContentType("text",
833
 
            "plain", {"charset": "utf8"}),
834
 
            lambda:[self._get_log(keep_log_file=True)]))
835
1009
        self._cleanEnvironment()
 
1010
 
 
1011
        if bzrlib.global_state is not None:
 
1012
            self.overrideAttr(bzrlib.global_state, 'cmdline_overrides',
 
1013
                              config.CommandLineStore())
 
1014
 
836
1015
        self._silenceUI()
837
1016
        self._startLogFile()
838
1017
        self._benchcalls = []
841
1020
        self._track_transports()
842
1021
        self._track_locks()
843
1022
        self._clear_debug_flags()
 
1023
        # Isolate global verbosity level, to make sure it's reproducible
 
1024
        # between tests.  We should get rid of this altogether: bug 656694. --
 
1025
        # mbp 20101008
 
1026
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
 
1027
        # Isolate config option expansion until its default value for bzrlib is
 
1028
        # settled on or a the FIXME associated with _get_expand_default_value
 
1029
        # is addressed -- vila 20110219
 
1030
        self.overrideAttr(config, '_expand_default_value', None)
 
1031
        self._log_files = set()
 
1032
        # Each key in the ``_counters`` dict holds a value for a different
 
1033
        # counter. When the test ends, addDetail() should be used to output the
 
1034
        # counter values. This happens in install_counter_hook().
 
1035
        self._counters = {}
 
1036
        if 'config_stats' in selftest_debug_flags:
 
1037
            self._install_config_stats_hooks()
 
1038
        # Do not use i18n for tests (unless the test reverses this)
 
1039
        i18n.disable_i18n()
844
1040
 
845
1041
    def debug(self):
846
1042
        # debug a frame up.
847
1043
        import pdb
848
 
        pdb.Pdb().set_trace(sys._getframe().f_back)
 
1044
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
1045
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
1046
                ).set_trace(sys._getframe().f_back)
849
1047
 
850
1048
    def discardDetail(self, name):
851
1049
        """Extend the addDetail, getDetails api so we can remove a detail.
863
1061
        if name in details:
864
1062
            del details[name]
865
1063
 
 
1064
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1065
        """Install a counting hook.
 
1066
 
 
1067
        Any hook can be counted as long as it doesn't need to return a value.
 
1068
 
 
1069
        :param hooks: Where the hook should be installed.
 
1070
 
 
1071
        :param name: The hook name that will be counted.
 
1072
 
 
1073
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1074
            to ``name``.
 
1075
        """
 
1076
        _counters = self._counters # Avoid closing over self
 
1077
        if counter_name is None:
 
1078
            counter_name = name
 
1079
        if _counters.has_key(counter_name):
 
1080
            raise AssertionError('%s is already used as a counter name'
 
1081
                                  % (counter_name,))
 
1082
        _counters[counter_name] = 0
 
1083
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1084
            lambda: ['%d' % (_counters[counter_name],)]))
 
1085
        def increment_counter(*args, **kwargs):
 
1086
            _counters[counter_name] += 1
 
1087
        label = 'count %s calls' % (counter_name,)
 
1088
        hooks.install_named_hook(name, increment_counter, label)
 
1089
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1090
 
 
1091
    def _install_config_stats_hooks(self):
 
1092
        """Install config hooks to count hook calls.
 
1093
 
 
1094
        """
 
1095
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1096
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1097
                                       'config.%s' % (hook_name,))
 
1098
 
 
1099
        # The OldConfigHooks are private and need special handling to protect
 
1100
        # against recursive tests (tests that run other tests), so we just do
 
1101
        # manually what registering them into _builtin_known_hooks will provide
 
1102
        # us.
 
1103
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1104
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1105
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1106
                                      'old_config.%s' % (hook_name,))
 
1107
 
866
1108
    def _clear_debug_flags(self):
867
1109
        """Prevent externally set debug flags affecting tests.
868
1110
 
883
1125
        for key, (parent, name) in known_hooks.iter_parent_objects():
884
1126
            current_hooks = getattr(parent, name)
885
1127
            self._preserved_hooks[parent] = (name, current_hooks)
 
1128
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1129
        hooks._lazy_hooks = {}
886
1130
        self.addCleanup(self._restoreHooks)
887
1131
        for key, (parent, name) in known_hooks.iter_parent_objects():
888
1132
            factory = known_hooks.get(key)
920
1164
        # break some locks on purpose and should be taken into account by
921
1165
        # considering that breaking a lock is just a dirty way of releasing it.
922
1166
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
923
 
            message = ('Different number of acquired and '
924
 
                       'released or broken locks. (%s, %s + %s)' %
925
 
                       (acquired_locks, released_locks, broken_locks))
 
1167
            message = (
 
1168
                'Different number of acquired and '
 
1169
                'released or broken locks.\n'
 
1170
                'acquired=%s\n'
 
1171
                'released=%s\n'
 
1172
                'broken=%s\n' %
 
1173
                (acquired_locks, released_locks, broken_locks))
926
1174
            if not self._lock_check_thorough:
927
1175
                # Rather than fail, just warn
928
1176
                print "Broken test %s: %s" % (self, message)
956
1204
 
957
1205
    def permit_dir(self, name):
958
1206
        """Permit a directory to be used by this test. See permit_url."""
959
 
        name_transport = _mod_transport.get_transport(name)
 
1207
        name_transport = _mod_transport.get_transport_from_path(name)
960
1208
        self.permit_url(name)
961
1209
        self.permit_url(name_transport.base)
962
1210
 
1041
1289
        self.addCleanup(transport_server.stop_server)
1042
1290
        # Obtain a real transport because if the server supplies a password, it
1043
1291
        # will be hidden from the base on the client side.
1044
 
        t = _mod_transport.get_transport(transport_server.get_url())
 
1292
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1045
1293
        # Some transport servers effectively chroot the backing transport;
1046
1294
        # others like SFTPServer don't - users of the transport can walk up the
1047
1295
        # transport to read the entire backing transport. This wouldn't matter
1103
1351
        except UnicodeError, e:
1104
1352
            # If we can't compare without getting a UnicodeError, then
1105
1353
            # obviously they are different
1106
 
            mutter('UnicodeError: %s', e)
 
1354
            trace.mutter('UnicodeError: %s', e)
1107
1355
        if message:
1108
1356
            message += '\n'
1109
1357
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1148
1396
                         'st_mtime did not match')
1149
1397
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1150
1398
                         'st_ctime did not match')
1151
 
        if sys.platform != 'win32':
 
1399
        if sys.platform == 'win32':
1152
1400
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1153
1401
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
1154
 
            # odd. Regardless we shouldn't actually try to assert anything
1155
 
            # about their values
 
1402
            # odd. We just force it to always be 0 to avoid any problems.
 
1403
            self.assertEqual(0, expected.st_dev)
 
1404
            self.assertEqual(0, actual.st_dev)
 
1405
            self.assertEqual(0, expected.st_ino)
 
1406
            self.assertEqual(0, actual.st_ino)
 
1407
        else:
1156
1408
            self.assertEqual(expected.st_dev, actual.st_dev,
1157
1409
                             'st_dev did not match')
1158
1410
            self.assertEqual(expected.st_ino, actual.st_ino,
1167
1419
                length, len(obj_with_len), obj_with_len))
1168
1420
 
1169
1421
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1170
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1422
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1171
1423
        """
1172
 
        from bzrlib import trace
1173
1424
        captured = []
1174
1425
        orig_log_exception_quietly = trace.log_exception_quietly
1175
1426
        try:
1176
1427
            def capture():
1177
1428
                orig_log_exception_quietly()
1178
 
                captured.append(sys.exc_info())
 
1429
                captured.append(sys.exc_info()[1])
1179
1430
            trace.log_exception_quietly = capture
1180
1431
            func(*args, **kwargs)
1181
1432
        finally:
1182
1433
            trace.log_exception_quietly = orig_log_exception_quietly
1183
1434
        self.assertLength(1, captured)
1184
 
        err = captured[0][1]
 
1435
        err = captured[0]
1185
1436
        self.assertIsInstance(err, exception_class)
1186
1437
        return err
1187
1438
 
1224
1475
        if haystack.find(needle) == -1:
1225
1476
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1226
1477
 
 
1478
    def assertNotContainsString(self, haystack, needle):
 
1479
        if haystack.find(needle) != -1:
 
1480
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1481
 
1227
1482
    def assertSubset(self, sublist, superlist):
1228
1483
        """Assert that every entry in sublist is present in superlist."""
1229
1484
        missing = set(sublist) - set(superlist)
1318
1573
 
1319
1574
    def assertFileEqual(self, content, path):
1320
1575
        """Fail if path does not contain 'content'."""
1321
 
        self.failUnlessExists(path)
 
1576
        self.assertPathExists(path)
1322
1577
        f = file(path, 'rb')
1323
1578
        try:
1324
1579
            s = f.read()
1334
1589
        else:
1335
1590
            self.assertEqual(expected_docstring, obj.__doc__)
1336
1591
 
 
1592
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1337
1593
    def failUnlessExists(self, path):
 
1594
        return self.assertPathExists(path)
 
1595
 
 
1596
    def assertPathExists(self, path):
1338
1597
        """Fail unless path or paths, which may be abs or relative, exist."""
1339
1598
        if not isinstance(path, basestring):
1340
1599
            for p in path:
1341
 
                self.failUnlessExists(p)
 
1600
                self.assertPathExists(p)
1342
1601
        else:
1343
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1602
            self.assertTrue(osutils.lexists(path),
 
1603
                path + " does not exist")
1344
1604
 
 
1605
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1345
1606
    def failIfExists(self, path):
 
1607
        return self.assertPathDoesNotExist(path)
 
1608
 
 
1609
    def assertPathDoesNotExist(self, path):
1346
1610
        """Fail if path or paths, which may be abs or relative, exist."""
1347
1611
        if not isinstance(path, basestring):
1348
1612
            for p in path:
1349
 
                self.failIfExists(p)
 
1613
                self.assertPathDoesNotExist(p)
1350
1614
        else:
1351
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1615
            self.assertFalse(osutils.lexists(path),
 
1616
                path + " exists")
1352
1617
 
1353
1618
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1354
1619
        """A helper for callDeprecated and applyDeprecated.
1380
1645
        not other callers that go direct to the warning module.
1381
1646
 
1382
1647
        To test that a deprecated method raises an error, do something like
1383
 
        this::
 
1648
        this (remember that both assertRaises and applyDeprecated delays *args
 
1649
        and **kwargs passing)::
1384
1650
 
1385
1651
            self.assertRaises(errors.ReservedId,
1386
1652
                self.applyDeprecated,
1464
1730
        return result
1465
1731
 
1466
1732
    def _startLogFile(self):
1467
 
        """Send bzr and test log messages to a temporary file.
1468
 
 
1469
 
        The file is removed as the test is torn down.
1470
 
        """
1471
 
        self._log_file = StringIO()
1472
 
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
 
1733
        """Setup a in-memory target for bzr and testcase log messages"""
 
1734
        pseudo_log_file = StringIO()
 
1735
        def _get_log_contents_for_weird_testtools_api():
 
1736
            return [pseudo_log_file.getvalue().decode(
 
1737
                "utf-8", "replace").encode("utf-8")]
 
1738
        self.addDetail("log", content.Content(content.ContentType("text",
 
1739
            "plain", {"charset": "utf8"}),
 
1740
            _get_log_contents_for_weird_testtools_api))
 
1741
        self._log_file = pseudo_log_file
 
1742
        self._log_memento = trace.push_log_file(self._log_file)
1473
1743
        self.addCleanup(self._finishLogFile)
1474
1744
 
1475
1745
    def _finishLogFile(self):
1476
 
        """Finished with the log file.
1477
 
 
1478
 
        Close the file and delete it, unless setKeepLogfile was called.
1479
 
        """
1480
 
        if bzrlib.trace._trace_file:
 
1746
        """Flush and dereference the in-memory log for this testcase"""
 
1747
        if trace._trace_file:
1481
1748
            # flush the log file, to get all content
1482
 
            bzrlib.trace._trace_file.flush()
1483
 
        bzrlib.trace.pop_log_file(self._log_memento)
1484
 
        # Cache the log result and delete the file on disk
1485
 
        self._get_log(False)
 
1749
            trace._trace_file.flush()
 
1750
        trace.pop_log_file(self._log_memento)
 
1751
        # The logging module now tracks references for cleanup so discard ours
 
1752
        del self._log_memento
1486
1753
 
1487
1754
    def thisFailsStrictLockCheck(self):
1488
1755
        """It is known that this test would fail with -Dstrict_locks.
1500
1767
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1501
1768
        """Overrides an object attribute restoring it after the test.
1502
1769
 
 
1770
        :note: This should be used with discretion; you should think about
 
1771
        whether it's better to make the code testable without monkey-patching.
 
1772
 
1503
1773
        :param obj: The object that will be mutated.
1504
1774
 
1505
1775
        :param attr_name: The attribute name we want to preserve/override in
1516
1786
            setattr(obj, attr_name, new)
1517
1787
        return value
1518
1788
 
 
1789
    def overrideEnv(self, name, new):
 
1790
        """Set an environment variable, and reset it after the test.
 
1791
 
 
1792
        :param name: The environment variable name.
 
1793
 
 
1794
        :param new: The value to set the variable to. If None, the 
 
1795
            variable is deleted from the environment.
 
1796
 
 
1797
        :returns: The actual variable value.
 
1798
        """
 
1799
        value = osutils.set_or_unset_env(name, new)
 
1800
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1801
        return value
 
1802
 
 
1803
    def recordCalls(self, obj, attr_name):
 
1804
        """Monkeypatch in a wrapper that will record calls.
 
1805
 
 
1806
        The monkeypatch is automatically removed when the test concludes.
 
1807
 
 
1808
        :param obj: The namespace holding the reference to be replaced;
 
1809
            typically a module, class, or object.
 
1810
        :param attr_name: A string for the name of the attribute to 
 
1811
            patch.
 
1812
        :returns: A list that will be extended with one item every time the
 
1813
            function is called, with a tuple of (args, kwargs).
 
1814
        """
 
1815
        calls = []
 
1816
 
 
1817
        def decorator(*args, **kwargs):
 
1818
            calls.append((args, kwargs))
 
1819
            return orig(*args, **kwargs)
 
1820
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1821
        return calls
 
1822
 
1519
1823
    def _cleanEnvironment(self):
1520
 
        new_env = {
1521
 
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1522
 
            'HOME': os.getcwd(),
1523
 
            # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1524
 
            # tests do check our impls match APPDATA
1525
 
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
1526
 
            'VISUAL': None,
1527
 
            'EDITOR': None,
1528
 
            'BZR_EMAIL': None,
1529
 
            'BZREMAIL': None, # may still be present in the environment
1530
 
            'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
1531
 
            'BZR_PROGRESS_BAR': None,
1532
 
            'BZR_LOG': None,
1533
 
            'BZR_PLUGIN_PATH': None,
1534
 
            'BZR_DISABLE_PLUGINS': None,
1535
 
            'BZR_PLUGINS_AT': None,
1536
 
            'BZR_CONCURRENCY': None,
1537
 
            # Make sure that any text ui tests are consistent regardless of
1538
 
            # the environment the test case is run in; you may want tests that
1539
 
            # test other combinations.  'dumb' is a reasonable guess for tests
1540
 
            # going to a pipe or a StringIO.
1541
 
            'TERM': 'dumb',
1542
 
            'LINES': '25',
1543
 
            'COLUMNS': '80',
1544
 
            'BZR_COLUMNS': '80',
1545
 
            # SSH Agent
1546
 
            'SSH_AUTH_SOCK': None,
1547
 
            # Proxies
1548
 
            'http_proxy': None,
1549
 
            'HTTP_PROXY': None,
1550
 
            'https_proxy': None,
1551
 
            'HTTPS_PROXY': None,
1552
 
            'no_proxy': None,
1553
 
            'NO_PROXY': None,
1554
 
            'all_proxy': None,
1555
 
            'ALL_PROXY': None,
1556
 
            # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1557
 
            # least. If you do (care), please update this comment
1558
 
            # -- vila 20080401
1559
 
            'ftp_proxy': None,
1560
 
            'FTP_PROXY': None,
1561
 
            'BZR_REMOTE_PATH': None,
1562
 
            # Generally speaking, we don't want apport reporting on crashes in
1563
 
            # the test envirnoment unless we're specifically testing apport,
1564
 
            # so that it doesn't leak into the real system environment.  We
1565
 
            # use an env var so it propagates to subprocesses.
1566
 
            'APPORT_DISABLE': '1',
1567
 
        }
1568
 
        self._old_env = {}
1569
 
        self.addCleanup(self._restoreEnvironment)
1570
 
        for name, value in new_env.iteritems():
1571
 
            self._captureVar(name, value)
1572
 
 
1573
 
    def _captureVar(self, name, newvalue):
1574
 
        """Set an environment variable, and reset it when finished."""
1575
 
        self._old_env[name] = osutils.set_or_unset_env(name, newvalue)
1576
 
 
1577
 
    def _restoreEnvironment(self):
1578
 
        for name, value in self._old_env.iteritems():
1579
 
            osutils.set_or_unset_env(name, value)
 
1824
        for name, value in isolated_environ.iteritems():
 
1825
            self.overrideEnv(name, value)
1580
1826
 
1581
1827
    def _restoreHooks(self):
1582
1828
        for klass, (name, hooks) in self._preserved_hooks.items():
1583
1829
            setattr(klass, name, hooks)
 
1830
        self._preserved_hooks.clear()
 
1831
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1832
        self._preserved_lazy_hooks.clear()
1584
1833
 
1585
1834
    def knownFailure(self, reason):
1586
 
        """This test has failed for some known reason."""
1587
 
        raise KnownFailure(reason)
 
1835
        """Declare that this test fails for a known reason
 
1836
 
 
1837
        Tests that are known to fail should generally be using expectedFailure
 
1838
        with an appropriate reverse assertion if a change could cause the test
 
1839
        to start passing. Conversely if the test has no immediate prospect of
 
1840
        succeeding then using skip is more suitable.
 
1841
 
 
1842
        When this method is called while an exception is being handled, that
 
1843
        traceback will be used, otherwise a new exception will be thrown to
 
1844
        provide one but won't be reported.
 
1845
        """
 
1846
        self._add_reason(reason)
 
1847
        try:
 
1848
            exc_info = sys.exc_info()
 
1849
            if exc_info != (None, None, None):
 
1850
                self._report_traceback(exc_info)
 
1851
            else:
 
1852
                try:
 
1853
                    raise self.failureException(reason)
 
1854
                except self.failureException:
 
1855
                    exc_info = sys.exc_info()
 
1856
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1857
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1858
        finally:
 
1859
            del exc_info
1588
1860
 
1589
1861
    def _suppress_log(self):
1590
1862
        """Remove the log info from details."""
1676
1948
            self._benchtime += time.time() - start
1677
1949
 
1678
1950
    def log(self, *args):
1679
 
        mutter(*args)
1680
 
 
1681
 
    def _get_log(self, keep_log_file=False):
1682
 
        """Internal helper to get the log from bzrlib.trace for this test.
1683
 
 
1684
 
        Please use self.getDetails, or self.get_log to access this in test case
1685
 
        code.
1686
 
 
1687
 
        :param keep_log_file: When True, if the log is still a file on disk
1688
 
            leave it as a file on disk. When False, if the log is still a file
1689
 
            on disk, the log file is deleted and the log preserved as
1690
 
            self._log_contents.
1691
 
        :return: A string containing the log.
1692
 
        """
1693
 
        if self._log_contents is not None:
1694
 
            try:
1695
 
                self._log_contents.decode('utf8')
1696
 
            except UnicodeDecodeError:
1697
 
                unicodestr = self._log_contents.decode('utf8', 'replace')
1698
 
                self._log_contents = unicodestr.encode('utf8')
1699
 
            return self._log_contents
1700
 
        if self._log_file is not None:
1701
 
            log_contents = self._log_file.getvalue()
1702
 
            try:
1703
 
                log_contents.decode('utf8')
1704
 
            except UnicodeDecodeError:
1705
 
                unicodestr = log_contents.decode('utf8', 'replace')
1706
 
                log_contents = unicodestr.encode('utf8')
1707
 
            if not keep_log_file:
1708
 
                self._log_file = None
1709
 
                # Permit multiple calls to get_log until we clean it up in
1710
 
                # finishLogFile
1711
 
                self._log_contents = log_contents
1712
 
            return log_contents
1713
 
        else:
1714
 
            return "No log file content."
 
1951
        trace.mutter(*args)
1715
1952
 
1716
1953
    def get_log(self):
1717
1954
        """Get a unicode string containing the log from bzrlib.trace.
1753
1990
 
1754
1991
        self.log('run bzr: %r', args)
1755
1992
        # FIXME: don't call into logging here
1756
 
        handler = logging.StreamHandler(stderr)
1757
 
        handler.setLevel(logging.INFO)
 
1993
        handler = trace.EncodedStreamHandler(stderr, errors="replace",
 
1994
            level=logging.INFO)
1758
1995
        logger = logging.getLogger('')
1759
1996
        logger.addHandler(handler)
1760
1997
        old_ui_factory = ui.ui_factory
1767
2004
 
1768
2005
        try:
1769
2006
            try:
1770
 
                result = self.apply_redirected(ui.ui_factory.stdin,
 
2007
                result = self.apply_redirected(
 
2008
                    ui.ui_factory.stdin,
1771
2009
                    stdout, stderr,
1772
 
                    bzrlib.commands.run_bzr_catch_user_errors,
 
2010
                    _mod_commands.run_bzr_catch_user_errors,
1773
2011
                    args)
1774
2012
            except KeyboardInterrupt:
1775
2013
                # Reraise KeyboardInterrupt with contents of redirected stdout
1917
2155
    def start_bzr_subprocess(self, process_args, env_changes=None,
1918
2156
                             skip_if_plan_to_signal=False,
1919
2157
                             working_dir=None,
1920
 
                             allow_plugins=False):
 
2158
                             allow_plugins=False, stderr=subprocess.PIPE):
1921
2159
        """Start bzr in a subprocess for testing.
1922
2160
 
1923
2161
        This starts a new Python interpreter and runs bzr in there.
1935
2173
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
1936
2174
            doesn't support signalling subprocesses.
1937
2175
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
2176
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2177
            are those valid for the stderr argument of `subprocess.Popen`.
 
2178
            Default value is ``subprocess.PIPE``.
1938
2179
 
1939
2180
        :returns: Popen object for the started process.
1940
2181
        """
1944
2185
 
1945
2186
        if env_changes is None:
1946
2187
            env_changes = {}
 
2188
        # Because $HOME is set to a tempdir for the context of a test, modules
 
2189
        # installed in the user dir will not be found unless $PYTHONUSERBASE
 
2190
        # gets set to the computed directory of this parent process.
 
2191
        if site.USER_BASE is not None:
 
2192
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
1947
2193
        old_env = {}
1948
2194
 
1949
2195
        def cleanup_environment():
1966
2212
            # so we will avoid using it on all platforms, just to
1967
2213
            # make sure the code path is used, and we don't break on win32
1968
2214
            cleanup_environment()
 
2215
            # Include the subprocess's log file in the test details, in case
 
2216
            # the test fails due to an error in the subprocess.
 
2217
            self._add_subprocess_log(trace._get_bzr_log_filename())
1969
2218
            command = [sys.executable]
1970
2219
            # frozen executables don't need the path to bzr
1971
2220
            if getattr(sys, "frozen", None) is None:
1975
2224
            command.extend(process_args)
1976
2225
            process = self._popen(command, stdin=subprocess.PIPE,
1977
2226
                                  stdout=subprocess.PIPE,
1978
 
                                  stderr=subprocess.PIPE)
 
2227
                                  stderr=stderr)
1979
2228
        finally:
1980
2229
            restore_environment()
1981
2230
            if cwd is not None:
1983
2232
 
1984
2233
        return process
1985
2234
 
 
2235
    def _add_subprocess_log(self, log_file_path):
 
2236
        if len(self._log_files) == 0:
 
2237
            # Register an addCleanup func.  We do this on the first call to
 
2238
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2239
            # addCleanup is registered after any cleanups for tempdirs that
 
2240
            # subclasses might create, which will probably remove the log file
 
2241
            # we want to read.
 
2242
            self.addCleanup(self._subprocess_log_cleanup)
 
2243
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2244
        # twice.
 
2245
        self._log_files.add(log_file_path)
 
2246
 
 
2247
    def _subprocess_log_cleanup(self):
 
2248
        for count, log_file_path in enumerate(self._log_files):
 
2249
            # We use buffer_now=True to avoid holding the file open beyond
 
2250
            # the life of this function, which might interfere with e.g.
 
2251
            # cleaning tempdirs on Windows.
 
2252
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2253
            #detail_content = content.content_from_file(
 
2254
            #    log_file_path, buffer_now=True)
 
2255
            with open(log_file_path, 'rb') as log_file:
 
2256
                log_file_bytes = log_file.read()
 
2257
            detail_content = content.Content(content.ContentType("text",
 
2258
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2259
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2260
                detail_content)
 
2261
 
1986
2262
    def _popen(self, *args, **kwargs):
1987
2263
        """Place a call to Popen.
1988
2264
 
2025
2301
        if retcode is not None and retcode != process.returncode:
2026
2302
            if process_args is None:
2027
2303
                process_args = "(unknown args)"
2028
 
            mutter('Output of bzr %s:\n%s', process_args, out)
2029
 
            mutter('Error for bzr %s:\n%s', process_args, err)
 
2304
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
 
2305
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
2030
2306
            self.fail('Command bzr %s failed with retcode %s != %s'
2031
2307
                      % (process_args, retcode, process.returncode))
2032
2308
        return [out, err]
2033
2309
 
2034
 
    def check_inventory_shape(self, inv, shape):
2035
 
        """Compare an inventory to a list of expected names.
 
2310
    def check_tree_shape(self, tree, shape):
 
2311
        """Compare a tree to a list of expected names.
2036
2312
 
2037
2313
        Fail if they are not precisely equal.
2038
2314
        """
2039
2315
        extras = []
2040
2316
        shape = list(shape)             # copy
2041
 
        for path, ie in inv.entries():
 
2317
        for path, ie in tree.iter_entries_by_dir():
2042
2318
            name = path.replace('\\', '/')
2043
2319
            if ie.kind == 'directory':
2044
2320
                name = name + '/'
2045
 
            if name in shape:
 
2321
            if name == "/":
 
2322
                pass # ignore root entry
 
2323
            elif name in shape:
2046
2324
                shape.remove(name)
2047
2325
            else:
2048
2326
                extras.append(name)
2089
2367
 
2090
2368
        Tests that expect to provoke LockContention errors should call this.
2091
2369
        """
2092
 
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2370
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2093
2371
 
2094
2372
    def make_utf8_encoded_stringio(self, encoding_type=None):
2095
2373
        """Return a StringIOWrapper instance, that will encode Unicode
2108
2386
        from bzrlib.smart import request
2109
2387
        request_handlers = request.request_handlers
2110
2388
        orig_method = request_handlers.get(verb)
 
2389
        orig_info = request_handlers.get_info(verb)
2111
2390
        request_handlers.remove(verb)
2112
 
        self.addCleanup(request_handlers.register, verb, orig_method)
 
2391
        self.addCleanup(request_handlers.register, verb, orig_method,
 
2392
            info=orig_info)
2113
2393
 
2114
2394
 
2115
2395
class CapturedCall(object):
2138
2418
class TestCaseWithMemoryTransport(TestCase):
2139
2419
    """Common test class for tests that do not need disk resources.
2140
2420
 
2141
 
    Tests that need disk resources should derive from TestCaseWithTransport.
 
2421
    Tests that need disk resources should derive from TestCaseInTempDir
 
2422
    orTestCaseWithTransport.
2142
2423
 
2143
2424
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2144
2425
 
2145
 
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
2426
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2146
2427
    a directory which does not exist. This serves to help ensure test isolation
2147
 
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
2148
 
    must exist. However, TestCaseWithMemoryTransport does not offer local
2149
 
    file defaults for the transport in tests, nor does it obey the command line
 
2428
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2429
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2430
    defaults for the transport in tests, nor does it obey the command line
2150
2431
    override, so tests that accidentally write to the common directory should
2151
2432
    be rare.
2152
2433
 
2153
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
2154
 
    a .bzr directory that stops us ascending higher into the filesystem.
 
2434
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2435
        ``.bzr`` directory that stops us ascending higher into the filesystem.
2155
2436
    """
2156
2437
 
2157
2438
    TEST_ROOT = None
2175
2456
 
2176
2457
        :param relpath: a path relative to the base url.
2177
2458
        """
2178
 
        t = _mod_transport.get_transport(self.get_url(relpath))
 
2459
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2179
2460
        self.assertFalse(t.is_readonly())
2180
2461
        return t
2181
2462
 
2187
2468
 
2188
2469
        :param relpath: a path relative to the base url.
2189
2470
        """
2190
 
        t = _mod_transport.get_transport(self.get_readonly_url(relpath))
 
2471
        t = _mod_transport.get_transport_from_url(
 
2472
            self.get_readonly_url(relpath))
2191
2473
        self.assertTrue(t.is_readonly())
2192
2474
        return t
2193
2475
 
2314
2596
        real branch.
2315
2597
        """
2316
2598
        root = TestCaseWithMemoryTransport.TEST_ROOT
2317
 
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2599
        # Make sure we get a readable and accessible home for .bzr.log
 
2600
        # and/or config files, and not fallback to weird defaults (see
 
2601
        # http://pad.lv/825027).
 
2602
        self.assertIs(None, os.environ.get('BZR_HOME', None))
 
2603
        os.environ['BZR_HOME'] = root
 
2604
        wt = bzrdir.BzrDir.create_standalone_workingtree(root)
 
2605
        del os.environ['BZR_HOME']
 
2606
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2607
        # we don't need to re-open the wt to check it hasn't changed.
 
2608
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2609
            wt.control_transport.get_bytes('dirstate'))
2318
2610
 
2319
2611
    def _check_safety_net(self):
2320
2612
        """Check that the safety .bzr directory have not been touched.
2323
2615
        propagating. This method ensures than a test did not leaked.
2324
2616
        """
2325
2617
        root = TestCaseWithMemoryTransport.TEST_ROOT
2326
 
        self.permit_url(_mod_transport.get_transport(root).base)
2327
 
        wt = workingtree.WorkingTree.open(root)
2328
 
        last_rev = wt.last_revision()
2329
 
        if last_rev != 'null:':
 
2618
        t = _mod_transport.get_transport_from_path(root)
 
2619
        self.permit_url(t.base)
 
2620
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2621
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2330
2622
            # The current test have modified the /bzr directory, we need to
2331
2623
            # recreate a new one or all the followng tests will fail.
2332
2624
            # If you need to inspect its content uncomment the following line
2367
2659
    def make_branch(self, relpath, format=None):
2368
2660
        """Create a branch on the transport at relpath."""
2369
2661
        repo = self.make_repository(relpath, format=format)
2370
 
        return repo.bzrdir.create_branch()
 
2662
        return repo.bzrdir.create_branch(append_revisions_only=False)
 
2663
 
 
2664
    def get_default_format(self):
 
2665
        return 'default'
 
2666
 
 
2667
    def resolve_format(self, format):
 
2668
        """Resolve an object to a ControlDir format object.
 
2669
 
 
2670
        The initial format object can either already be
 
2671
        a ControlDirFormat, None (for the default format),
 
2672
        or a string with the name of the control dir format.
 
2673
 
 
2674
        :param format: Object to resolve
 
2675
        :return A ControlDirFormat instance
 
2676
        """
 
2677
        if format is None:
 
2678
            format = self.get_default_format()
 
2679
        if isinstance(format, basestring):
 
2680
            format = bzrdir.format_registry.make_bzrdir(format)
 
2681
        return format
2371
2682
 
2372
2683
    def make_bzrdir(self, relpath, format=None):
2373
2684
        try:
2377
2688
            t = _mod_transport.get_transport(maybe_a_url)
2378
2689
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2379
2690
                t.ensure_base()
2380
 
            if format is None:
2381
 
                format = 'default'
2382
 
            if isinstance(format, basestring):
2383
 
                format = bzrdir.format_registry.make_bzrdir(format)
 
2691
            format = self.resolve_format(format)
2384
2692
            return format.initialize_on_transport(t)
2385
2693
        except errors.UninitializableFormat:
2386
2694
            raise TestSkipped("Format %s is not initializable." % format)
2387
2695
 
2388
 
    def make_repository(self, relpath, shared=False, format=None):
 
2696
    def make_repository(self, relpath, shared=None, format=None):
2389
2697
        """Create a repository on our default transport at relpath.
2390
2698
 
2391
2699
        Note that relpath must be a relative path, not a full url.
2402
2710
            backing_server = self.get_server()
2403
2711
        smart_server = test_server.SmartTCPServer_for_testing()
2404
2712
        self.start_server(smart_server, backing_server)
2405
 
        remote_transport = _mod_transport.get_transport(smart_server.get_url()
 
2713
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
2406
2714
                                                   ).clone(path)
2407
2715
        return remote_transport
2408
2716
 
2419
2727
        test_home_dir = self.test_home_dir
2420
2728
        if isinstance(test_home_dir, unicode):
2421
2729
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2422
 
        os.environ['HOME'] = test_home_dir
2423
 
        os.environ['BZR_HOME'] = test_home_dir
 
2730
        self.overrideEnv('HOME', test_home_dir)
 
2731
        self.overrideEnv('BZR_HOME', test_home_dir)
2424
2732
 
2425
2733
    def setUp(self):
2426
2734
        super(TestCaseWithMemoryTransport, self).setUp()
2486
2794
 
2487
2795
    OVERRIDE_PYTHON = 'python'
2488
2796
 
 
2797
    def setUp(self):
 
2798
        super(TestCaseInTempDir, self).setUp()
 
2799
        # Remove the protection set in isolated_environ, we have a proper
 
2800
        # access to disk resources now.
 
2801
        self.overrideEnv('BZR_LOG', None)
 
2802
 
2489
2803
    def check_file_contents(self, filename, expect):
2490
2804
        self.log("check contents of file %s" % filename)
2491
2805
        f = file(filename)
2572
2886
                "a list or a tuple. Got %r instead" % (shape,))
2573
2887
        # It's OK to just create them using forward slashes on windows.
2574
2888
        if transport is None or transport.is_readonly():
2575
 
            transport = _mod_transport.get_transport(".")
 
2889
            transport = _mod_transport.get_transport_from_path(".")
2576
2890
        for name in shape:
2577
2891
            self.assertIsInstance(name, basestring)
2578
2892
            if name[-1] == '/':
2663
2977
        # this obviously requires a format that supports branch references
2664
2978
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2665
2979
        # RBC 20060208
 
2980
        format = self.resolve_format(format=format)
 
2981
        if not format.supports_workingtrees:
 
2982
            b = self.make_branch(relpath+'.branch', format=format)
 
2983
            return b.create_checkout(relpath, lightweight=True)
2666
2984
        b = self.make_branch(relpath, format=format)
2667
2985
        try:
2668
2986
            return b.bzrdir.create_workingtree()
2967
3285
                            result_decorators=result_decorators,
2968
3286
                            )
2969
3287
    runner.stop_on_failure=stop_on_failure
 
3288
    if isinstance(suite, unittest.TestSuite):
 
3289
        # Empty out _tests list of passed suite and populate new TestSuite
 
3290
        suite._tests[:], suite = [], TestSuite(suite)
2970
3291
    # built in decorator factories:
2971
3292
    decorators = [
2972
3293
        random_order(random_seed, runner),
3070
3391
 
3071
3392
class TestDecorator(TestUtil.TestSuite):
3072
3393
    """A decorator for TestCase/TestSuite objects.
3073
 
    
3074
 
    Usually, subclasses should override __iter__(used when flattening test
3075
 
    suites), which we do to filter, reorder, parallelise and so on, run() and
3076
 
    debug().
 
3394
 
 
3395
    Contains rather than flattening suite passed on construction
3077
3396
    """
3078
3397
 
3079
 
    def __init__(self, suite):
3080
 
        TestUtil.TestSuite.__init__(self)
3081
 
        self.addTest(suite)
3082
 
 
3083
 
    def countTestCases(self):
3084
 
        cases = 0
3085
 
        for test in self:
3086
 
            cases += test.countTestCases()
3087
 
        return cases
3088
 
 
3089
 
    def debug(self):
3090
 
        for test in self:
3091
 
            test.debug()
3092
 
 
3093
 
    def run(self, result):
3094
 
        # Use iteration on self, not self._tests, to allow subclasses to hook
3095
 
        # into __iter__.
3096
 
        for test in self:
3097
 
            if result.shouldStop:
3098
 
                break
3099
 
            test.run(result)
3100
 
        return result
 
3398
    def __init__(self, suite=None):
 
3399
        super(TestDecorator, self).__init__()
 
3400
        if suite is not None:
 
3401
            self.addTest(suite)
 
3402
 
 
3403
    # Don't need subclass run method with suite emptying
 
3404
    run = unittest.TestSuite.run
3101
3405
 
3102
3406
 
3103
3407
class CountingDecorator(TestDecorator):
3114
3418
    """A decorator which excludes test matching an exclude pattern."""
3115
3419
 
3116
3420
    def __init__(self, suite, exclude_pattern):
3117
 
        TestDecorator.__init__(self, suite)
3118
 
        self.exclude_pattern = exclude_pattern
3119
 
        self.excluded = False
3120
 
 
3121
 
    def __iter__(self):
3122
 
        if self.excluded:
3123
 
            return iter(self._tests)
3124
 
        self.excluded = True
3125
 
        suite = exclude_tests_by_re(self, self.exclude_pattern)
3126
 
        del self._tests[:]
3127
 
        self.addTests(suite)
3128
 
        return iter(self._tests)
 
3421
        super(ExcludeDecorator, self).__init__(
 
3422
            exclude_tests_by_re(suite, exclude_pattern))
3129
3423
 
3130
3424
 
3131
3425
class FilterTestsDecorator(TestDecorator):
3132
3426
    """A decorator which filters tests to those matching a pattern."""
3133
3427
 
3134
3428
    def __init__(self, suite, pattern):
3135
 
        TestDecorator.__init__(self, suite)
3136
 
        self.pattern = pattern
3137
 
        self.filtered = False
3138
 
 
3139
 
    def __iter__(self):
3140
 
        if self.filtered:
3141
 
            return iter(self._tests)
3142
 
        self.filtered = True
3143
 
        suite = filter_suite_by_re(self, self.pattern)
3144
 
        del self._tests[:]
3145
 
        self.addTests(suite)
3146
 
        return iter(self._tests)
 
3429
        super(FilterTestsDecorator, self).__init__(
 
3430
            filter_suite_by_re(suite, pattern))
3147
3431
 
3148
3432
 
3149
3433
class RandomDecorator(TestDecorator):
3150
3434
    """A decorator which randomises the order of its tests."""
3151
3435
 
3152
3436
    def __init__(self, suite, random_seed, stream):
3153
 
        TestDecorator.__init__(self, suite)
3154
 
        self.random_seed = random_seed
3155
 
        self.randomised = False
3156
 
        self.stream = stream
3157
 
 
3158
 
    def __iter__(self):
3159
 
        if self.randomised:
3160
 
            return iter(self._tests)
3161
 
        self.randomised = True
3162
 
        self.stream.write("Randomizing test order using seed %s\n\n" %
3163
 
            (self.actual_seed()))
 
3437
        random_seed = self.actual_seed(random_seed)
 
3438
        stream.write("Randomizing test order using seed %s\n\n" %
 
3439
            (random_seed,))
3164
3440
        # Initialise the random number generator.
3165
 
        random.seed(self.actual_seed())
3166
 
        suite = randomize_suite(self)
3167
 
        del self._tests[:]
3168
 
        self.addTests(suite)
3169
 
        return iter(self._tests)
 
3441
        random.seed(random_seed)
 
3442
        super(RandomDecorator, self).__init__(randomize_suite(suite))
3170
3443
 
3171
 
    def actual_seed(self):
3172
 
        if self.random_seed == "now":
 
3444
    @staticmethod
 
3445
    def actual_seed(seed):
 
3446
        if seed == "now":
3173
3447
            # We convert the seed to a long to make it reuseable across
3174
3448
            # invocations (because the user can reenter it).
3175
 
            self.random_seed = long(time.time())
 
3449
            return long(time.time())
3176
3450
        else:
3177
3451
            # Convert the seed to a long if we can
3178
3452
            try:
3179
 
                self.random_seed = long(self.random_seed)
3180
 
            except:
 
3453
                return long(seed)
 
3454
            except (TypeError, ValueError):
3181
3455
                pass
3182
 
        return self.random_seed
 
3456
        return seed
3183
3457
 
3184
3458
 
3185
3459
class TestFirstDecorator(TestDecorator):
3186
3460
    """A decorator which moves named tests to the front."""
3187
3461
 
3188
3462
    def __init__(self, suite, pattern):
3189
 
        TestDecorator.__init__(self, suite)
3190
 
        self.pattern = pattern
3191
 
        self.filtered = False
3192
 
 
3193
 
    def __iter__(self):
3194
 
        if self.filtered:
3195
 
            return iter(self._tests)
3196
 
        self.filtered = True
3197
 
        suites = split_suite_by_re(self, self.pattern)
3198
 
        del self._tests[:]
3199
 
        self.addTests(suites)
3200
 
        return iter(self._tests)
 
3463
        super(TestFirstDecorator, self).__init__()
 
3464
        self.addTests(split_suite_by_re(suite, pattern))
3201
3465
 
3202
3466
 
3203
3467
def partition_tests(suite, count):
3235
3499
    """
3236
3500
    concurrency = osutils.local_concurrency()
3237
3501
    result = []
3238
 
    from subunit import TestProtocolClient, ProtocolTestCase
 
3502
    from subunit import ProtocolTestCase
3239
3503
    from subunit.test_results import AutoTimingTestResultDecorator
3240
3504
    class TestInOtherProcess(ProtocolTestCase):
3241
3505
        # Should be in subunit, I think. RBC.
3247
3511
            try:
3248
3512
                ProtocolTestCase.run(self, result)
3249
3513
            finally:
3250
 
                os.waitpid(self.pid, 0)
 
3514
                pid, status = os.waitpid(self.pid, 0)
 
3515
            # GZ 2011-10-18: If status is nonzero, should report to the result
 
3516
            #                that something went wrong.
3251
3517
 
3252
3518
    test_blocks = partition_tests(suite, concurrency)
 
3519
    # Clear the tests from the original suite so it doesn't keep them alive
 
3520
    suite._tests[:] = []
3253
3521
    for process_tests in test_blocks:
3254
 
        process_suite = TestUtil.TestSuite()
3255
 
        process_suite.addTests(process_tests)
 
3522
        process_suite = TestUtil.TestSuite(process_tests)
 
3523
        # Also clear each split list so new suite has only reference
 
3524
        process_tests[:] = []
3256
3525
        c2pread, c2pwrite = os.pipe()
3257
3526
        pid = os.fork()
3258
3527
        if pid == 0:
3259
 
            workaround_zealous_crypto_random()
3260
3528
            try:
 
3529
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3530
                workaround_zealous_crypto_random()
3261
3531
                os.close(c2pread)
3262
3532
                # Leave stderr and stdout open so we can see test noise
3263
3533
                # Close stdin so that the child goes away if it decides to
3264
3534
                # read from stdin (otherwise its a roulette to see what
3265
3535
                # child actually gets keystrokes for pdb etc).
3266
3536
                sys.stdin.close()
3267
 
                sys.stdin = None
3268
 
                stream = os.fdopen(c2pwrite, 'wb', 1)
3269
3537
                subunit_result = AutoTimingTestResultDecorator(
3270
 
                    TestProtocolClient(stream))
 
3538
                    SubUnitBzrProtocolClient(stream))
3271
3539
                process_suite.run(subunit_result)
3272
 
            finally:
3273
 
                os._exit(0)
 
3540
            except:
 
3541
                # Try and report traceback on stream, but exit with error even
 
3542
                # if stream couldn't be created or something else goes wrong.
 
3543
                # The traceback is formatted to a string and written in one go
 
3544
                # to avoid interleaving lines from multiple failing children.
 
3545
                try:
 
3546
                    stream.write(traceback.format_exc())
 
3547
                finally:
 
3548
                    os._exit(1)
 
3549
            os._exit(0)
3274
3550
        else:
3275
3551
            os.close(c2pwrite)
3276
3552
            stream = os.fdopen(c2pread, 'rb', 1)
3337
3613
    return result
3338
3614
 
3339
3615
 
3340
 
class ForwardingResult(unittest.TestResult):
3341
 
 
3342
 
    def __init__(self, target):
3343
 
        unittest.TestResult.__init__(self)
3344
 
        self.result = target
3345
 
 
3346
 
    def startTest(self, test):
3347
 
        self.result.startTest(test)
3348
 
 
3349
 
    def stopTest(self, test):
3350
 
        self.result.stopTest(test)
3351
 
 
3352
 
    def startTestRun(self):
3353
 
        self.result.startTestRun()
3354
 
 
3355
 
    def stopTestRun(self):
3356
 
        self.result.stopTestRun()
3357
 
 
3358
 
    def addSkip(self, test, reason):
3359
 
        self.result.addSkip(test, reason)
3360
 
 
3361
 
    def addSuccess(self, test):
3362
 
        self.result.addSuccess(test)
3363
 
 
3364
 
    def addError(self, test, err):
3365
 
        self.result.addError(test, err)
3366
 
 
3367
 
    def addFailure(self, test, err):
3368
 
        self.result.addFailure(test, err)
3369
 
ForwardingResult = testtools.ExtendedToOriginalDecorator
3370
 
 
3371
 
 
3372
 
class ProfileResult(ForwardingResult):
 
3616
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3373
3617
    """Generate profiling data for all activity between start and success.
3374
3618
    
3375
3619
    The profile data is appended to the test's _benchcalls attribute and can
3387
3631
        # unavoidably fail.
3388
3632
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3389
3633
        self.profiler.start()
3390
 
        ForwardingResult.startTest(self, test)
 
3634
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3391
3635
 
3392
3636
    def addSuccess(self, test):
3393
3637
        stats = self.profiler.stop()
3397
3641
            test._benchcalls = []
3398
3642
            calls = test._benchcalls
3399
3643
        calls.append(((test.id(), "", ""), stats))
3400
 
        ForwardingResult.addSuccess(self, test)
 
3644
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3401
3645
 
3402
3646
    def stopTest(self, test):
3403
 
        ForwardingResult.stopTest(self, test)
 
3647
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3404
3648
        self.profiler = None
3405
3649
 
3406
3650
 
3414
3658
#                           with proper exclusion rules.
3415
3659
#   -Ethreads               Will display thread ident at creation/join time to
3416
3660
#                           help track thread leaks
 
3661
#   -Euncollected_cases     Display the identity of any test cases that weren't
 
3662
#                           deallocated after being completed.
 
3663
#   -Econfig_stats          Will collect statistics using addDetail
3417
3664
selftest_debug_flags = set()
3418
3665
 
3419
3666
 
3613
3860
                key, obj, help=help, info=info, override_existing=False)
3614
3861
        except KeyError:
3615
3862
            actual = self.get(key)
3616
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3617
 
                 % (key, actual, obj))
 
3863
            trace.note(
 
3864
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3865
                % (key, actual, obj))
3618
3866
 
3619
3867
    def resolve_alias(self, id_start):
3620
3868
        """Replace the alias by the prefix in the given string.
3670
3918
        'bzrlib.tests.per_repository',
3671
3919
        'bzrlib.tests.per_repository_chk',
3672
3920
        'bzrlib.tests.per_repository_reference',
 
3921
        'bzrlib.tests.per_repository_vf',
3673
3922
        'bzrlib.tests.per_uifactory',
3674
3923
        'bzrlib.tests.per_versionedfile',
3675
3924
        'bzrlib.tests.per_workingtree',
3709
3958
        'bzrlib.tests.test_commit_merge',
3710
3959
        'bzrlib.tests.test_config',
3711
3960
        'bzrlib.tests.test_conflicts',
 
3961
        'bzrlib.tests.test_controldir',
3712
3962
        'bzrlib.tests.test_counted_lock',
3713
3963
        'bzrlib.tests.test_crash',
3714
3964
        'bzrlib.tests.test_decorators',
3715
3965
        'bzrlib.tests.test_delta',
3716
3966
        'bzrlib.tests.test_debug',
3717
 
        'bzrlib.tests.test_deprecated_graph',
3718
3967
        'bzrlib.tests.test_diff',
3719
3968
        'bzrlib.tests.test_directory_service',
3720
3969
        'bzrlib.tests.test_dirstate',
3721
3970
        'bzrlib.tests.test_email_message',
3722
3971
        'bzrlib.tests.test_eol_filters',
3723
3972
        'bzrlib.tests.test_errors',
 
3973
        'bzrlib.tests.test_estimate_compressed_size',
3724
3974
        'bzrlib.tests.test_export',
 
3975
        'bzrlib.tests.test_export_pot',
3725
3976
        'bzrlib.tests.test_extract',
 
3977
        'bzrlib.tests.test_features',
3726
3978
        'bzrlib.tests.test_fetch',
3727
3979
        'bzrlib.tests.test_fixtures',
3728
3980
        'bzrlib.tests.test_fifo_cache',
3729
3981
        'bzrlib.tests.test_filters',
 
3982
        'bzrlib.tests.test_filter_tree',
3730
3983
        'bzrlib.tests.test_ftp_transport',
3731
3984
        'bzrlib.tests.test_foreign',
3732
3985
        'bzrlib.tests.test_generate_docs',
3741
3994
        'bzrlib.tests.test_http',
3742
3995
        'bzrlib.tests.test_http_response',
3743
3996
        'bzrlib.tests.test_https_ca_bundle',
 
3997
        'bzrlib.tests.test_i18n',
3744
3998
        'bzrlib.tests.test_identitymap',
3745
3999
        'bzrlib.tests.test_ignores',
3746
4000
        'bzrlib.tests.test_index',
3765
4019
        'bzrlib.tests.test_merge3',
3766
4020
        'bzrlib.tests.test_merge_core',
3767
4021
        'bzrlib.tests.test_merge_directive',
 
4022
        'bzrlib.tests.test_mergetools',
3768
4023
        'bzrlib.tests.test_missing',
3769
4024
        'bzrlib.tests.test_msgeditor',
3770
4025
        'bzrlib.tests.test_multiparent',
3794
4049
        'bzrlib.tests.test_rio',
3795
4050
        'bzrlib.tests.test_rules',
3796
4051
        'bzrlib.tests.test_sampler',
 
4052
        'bzrlib.tests.test_scenarios',
3797
4053
        'bzrlib.tests.test_script',
3798
4054
        'bzrlib.tests.test_selftest',
3799
4055
        'bzrlib.tests.test_serializer',
3804
4060
        'bzrlib.tests.test_smart',
3805
4061
        'bzrlib.tests.test_smart_add',
3806
4062
        'bzrlib.tests.test_smart_request',
 
4063
        'bzrlib.tests.test_smart_signals',
3807
4064
        'bzrlib.tests.test_smart_transport',
3808
4065
        'bzrlib.tests.test_smtp_connection',
3809
4066
        'bzrlib.tests.test_source',
3819
4076
        'bzrlib.tests.test_testament',
3820
4077
        'bzrlib.tests.test_textfile',
3821
4078
        'bzrlib.tests.test_textmerge',
 
4079
        'bzrlib.tests.test_cethread',
3822
4080
        'bzrlib.tests.test_timestamp',
3823
4081
        'bzrlib.tests.test_trace',
3824
4082
        'bzrlib.tests.test_transactions',
3835
4093
        'bzrlib.tests.test_upgrade',
3836
4094
        'bzrlib.tests.test_upgrade_stacked',
3837
4095
        'bzrlib.tests.test_urlutils',
 
4096
        'bzrlib.tests.test_utextwrap',
3838
4097
        'bzrlib.tests.test_version',
3839
4098
        'bzrlib.tests.test_version_info',
3840
4099
        'bzrlib.tests.test_versionedfile',
 
4100
        'bzrlib.tests.test_vf_search',
3841
4101
        'bzrlib.tests.test_weave',
3842
4102
        'bzrlib.tests.test_whitebox',
3843
4103
        'bzrlib.tests.test_win32utils',
3857
4117
        'bzrlib',
3858
4118
        'bzrlib.branchbuilder',
3859
4119
        'bzrlib.decorators',
3860
 
        'bzrlib.export',
3861
4120
        'bzrlib.inventory',
3862
4121
        'bzrlib.iterablefile',
3863
4122
        'bzrlib.lockdir',
3868
4127
        'bzrlib.tests',
3869
4128
        'bzrlib.tests.fixtures',
3870
4129
        'bzrlib.timestamp',
 
4130
        'bzrlib.transport.http',
3871
4131
        'bzrlib.version_info_formats.format_custom',
3872
4132
        ]
3873
4133
 
3926
4186
        try:
3927
4187
            # note that this really does mean "report only" -- doctest
3928
4188
            # still runs the rest of the examples
3929
 
            doc_suite = doctest.DocTestSuite(mod,
3930
 
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4189
            doc_suite = IsolatedDocTestSuite(
 
4190
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3931
4191
        except ValueError, e:
3932
4192
            print '**failed to get doctest for: %s\n%s' % (mod, e)
3933
4193
            raise
3936
4196
        suite.addTest(doc_suite)
3937
4197
 
3938
4198
    default_encoding = sys.getdefaultencoding()
3939
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4199
    for name, plugin in _mod_plugin.plugins().items():
3940
4200
        if not interesting_module(plugin.module.__name__):
3941
4201
            continue
3942
4202
        plugin_suite = plugin.test_suite()
3948
4208
        if plugin_suite is not None:
3949
4209
            suite.addTest(plugin_suite)
3950
4210
        if default_encoding != sys.getdefaultencoding():
3951
 
            bzrlib.trace.warning(
 
4211
            trace.warning(
3952
4212
                'Plugin "%s" tried to reset default encoding to: %s', name,
3953
4213
                sys.getdefaultencoding())
3954
4214
            reload(sys)
3969
4229
            # Some tests mentioned in the list are not in the test suite. The
3970
4230
            # list may be out of date, report to the tester.
3971
4231
            for id in not_found:
3972
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4232
                trace.warning('"%s" not found in the test suite', id)
3973
4233
        for id in duplicates:
3974
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4234
            trace.warning('"%s" is used as an id by several tests', id)
3975
4235
 
3976
4236
    return suite
3977
4237
 
3978
4238
 
3979
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4239
def multiply_scenarios(*scenarios):
 
4240
    """Multiply two or more iterables of scenarios.
 
4241
 
 
4242
    It is safe to pass scenario generators or iterators.
 
4243
 
 
4244
    :returns: A list of compound scenarios: the cross-product of all 
 
4245
        scenarios, with the names concatenated and the parameters
 
4246
        merged together.
 
4247
    """
 
4248
    return reduce(_multiply_two_scenarios, map(list, scenarios))
 
4249
 
 
4250
 
 
4251
def _multiply_two_scenarios(scenarios_left, scenarios_right):
3980
4252
    """Multiply two sets of scenarios.
3981
4253
 
3982
4254
    :returns: the cartesian product of the two sets of scenarios, that is
4106
4378
        the module is available.
4107
4379
    """
4108
4380
 
 
4381
    from bzrlib.tests.features import ModuleAvailableFeature
4109
4382
    py_module = pyutils.get_named_object(py_module_name)
4110
4383
    scenarios = [
4111
4384
        ('python', {'module': py_module}),
4152
4425
                         % (os.path.basename(dirname), printable_e))
4153
4426
 
4154
4427
 
4155
 
class Feature(object):
4156
 
    """An operating system Feature."""
4157
 
 
4158
 
    def __init__(self):
4159
 
        self._available = None
4160
 
 
4161
 
    def available(self):
4162
 
        """Is the feature available?
4163
 
 
4164
 
        :return: True if the feature is available.
4165
 
        """
4166
 
        if self._available is None:
4167
 
            self._available = self._probe()
4168
 
        return self._available
4169
 
 
4170
 
    def _probe(self):
4171
 
        """Implement this method in concrete features.
4172
 
 
4173
 
        :return: True if the feature is available.
4174
 
        """
4175
 
        raise NotImplementedError
4176
 
 
4177
 
    def __str__(self):
4178
 
        if getattr(self, 'feature_name', None):
4179
 
            return self.feature_name()
4180
 
        return self.__class__.__name__
4181
 
 
4182
 
 
4183
 
class _SymlinkFeature(Feature):
4184
 
 
4185
 
    def _probe(self):
4186
 
        return osutils.has_symlinks()
4187
 
 
4188
 
    def feature_name(self):
4189
 
        return 'symlinks'
4190
 
 
4191
 
SymlinkFeature = _SymlinkFeature()
4192
 
 
4193
 
 
4194
 
class _HardlinkFeature(Feature):
4195
 
 
4196
 
    def _probe(self):
4197
 
        return osutils.has_hardlinks()
4198
 
 
4199
 
    def feature_name(self):
4200
 
        return 'hardlinks'
4201
 
 
4202
 
HardlinkFeature = _HardlinkFeature()
4203
 
 
4204
 
 
4205
 
class _OsFifoFeature(Feature):
4206
 
 
4207
 
    def _probe(self):
4208
 
        return getattr(os, 'mkfifo', None)
4209
 
 
4210
 
    def feature_name(self):
4211
 
        return 'filesystem fifos'
4212
 
 
4213
 
OsFifoFeature = _OsFifoFeature()
4214
 
 
4215
 
 
4216
 
class _UnicodeFilenameFeature(Feature):
4217
 
    """Does the filesystem support Unicode filenames?"""
4218
 
 
4219
 
    def _probe(self):
4220
 
        try:
4221
 
            # Check for character combinations unlikely to be covered by any
4222
 
            # single non-unicode encoding. We use the characters
4223
 
            # - greek small letter alpha (U+03B1) and
4224
 
            # - braille pattern dots-123456 (U+283F).
4225
 
            os.stat(u'\u03b1\u283f')
4226
 
        except UnicodeEncodeError:
4227
 
            return False
4228
 
        except (IOError, OSError):
4229
 
            # The filesystem allows the Unicode filename but the file doesn't
4230
 
            # exist.
4231
 
            return True
4232
 
        else:
4233
 
            # The filesystem allows the Unicode filename and the file exists,
4234
 
            # for some reason.
4235
 
            return True
4236
 
 
4237
 
UnicodeFilenameFeature = _UnicodeFilenameFeature()
4238
 
 
4239
 
 
4240
 
class _CompatabilityThunkFeature(Feature):
4241
 
    """This feature is just a thunk to another feature.
4242
 
 
4243
 
    It issues a deprecation warning if it is accessed, to let you know that you
4244
 
    should really use a different feature.
4245
 
    """
4246
 
 
4247
 
    def __init__(self, dep_version, module, name,
4248
 
                 replacement_name, replacement_module=None):
4249
 
        super(_CompatabilityThunkFeature, self).__init__()
4250
 
        self._module = module
4251
 
        if replacement_module is None:
4252
 
            replacement_module = module
4253
 
        self._replacement_module = replacement_module
4254
 
        self._name = name
4255
 
        self._replacement_name = replacement_name
4256
 
        self._dep_version = dep_version
4257
 
        self._feature = None
4258
 
 
4259
 
    def _ensure(self):
4260
 
        if self._feature is None:
4261
 
            depr_msg = self._dep_version % ('%s.%s'
4262
 
                                            % (self._module, self._name))
4263
 
            use_msg = ' Use %s.%s instead.' % (self._replacement_module,
4264
 
                                               self._replacement_name)
4265
 
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
4266
 
            # Import the new feature and use it as a replacement for the
4267
 
            # deprecated one.
4268
 
            self._feature = pyutils.get_named_object(
4269
 
                self._replacement_module, self._replacement_name)
4270
 
 
4271
 
    def _probe(self):
4272
 
        self._ensure()
4273
 
        return self._feature._probe()
4274
 
 
4275
 
 
4276
 
class ModuleAvailableFeature(Feature):
4277
 
    """This is a feature than describes a module we want to be available.
4278
 
 
4279
 
    Declare the name of the module in __init__(), and then after probing, the
4280
 
    module will be available as 'self.module'.
4281
 
 
4282
 
    :ivar module: The module if it is available, else None.
4283
 
    """
4284
 
 
4285
 
    def __init__(self, module_name):
4286
 
        super(ModuleAvailableFeature, self).__init__()
4287
 
        self.module_name = module_name
4288
 
 
4289
 
    def _probe(self):
4290
 
        try:
4291
 
            self._module = __import__(self.module_name, {}, {}, [''])
4292
 
            return True
4293
 
        except ImportError:
4294
 
            return False
4295
 
 
4296
 
    @property
4297
 
    def module(self):
4298
 
        if self.available(): # Make sure the probe has been done
4299
 
            return self._module
4300
 
        return None
4301
 
 
4302
 
    def feature_name(self):
4303
 
        return self.module_name
4304
 
 
4305
 
 
4306
 
# This is kept here for compatibility, it is recommended to use
4307
 
# 'bzrlib.tests.feature.paramiko' instead
4308
 
ParamikoFeature = _CompatabilityThunkFeature(
4309
 
    deprecated_in((2,1,0)),
4310
 
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
4311
 
 
4312
 
 
4313
4428
def probe_unicode_in_user_encoding():
4314
4429
    """Try to encode several unicode strings to use in unicode-aware tests.
4315
4430
    Return first successfull match.
4343
4458
    return None
4344
4459
 
4345
4460
 
4346
 
class _HTTPSServerFeature(Feature):
4347
 
    """Some tests want an https Server, check if one is available.
4348
 
 
4349
 
    Right now, the only way this is available is under python2.6 which provides
4350
 
    an ssl module.
4351
 
    """
4352
 
 
4353
 
    def _probe(self):
4354
 
        try:
4355
 
            import ssl
4356
 
            return True
4357
 
        except ImportError:
4358
 
            return False
4359
 
 
4360
 
    def feature_name(self):
4361
 
        return 'HTTPSServer'
4362
 
 
4363
 
 
4364
 
HTTPSServerFeature = _HTTPSServerFeature()
4365
 
 
4366
 
 
4367
 
class _UnicodeFilename(Feature):
4368
 
    """Does the filesystem support Unicode filenames?"""
4369
 
 
4370
 
    def _probe(self):
4371
 
        try:
4372
 
            os.stat(u'\u03b1')
4373
 
        except UnicodeEncodeError:
4374
 
            return False
4375
 
        except (IOError, OSError):
4376
 
            # The filesystem allows the Unicode filename but the file doesn't
4377
 
            # exist.
4378
 
            return True
4379
 
        else:
4380
 
            # The filesystem allows the Unicode filename and the file exists,
4381
 
            # for some reason.
4382
 
            return True
4383
 
 
4384
 
UnicodeFilename = _UnicodeFilename()
4385
 
 
4386
 
 
4387
 
class _ByteStringNamedFilesystem(Feature):
4388
 
    """Is the filesystem based on bytes?"""
4389
 
 
4390
 
    def _probe(self):
4391
 
        if os.name == "posix":
4392
 
            return True
4393
 
        return False
4394
 
 
4395
 
ByteStringNamedFilesystem = _ByteStringNamedFilesystem()
4396
 
 
4397
 
 
4398
 
class _UTF8Filesystem(Feature):
4399
 
    """Is the filesystem UTF-8?"""
4400
 
 
4401
 
    def _probe(self):
4402
 
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
4403
 
            return True
4404
 
        return False
4405
 
 
4406
 
UTF8Filesystem = _UTF8Filesystem()
4407
 
 
4408
 
 
4409
 
class _BreakinFeature(Feature):
4410
 
    """Does this platform support the breakin feature?"""
4411
 
 
4412
 
    def _probe(self):
4413
 
        from bzrlib import breakin
4414
 
        if breakin.determine_signal() is None:
4415
 
            return False
4416
 
        if sys.platform == 'win32':
4417
 
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
4418
 
            # We trigger SIGBREAK via a Console api so we need ctypes to
4419
 
            # access the function
4420
 
            try:
4421
 
                import ctypes
4422
 
            except OSError:
4423
 
                return False
4424
 
        return True
4425
 
 
4426
 
    def feature_name(self):
4427
 
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
4428
 
 
4429
 
 
4430
 
BreakinFeature = _BreakinFeature()
4431
 
 
4432
 
 
4433
 
class _CaseInsCasePresFilenameFeature(Feature):
4434
 
    """Is the file-system case insensitive, but case-preserving?"""
4435
 
 
4436
 
    def _probe(self):
4437
 
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
4438
 
        try:
4439
 
            # first check truly case-preserving for created files, then check
4440
 
            # case insensitive when opening existing files.
4441
 
            name = osutils.normpath(name)
4442
 
            base, rel = osutils.split(name)
4443
 
            found_rel = osutils.canonical_relpath(base, name)
4444
 
            return (found_rel == rel
4445
 
                    and os.path.isfile(name.upper())
4446
 
                    and os.path.isfile(name.lower()))
4447
 
        finally:
4448
 
            os.close(fileno)
4449
 
            os.remove(name)
4450
 
 
4451
 
    def feature_name(self):
4452
 
        return "case-insensitive case-preserving filesystem"
4453
 
 
4454
 
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
4455
 
 
4456
 
 
4457
 
class _CaseInsensitiveFilesystemFeature(Feature):
4458
 
    """Check if underlying filesystem is case-insensitive but *not* case
4459
 
    preserving.
4460
 
    """
4461
 
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
4462
 
    # more likely to be case preserving, so this case is rare.
4463
 
 
4464
 
    def _probe(self):
4465
 
        if CaseInsCasePresFilenameFeature.available():
4466
 
            return False
4467
 
 
4468
 
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
4469
 
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
4470
 
            TestCaseWithMemoryTransport.TEST_ROOT = root
4471
 
        else:
4472
 
            root = TestCaseWithMemoryTransport.TEST_ROOT
4473
 
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
4474
 
            dir=root)
4475
 
        name_a = osutils.pathjoin(tdir, 'a')
4476
 
        name_A = osutils.pathjoin(tdir, 'A')
4477
 
        os.mkdir(name_a)
4478
 
        result = osutils.isdir(name_A)
4479
 
        _rmtree_temp_dir(tdir)
4480
 
        return result
4481
 
 
4482
 
    def feature_name(self):
4483
 
        return 'case-insensitive filesystem'
4484
 
 
4485
 
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
4486
 
 
4487
 
 
4488
 
class _CaseSensitiveFilesystemFeature(Feature):
4489
 
 
4490
 
    def _probe(self):
4491
 
        if CaseInsCasePresFilenameFeature.available():
4492
 
            return False
4493
 
        elif CaseInsensitiveFilesystemFeature.available():
4494
 
            return False
4495
 
        else:
4496
 
            return True
4497
 
 
4498
 
    def feature_name(self):
4499
 
        return 'case-sensitive filesystem'
4500
 
 
4501
 
# new coding style is for feature instances to be lowercase
4502
 
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
4503
 
 
4504
 
 
4505
 
# Kept for compatibility, use bzrlib.tests.features.subunit instead
4506
 
SubUnitFeature = _CompatabilityThunkFeature(
4507
 
    deprecated_in((2,1,0)),
4508
 
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
4509
4461
# Only define SubUnitBzrRunner if subunit is available.
4510
4462
try:
4511
4463
    from subunit import TestProtocolClient
4512
4464
    from subunit.test_results import AutoTimingTestResultDecorator
4513
4465
    class SubUnitBzrProtocolClient(TestProtocolClient):
4514
4466
 
 
4467
        def stopTest(self, test):
 
4468
            super(SubUnitBzrProtocolClient, self).stopTest(test)
 
4469
            _clear__type_equality_funcs(test)
 
4470
 
4515
4471
        def addSuccess(self, test, details=None):
4516
4472
            # The subunit client always includes the details in the subunit
4517
4473
            # stream, but we don't want to include it in ours.
4529
4485
except ImportError:
4530
4486
    pass
4531
4487
 
4532
 
class _PosixPermissionsFeature(Feature):
4533
 
 
4534
 
    def _probe(self):
4535
 
        def has_perms():
4536
 
            # create temporary file and check if specified perms are maintained.
4537
 
            import tempfile
4538
 
 
4539
 
            write_perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
4540
 
            f = tempfile.mkstemp(prefix='bzr_perms_chk_')
4541
 
            fd, name = f
4542
 
            os.close(fd)
4543
 
            os.chmod(name, write_perms)
4544
 
 
4545
 
            read_perms = os.stat(name).st_mode & 0777
4546
 
            os.unlink(name)
4547
 
            return (write_perms == read_perms)
4548
 
 
4549
 
        return (os.name == 'posix') and has_perms()
4550
 
 
4551
 
    def feature_name(self):
4552
 
        return 'POSIX permissions support'
4553
 
 
4554
 
posix_permissions_feature = _PosixPermissionsFeature()
 
4488
 
 
4489
# API compatibility for old plugins; see bug 892622.
 
4490
for name in [
 
4491
    'Feature',
 
4492
    'HTTPServerFeature', 
 
4493
    'ModuleAvailableFeature',
 
4494
    'HTTPSServerFeature', 'SymlinkFeature', 'HardlinkFeature',
 
4495
    'OsFifoFeature', 'UnicodeFilenameFeature',
 
4496
    'ByteStringNamedFilesystem', 'UTF8Filesystem',
 
4497
    'BreakinFeature', 'CaseInsCasePresFilenameFeature',
 
4498
    'CaseInsensitiveFilesystemFeature', 'case_sensitive_filesystem_feature',
 
4499
    'posix_permissions_feature',
 
4500
    ]:
 
4501
    globals()[name] = _CompatabilityThunkFeature(
 
4502
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4503
        'bzrlib.tests', name,
 
4504
        name, 'bzrlib.tests.features')
 
4505
 
 
4506
 
 
4507
for (old_name, new_name) in [
 
4508
    ('UnicodeFilename', 'UnicodeFilenameFeature'),
 
4509
    ]:
 
4510
    globals()[name] = _CompatabilityThunkFeature(
 
4511
        symbol_versioning.deprecated_in((2, 5, 0)),
 
4512
        'bzrlib.tests', old_name,
 
4513
        new_name, 'bzrlib.tests.features')