/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Jelmer Vernooij
  • Date: 2011-09-09 02:12:38 UTC
  • mto: This revision was merged to the branch mainline in revision 6137.
  • Revision ID: jelmer@samba.org-20110909021238-gzrpy7h5qfyvwbvt
Report missing files as removed in 'bzr commit', rather than modified.

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.
29
23
 
30
24
import atexit
31
25
import codecs
32
 
from copy import copy
 
26
import copy
33
27
from cStringIO import StringIO
34
28
import difflib
35
29
import doctest
36
30
import errno
 
31
import itertools
37
32
import logging
38
 
import math
39
33
import os
40
 
from pprint import pformat
 
34
import platform
 
35
import pprint
41
36
import random
42
37
import re
43
38
import shlex
44
39
import stat
45
 
from subprocess import Popen, PIPE, STDOUT
 
40
import subprocess
46
41
import sys
47
42
import tempfile
48
43
import threading
54
49
import testtools
55
50
# nb: check this before importing anything else from within it
56
51
_testtools_version = getattr(testtools, '__version__', ())
57
 
if _testtools_version < (0, 9, 2):
58
 
    raise ImportError("need at least testtools 0.9.2: %s is %r"
 
52
if _testtools_version < (0, 9, 5):
 
53
    raise ImportError("need at least testtools 0.9.5: %s is %r"
59
54
        % (testtools.__file__, _testtools_version))
60
55
from testtools import content
61
56
 
 
57
import bzrlib
62
58
from bzrlib import (
63
59
    branchbuilder,
64
60
    bzrdir,
65
61
    chk_map,
 
62
    commands as _mod_commands,
66
63
    config,
67
64
    debug,
68
65
    errors,
69
66
    hooks,
70
67
    lock as _mod_lock,
 
68
    lockdir,
71
69
    memorytree,
72
70
    osutils,
73
 
    progress,
 
71
    plugin as _mod_plugin,
 
72
    pyutils,
74
73
    ui,
75
74
    urlutils,
76
75
    registry,
 
76
    symbol_versioning,
 
77
    trace,
 
78
    transport as _mod_transport,
77
79
    workingtree,
78
80
    )
79
 
import bzrlib.branch
80
 
import bzrlib.commands
81
 
import bzrlib.timestamp
82
 
import bzrlib.export
83
 
import bzrlib.inventory
84
 
import bzrlib.iterablefile
85
 
import bzrlib.lockdir
86
81
try:
87
82
    import bzrlib.lsprof
88
83
except ImportError:
89
84
    # lsprof not available
90
85
    pass
91
 
from bzrlib.merge import merge_inner
92
 
import bzrlib.merge3
93
 
import bzrlib.plugin
94
 
from bzrlib.smart import client, request, server
95
 
import bzrlib.store
96
 
from bzrlib import symbol_versioning
 
86
from bzrlib.smart import client, request
 
87
from bzrlib.transport import (
 
88
    memory,
 
89
    pathfilter,
 
90
    )
97
91
from bzrlib.symbol_versioning import (
98
 
    DEPRECATED_PARAMETER,
99
92
    deprecated_function,
100
93
    deprecated_in,
101
 
    deprecated_method,
102
 
    deprecated_passed,
103
 
    )
104
 
import bzrlib.trace
105
 
from bzrlib.transport import (
106
 
    get_transport,
107
 
    memory,
108
 
    pathfilter,
109
 
    )
110
 
import bzrlib.transport
111
 
from bzrlib.trace import mutter, note
 
94
    )
112
95
from bzrlib.tests import (
113
96
    test_server,
114
97
    TestUtil,
115
98
    treeshape,
116
99
    )
117
 
from bzrlib.tests.http_server import HttpServer
118
 
from bzrlib.tests.TestUtil import (
119
 
                          TestSuite,
120
 
                          TestLoader,
121
 
                          )
122
100
from bzrlib.ui import NullProgressView
123
101
from bzrlib.ui.text import TextUIFactory
124
 
import bzrlib.version_info_formats.format_custom
125
 
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
126
102
 
127
103
# Mark this python module as being part of the implementation
128
104
# of unittest: this gives us better tracebacks where the last
140
116
SUBUNIT_SEEK_SET = 0
141
117
SUBUNIT_SEEK_CUR = 1
142
118
 
143
 
 
144
 
class ExtendedTestResult(unittest._TextTestResult):
 
119
# These are intentionally brought into this namespace. That way plugins, etc
 
120
# can just "from bzrlib.tests import TestCase, TestLoader, etc"
 
121
TestSuite = TestUtil.TestSuite
 
122
TestLoader = TestUtil.TestLoader
 
123
 
 
124
# Tests should run in a clean and clearly defined environment. The goal is to
 
125
# keep them isolated from the running environment as mush as possible. The test
 
126
# framework ensures the variables defined below are set (or deleted if the
 
127
# value is None) before a test is run and reset to their original value after
 
128
# the test is run. Generally if some code depends on an environment variable,
 
129
# the tests should start without this variable in the environment. There are a
 
130
# few exceptions but you shouldn't violate this rule lightly.
 
131
isolated_environ = {
 
132
    'BZR_HOME': None,
 
133
    'HOME': None,
 
134
    # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
 
135
    # tests do check our impls match APPDATA
 
136
    'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
137
    'VISUAL': None,
 
138
    'EDITOR': None,
 
139
    'BZR_EMAIL': None,
 
140
    'BZREMAIL': None, # may still be present in the environment
 
141
    'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
 
142
    'BZR_PROGRESS_BAR': None,
 
143
    # This should trap leaks to ~/.bzr.log. This occurs when tests use TestCase
 
144
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
 
145
    # TestCase should not use disk resources, BZR_LOG is one.
 
146
    'BZR_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
147
    'BZR_PLUGIN_PATH': None,
 
148
    'BZR_DISABLE_PLUGINS': None,
 
149
    'BZR_PLUGINS_AT': None,
 
150
    'BZR_CONCURRENCY': None,
 
151
    # Make sure that any text ui tests are consistent regardless of
 
152
    # the environment the test case is run in; you may want tests that
 
153
    # test other combinations.  'dumb' is a reasonable guess for tests
 
154
    # going to a pipe or a StringIO.
 
155
    'TERM': 'dumb',
 
156
    'LINES': '25',
 
157
    'COLUMNS': '80',
 
158
    'BZR_COLUMNS': '80',
 
159
    # Disable SSH Agent
 
160
    'SSH_AUTH_SOCK': None,
 
161
    # Proxies
 
162
    'http_proxy': None,
 
163
    'HTTP_PROXY': None,
 
164
    'https_proxy': None,
 
165
    'HTTPS_PROXY': None,
 
166
    'no_proxy': None,
 
167
    'NO_PROXY': None,
 
168
    'all_proxy': None,
 
169
    'ALL_PROXY': None,
 
170
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
171
    # least. If you do (care), please update this comment
 
172
    # -- vila 20080401
 
173
    'ftp_proxy': None,
 
174
    'FTP_PROXY': None,
 
175
    'BZR_REMOTE_PATH': None,
 
176
    # Generally speaking, we don't want apport reporting on crashes in
 
177
    # the test envirnoment unless we're specifically testing apport,
 
178
    # so that it doesn't leak into the real system environment.  We
 
179
    # use an env var so it propagates to subprocesses.
 
180
    'APPORT_DISABLE': '1',
 
181
    }
 
182
 
 
183
 
 
184
def override_os_environ(test, env=None):
 
185
    """Modify os.environ keeping a copy.
 
186
    
 
187
    :param test: A test instance
 
188
 
 
189
    :param env: A dict containing variable definitions to be installed
 
190
    """
 
191
    if env is None:
 
192
        env = isolated_environ
 
193
    test._original_os_environ = dict([(var, value)
 
194
                                      for var, value in os.environ.iteritems()])
 
195
    for var, value in env.iteritems():
 
196
        osutils.set_or_unset_env(var, value)
 
197
        if var not in test._original_os_environ:
 
198
            # The var is new, add it with a value of None, so
 
199
            # restore_os_environ will delete it
 
200
            test._original_os_environ[var] = None
 
201
 
 
202
 
 
203
def restore_os_environ(test):
 
204
    """Restore os.environ to its original state.
 
205
 
 
206
    :param test: A test instance previously passed to override_os_environ.
 
207
    """
 
208
    for var, value in test._original_os_environ.iteritems():
 
209
        # Restore the original value (or delete it if the value has been set to
 
210
        # None in override_os_environ).
 
211
        osutils.set_or_unset_env(var, value)
 
212
 
 
213
 
 
214
class ExtendedTestResult(testtools.TextTestResult):
145
215
    """Accepts, reports and accumulates the results of running tests.
146
216
 
147
217
    Compared to the unittest version this class adds support for
168
238
        :param bench_history: Optionally, a writable file object to accumulate
169
239
            benchmark results.
170
240
        """
171
 
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
241
        testtools.TextTestResult.__init__(self, stream)
172
242
        if bench_history is not None:
173
243
            from bzrlib.version import _get_bzr_source_tree
174
244
            src_tree = _get_bzr_source_tree()
195
265
        self.count = 0
196
266
        self._overall_start_time = time.time()
197
267
        self._strict = strict
 
268
        self._first_thread_leaker_id = None
 
269
        self._tests_leaking_threads_count = 0
 
270
        self._traceback_from_test = None
198
271
 
199
272
    def stopTestRun(self):
200
273
        run = self.testsRun
201
274
        actionTaken = "Ran"
202
275
        stopTime = time.time()
203
276
        timeTaken = stopTime - self.startTime
204
 
        self.printErrors()
205
 
        self.stream.writeln(self.separator2)
206
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
277
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
 
278
        #                the parent class method is similar have to duplicate
 
279
        self._show_list('ERROR', self.errors)
 
280
        self._show_list('FAIL', self.failures)
 
281
        self.stream.write(self.sep2)
 
282
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
207
283
                            run, run != 1 and "s" or "", timeTaken))
208
 
        self.stream.writeln()
209
284
        if not self.wasSuccessful():
210
285
            self.stream.write("FAILED (")
211
286
            failed, errored = map(len, (self.failures, self.errors))
218
293
                if failed or errored: self.stream.write(", ")
219
294
                self.stream.write("known_failure_count=%d" %
220
295
                    self.known_failure_count)
221
 
            self.stream.writeln(")")
 
296
            self.stream.write(")\n")
222
297
        else:
223
298
            if self.known_failure_count:
224
 
                self.stream.writeln("OK (known_failures=%d)" %
 
299
                self.stream.write("OK (known_failures=%d)\n" %
225
300
                    self.known_failure_count)
226
301
            else:
227
 
                self.stream.writeln("OK")
 
302
                self.stream.write("OK\n")
228
303
        if self.skip_count > 0:
229
304
            skipped = self.skip_count
230
 
            self.stream.writeln('%d test%s skipped' %
 
305
            self.stream.write('%d test%s skipped\n' %
231
306
                                (skipped, skipped != 1 and "s" or ""))
232
307
        if self.unsupported:
233
308
            for feature, count in sorted(self.unsupported.items()):
234
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
309
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
235
310
                    (feature, count))
236
311
        if self._strict:
237
312
            ok = self.wasStrictlySuccessful()
238
313
        else:
239
314
            ok = self.wasSuccessful()
240
 
        if TestCase._first_thread_leaker_id:
 
315
        if self._first_thread_leaker_id:
241
316
            self.stream.write(
242
317
                '%s is leaking threads among %d leaking tests.\n' % (
243
 
                TestCase._first_thread_leaker_id,
244
 
                TestCase._leaking_threads_tests))
 
318
                self._first_thread_leaker_id,
 
319
                self._tests_leaking_threads_count))
245
320
            # We don't report the main thread as an active one.
246
321
            self.stream.write(
247
322
                '%d non-main threads were left active in the end.\n'
248
 
                % (TestCase._active_threads - 1))
 
323
                % (len(self._active_threads) - 1))
249
324
 
250
325
    def getDescription(self, test):
251
326
        return test.id()
258
333
 
259
334
    def _elapsedTestTimeString(self):
260
335
        """Return a time string for the overall time the current test has taken."""
261
 
        return self._formatTime(time.time() - self._start_time)
 
336
        return self._formatTime(self._delta_to_float(
 
337
            self._now() - self._start_datetime))
262
338
 
263
339
    def _testTimeString(self, testCase):
264
340
        benchmark_time = self._extractBenchmarkTime(testCase)
275
351
 
276
352
    def _shortened_test_description(self, test):
277
353
        what = test.id()
278
 
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
354
        what = re.sub(r'^bzrlib\.tests\.', '', what)
279
355
        return what
280
356
 
 
357
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
358
    #                multiple times in a row, because the handler is added for
 
359
    #                each test but the container list is shared between cases.
 
360
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
361
    def _record_traceback_from_test(self, exc_info):
 
362
        """Store the traceback from passed exc_info tuple till"""
 
363
        self._traceback_from_test = exc_info[2]
 
364
 
281
365
    def startTest(self, test):
282
 
        unittest.TestResult.startTest(self, test)
 
366
        super(ExtendedTestResult, self).startTest(test)
283
367
        if self.count == 0:
284
368
            self.startTests()
 
369
        self.count += 1
285
370
        self.report_test_start(test)
286
371
        test.number = self.count
287
372
        self._recordTestStartTime()
 
373
        # Make testtools cases give us the real traceback on failure
 
374
        addOnException = getattr(test, "addOnException", None)
 
375
        if addOnException is not None:
 
376
            addOnException(self._record_traceback_from_test)
 
377
        # Only check for thread leaks on bzrlib derived test cases
 
378
        if isinstance(test, TestCase):
 
379
            test.addCleanup(self._check_leaked_threads, test)
 
380
 
 
381
    def stopTest(self, test):
 
382
        super(ExtendedTestResult, self).stopTest(test)
 
383
        # Manually break cycles, means touching various private things but hey
 
384
        getDetails = getattr(test, "getDetails", None)
 
385
        if getDetails is not None:
 
386
            getDetails().clear()
 
387
        # Clear _type_equality_funcs to try to stop TestCase instances
 
388
        # from wasting memory. 'clear' is not available in all Python
 
389
        # versions (bug 809048)
 
390
        type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
391
        if type_equality_funcs is not None:
 
392
            tef_clear = getattr(type_equality_funcs, "clear", None)
 
393
            if tef_clear is None:
 
394
                tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
 
395
                if tef_instance_dict is not None:
 
396
                    tef_clear = tef_instance_dict.clear
 
397
            if tef_clear is not None:
 
398
                tef_clear()
 
399
        self._traceback_from_test = None
288
400
 
289
401
    def startTests(self):
290
 
        import platform
291
 
        if getattr(sys, 'frozen', None) is None:
292
 
            bzr_path = osutils.realpath(sys.argv[0])
293
 
        else:
294
 
            bzr_path = sys.executable
295
 
        self.stream.write(
296
 
            'bzr selftest: %s\n' % (bzr_path,))
297
 
        self.stream.write(
298
 
            '   %s\n' % (
299
 
                    bzrlib.__path__[0],))
300
 
        self.stream.write(
301
 
            '   bzr-%s python-%s %s\n' % (
302
 
                    bzrlib.version_string,
303
 
                    bzrlib._format_version_tuple(sys.version_info),
304
 
                    platform.platform(aliased=1),
305
 
                    ))
306
 
        self.stream.write('\n')
 
402
        self.report_tests_starting()
 
403
        self._active_threads = threading.enumerate()
 
404
 
 
405
    def _check_leaked_threads(self, test):
 
406
        """See if any threads have leaked since last call
 
407
 
 
408
        A sample of live threads is stored in the _active_threads attribute,
 
409
        when this method runs it compares the current live threads and any not
 
410
        in the previous sample are treated as having leaked.
 
411
        """
 
412
        now_active_threads = set(threading.enumerate())
 
413
        threads_leaked = now_active_threads.difference(self._active_threads)
 
414
        if threads_leaked:
 
415
            self._report_thread_leak(test, threads_leaked, now_active_threads)
 
416
            self._tests_leaking_threads_count += 1
 
417
            if self._first_thread_leaker_id is None:
 
418
                self._first_thread_leaker_id = test.id()
 
419
            self._active_threads = now_active_threads
307
420
 
308
421
    def _recordTestStartTime(self):
309
422
        """Record that a test has started."""
310
 
        self._start_time = time.time()
311
 
 
312
 
    def _cleanupLogFile(self, test):
313
 
        # We can only do this if we have one of our TestCases, not if
314
 
        # we have a doctest.
315
 
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
316
 
        if setKeepLogfile is not None:
317
 
            setKeepLogfile()
 
423
        self._start_datetime = self._now()
318
424
 
319
425
    def addError(self, test, err):
320
426
        """Tell result that test finished with an error.
322
428
        Called from the TestCase run() method when the test
323
429
        fails with an unexpected error.
324
430
        """
325
 
        self._post_mortem()
326
 
        unittest.TestResult.addError(self, test, err)
 
431
        self._post_mortem(self._traceback_from_test)
 
432
        super(ExtendedTestResult, self).addError(test, err)
327
433
        self.error_count += 1
328
434
        self.report_error(test, err)
329
435
        if self.stop_early:
330
436
            self.stop()
331
 
        self._cleanupLogFile(test)
332
437
 
333
438
    def addFailure(self, test, err):
334
439
        """Tell result that test failed.
336
441
        Called from the TestCase run() method when the test
337
442
        fails because e.g. an assert() method failed.
338
443
        """
339
 
        self._post_mortem()
340
 
        unittest.TestResult.addFailure(self, test, err)
 
444
        self._post_mortem(self._traceback_from_test)
 
445
        super(ExtendedTestResult, self).addFailure(test, err)
341
446
        self.failure_count += 1
342
447
        self.report_failure(test, err)
343
448
        if self.stop_early:
344
449
            self.stop()
345
 
        self._cleanupLogFile(test)
346
450
 
347
451
    def addSuccess(self, test, details=None):
348
452
        """Tell result that test completed successfully.
356
460
                    self._formatTime(benchmark_time),
357
461
                    test.id()))
358
462
        self.report_success(test)
359
 
        self._cleanupLogFile(test)
360
 
        unittest.TestResult.addSuccess(self, test)
 
463
        super(ExtendedTestResult, self).addSuccess(test)
361
464
        test._log_contents = ''
362
465
 
363
466
    def addExpectedFailure(self, test, err):
364
467
        self.known_failure_count += 1
365
468
        self.report_known_failure(test, err)
366
469
 
 
470
    def addUnexpectedSuccess(self, test, details=None):
 
471
        """Tell result the test unexpectedly passed, counting as a failure
 
472
 
 
473
        When the minimum version of testtools required becomes 0.9.8 this
 
474
        can be updated to use the new handling there.
 
475
        """
 
476
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
477
        self.failure_count += 1
 
478
        self.report_unexpected_success(test,
 
479
            "".join(details["reason"].iter_text()))
 
480
        if self.stop_early:
 
481
            self.stop()
 
482
 
367
483
    def addNotSupported(self, test, feature):
368
484
        """The test will not be run because of a missing feature.
369
485
        """
386
502
        self.not_applicable_count += 1
387
503
        self.report_not_applicable(test, reason)
388
504
 
389
 
    def _post_mortem(self):
 
505
    def _post_mortem(self, tb=None):
390
506
        """Start a PDB post mortem session."""
391
507
        if os.environ.get('BZR_TEST_PDB', None):
392
 
            import pdb;pdb.post_mortem()
 
508
            import pdb
 
509
            pdb.post_mortem(tb)
393
510
 
394
511
    def progress(self, offset, whence):
395
512
        """The test is adjusting the count of tests to run."""
400
517
        else:
401
518
            raise errors.BzrError("Unknown whence %r" % whence)
402
519
 
403
 
    def report_cleaning_up(self):
404
 
        pass
 
520
    def report_tests_starting(self):
 
521
        """Display information before the test run begins"""
 
522
        if getattr(sys, 'frozen', None) is None:
 
523
            bzr_path = osutils.realpath(sys.argv[0])
 
524
        else:
 
525
            bzr_path = sys.executable
 
526
        self.stream.write(
 
527
            'bzr selftest: %s\n' % (bzr_path,))
 
528
        self.stream.write(
 
529
            '   %s\n' % (
 
530
                    bzrlib.__path__[0],))
 
531
        self.stream.write(
 
532
            '   bzr-%s python-%s %s\n' % (
 
533
                    bzrlib.version_string,
 
534
                    bzrlib._format_version_tuple(sys.version_info),
 
535
                    platform.platform(aliased=1),
 
536
                    ))
 
537
        self.stream.write('\n')
 
538
 
 
539
    def report_test_start(self, test):
 
540
        """Display information on the test just about to be run"""
 
541
 
 
542
    def _report_thread_leak(self, test, leaked_threads, active_threads):
 
543
        """Display information on a test that leaked one or more threads"""
 
544
        # GZ 2010-09-09: A leak summary reported separately from the general
 
545
        #                thread debugging would be nice. Tests under subunit
 
546
        #                need something not using stream, perhaps adding a
 
547
        #                testtools details object would be fitting.
 
548
        if 'threads' in selftest_debug_flags:
 
549
            self.stream.write('%s is leaking, active is now %d\n' %
 
550
                (test.id(), len(active_threads)))
405
551
 
406
552
    def startTestRun(self):
407
553
        self.startTime = time.time()
444
590
        self.pb.finished()
445
591
        super(TextTestResult, self).stopTestRun()
446
592
 
447
 
    def startTestRun(self):
448
 
        super(TextTestResult, self).startTestRun()
 
593
    def report_tests_starting(self):
 
594
        super(TextTestResult, self).report_tests_starting()
449
595
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
450
596
 
451
 
    def printErrors(self):
452
 
        # clear the pb to make room for the error listing
453
 
        self.pb.clear()
454
 
        super(TextTestResult, self).printErrors()
455
 
 
456
597
    def _progress_prefix_text(self):
457
598
        # the longer this text, the less space we have to show the test
458
599
        # name...
480
621
        return a
481
622
 
482
623
    def report_test_start(self, test):
483
 
        self.count += 1
484
624
        self.pb.update(
485
625
                self._progress_prefix_text()
486
626
                + ' '
504
644
    def report_known_failure(self, test, err):
505
645
        pass
506
646
 
 
647
    def report_unexpected_success(self, test, reason):
 
648
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
 
649
            self._test_description(test),
 
650
            "Unexpected success. Should have failed",
 
651
            reason,
 
652
            ))
 
653
 
507
654
    def report_skip(self, test, reason):
508
655
        pass
509
656
 
513
660
    def report_unsupported(self, test, feature):
514
661
        """test cannot be run because feature is missing."""
515
662
 
516
 
    def report_cleaning_up(self):
517
 
        self.pb.update('Cleaning up')
518
 
 
519
663
 
520
664
class VerboseTestResult(ExtendedTestResult):
521
665
    """Produce long output, with one line per test run plus times"""
528
672
            result = a_string
529
673
        return result.ljust(final_width)
530
674
 
531
 
    def startTestRun(self):
532
 
        super(VerboseTestResult, self).startTestRun()
 
675
    def report_tests_starting(self):
533
676
        self.stream.write('running %d tests...\n' % self.num_tests)
 
677
        super(VerboseTestResult, self).report_tests_starting()
534
678
 
535
679
    def report_test_start(self, test):
536
 
        self.count += 1
537
680
        name = self._shortened_test_description(test)
538
681
        width = osutils.terminal_width()
539
682
        if width is not None:
551
694
        return '%s%s' % (indent, err[1])
552
695
 
553
696
    def report_error(self, test, err):
554
 
        self.stream.writeln('ERROR %s\n%s'
 
697
        self.stream.write('ERROR %s\n%s\n'
555
698
                % (self._testTimeString(test),
556
699
                   self._error_summary(err)))
557
700
 
558
701
    def report_failure(self, test, err):
559
 
        self.stream.writeln(' FAIL %s\n%s'
 
702
        self.stream.write(' FAIL %s\n%s\n'
560
703
                % (self._testTimeString(test),
561
704
                   self._error_summary(err)))
562
705
 
563
706
    def report_known_failure(self, test, err):
564
 
        self.stream.writeln('XFAIL %s\n%s'
 
707
        self.stream.write('XFAIL %s\n%s\n'
565
708
                % (self._testTimeString(test),
566
709
                   self._error_summary(err)))
567
710
 
 
711
    def report_unexpected_success(self, test, reason):
 
712
        self.stream.write(' FAIL %s\n%s: %s\n'
 
713
                % (self._testTimeString(test),
 
714
                   "Unexpected success. Should have failed",
 
715
                   reason))
 
716
 
568
717
    def report_success(self, test):
569
 
        self.stream.writeln('   OK %s' % self._testTimeString(test))
 
718
        self.stream.write('   OK %s\n' % self._testTimeString(test))
570
719
        for bench_called, stats in getattr(test, '_benchcalls', []):
571
 
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
720
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
572
721
            stats.pprint(file=self.stream)
573
722
        # flush the stream so that we get smooth output. This verbose mode is
574
723
        # used to show the output in PQM.
575
724
        self.stream.flush()
576
725
 
577
726
    def report_skip(self, test, reason):
578
 
        self.stream.writeln(' SKIP %s\n%s'
 
727
        self.stream.write(' SKIP %s\n%s\n'
579
728
                % (self._testTimeString(test), reason))
580
729
 
581
730
    def report_not_applicable(self, test, reason):
582
 
        self.stream.writeln('  N/A %s\n    %s'
 
731
        self.stream.write('  N/A %s\n    %s\n'
583
732
                % (self._testTimeString(test), reason))
584
733
 
585
734
    def report_unsupported(self, test, feature):
586
735
        """test cannot be run because feature is missing."""
587
 
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
 
736
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
588
737
                %(self._testTimeString(test), feature))
589
738
 
590
739
 
617
766
            encode = codec[0]
618
767
        else:
619
768
            encode = codec.encode
620
 
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream)
 
769
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
770
        #                so should swap to the plain codecs.StreamWriter
 
771
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
772
            "backslashreplace")
621
773
        stream.encoding = new_encoding
622
 
        self.stream = unittest._WritelnDecorator(stream)
 
774
        self.stream = stream
623
775
        self.descriptions = descriptions
624
776
        self.verbosity = verbosity
625
777
        self._bench_history = bench_history
749
901
    # XXX: Should probably unify more with CannedInputUIFactory or a
750
902
    # particular configuration of TextUIFactory, or otherwise have a clearer
751
903
    # idea of how they're supposed to be different.
752
 
    # See https://bugs.edge.launchpad.net/bzr/+bug/408213
 
904
    # See https://bugs.launchpad.net/bzr/+bug/408213
753
905
 
754
906
    def __init__(self, stdout=None, stderr=None, stdin=None):
755
907
        if stdin is not None:
773
925
        return NullProgressView()
774
926
 
775
927
 
 
928
def isolated_doctest_setUp(test):
 
929
    override_os_environ(test)
 
930
 
 
931
 
 
932
def isolated_doctest_tearDown(test):
 
933
    restore_os_environ(test)
 
934
 
 
935
 
 
936
def IsolatedDocTestSuite(*args, **kwargs):
 
937
    """Overrides doctest.DocTestSuite to handle isolation.
 
938
 
 
939
    The method is really a factory and users are expected to use it as such.
 
940
    """
 
941
 
 
942
    kwargs['setUp'] = isolated_doctest_setUp
 
943
    kwargs['tearDown'] = isolated_doctest_tearDown
 
944
    return doctest.DocTestSuite(*args, **kwargs)
 
945
 
 
946
 
776
947
class TestCase(testtools.TestCase):
777
948
    """Base class for bzr unit tests.
778
949
 
789
960
    routine, and to build and check bzr trees.
790
961
 
791
962
    In addition to the usual method of overriding tearDown(), this class also
792
 
    allows subclasses to register functions into the _cleanups list, which is
 
963
    allows subclasses to register cleanup functions via addCleanup, which are
793
964
    run in order as the object is torn down.  It's less likely this will be
794
965
    accidentally overlooked.
795
966
    """
796
967
 
797
 
    _active_threads = None
798
 
    _leaking_threads_tests = 0
799
 
    _first_thread_leaker_id = None
800
 
    _log_file_name = None
 
968
    _log_file = None
801
969
    # record lsprof data when performing benchmark calls.
802
970
    _gather_lsprof_in_benchmarks = False
803
971
 
804
972
    def __init__(self, methodName='testMethod'):
805
973
        super(TestCase, self).__init__(methodName)
806
 
        self._cleanups = []
807
974
        self._directory_isolation = True
808
975
        self.exception_handlers.insert(0,
809
976
            (UnavailableFeature, self._do_unsupported_or_skip))
814
981
        super(TestCase, self).setUp()
815
982
        for feature in getattr(self, '_test_needs_features', []):
816
983
            self.requireFeature(feature)
817
 
        self._log_contents = None
818
 
        self.addDetail("log", content.Content(content.ContentType("text",
819
 
            "plain", {"charset": "utf8"}),
820
 
            lambda:[self._get_log(keep_log_file=True)]))
821
984
        self._cleanEnvironment()
822
985
        self._silenceUI()
823
986
        self._startLogFile()
827
990
        self._track_transports()
828
991
        self._track_locks()
829
992
        self._clear_debug_flags()
830
 
        TestCase._active_threads = threading.activeCount()
831
 
        self.addCleanup(self._check_leaked_threads)
 
993
        # Isolate global verbosity level, to make sure it's reproducible
 
994
        # between tests.  We should get rid of this altogether: bug 656694. --
 
995
        # mbp 20101008
 
996
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
 
997
        # Isolate config option expansion until its default value for bzrlib is
 
998
        # settled on or a the FIXME associated with _get_expand_default_value
 
999
        # is addressed -- vila 20110219
 
1000
        self.overrideAttr(config, '_expand_default_value', None)
 
1001
        self._log_files = set()
 
1002
        # Each key in the ``_counters`` dict holds a value for a different
 
1003
        # counter. When the test ends, addDetail() should be used to output the
 
1004
        # counter values. This happens in install_counter_hook().
 
1005
        self._counters = {}
 
1006
        if 'config_stats' in selftest_debug_flags:
 
1007
            self._install_config_stats_hooks()
832
1008
 
833
1009
    def debug(self):
834
1010
        # debug a frame up.
835
1011
        import pdb
836
 
        pdb.Pdb().set_trace(sys._getframe().f_back)
837
 
 
838
 
    def _check_leaked_threads(self):
839
 
        active = threading.activeCount()
840
 
        leaked_threads = active - TestCase._active_threads
841
 
        TestCase._active_threads = active
842
 
        # If some tests make the number of threads *decrease*, we'll consider
843
 
        # that they are just observing old threads dieing, not agressively kill
844
 
        # random threads. So we don't report these tests as leaking. The risk
845
 
        # is that we have false positives that way (the test see 2 threads
846
 
        # going away but leak one) but it seems less likely than the actual
847
 
        # false positives (the test see threads going away and does not leak).
848
 
        if leaked_threads > 0:
849
 
            TestCase._leaking_threads_tests += 1
850
 
            if TestCase._first_thread_leaker_id is None:
851
 
                TestCase._first_thread_leaker_id = self.id()
 
1012
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
1013
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
1014
                ).set_trace(sys._getframe().f_back)
 
1015
 
 
1016
    def discardDetail(self, name):
 
1017
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1018
 
 
1019
        eg. bzr always adds the 'log' detail at startup, but we don't want to
 
1020
        include it for skipped, xfail, etc tests.
 
1021
 
 
1022
        It is safe to call this for a detail that doesn't exist, in case this
 
1023
        gets called multiple times.
 
1024
        """
 
1025
        # We cheat. details is stored in __details which means we shouldn't
 
1026
        # touch it. but getDetails() returns the dict directly, so we can
 
1027
        # mutate it.
 
1028
        details = self.getDetails()
 
1029
        if name in details:
 
1030
            del details[name]
 
1031
 
 
1032
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1033
        """Install a counting hook.
 
1034
 
 
1035
        Any hook can be counted as long as it doesn't need to return a value.
 
1036
 
 
1037
        :param hooks: Where the hook should be installed.
 
1038
 
 
1039
        :param name: The hook name that will be counted.
 
1040
 
 
1041
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1042
            to ``name``.
 
1043
        """
 
1044
        _counters = self._counters # Avoid closing over self
 
1045
        if counter_name is None:
 
1046
            counter_name = name
 
1047
        if _counters.has_key(counter_name):
 
1048
            raise AssertionError('%s is already used as a counter name'
 
1049
                                  % (counter_name,))
 
1050
        _counters[counter_name] = 0
 
1051
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1052
            lambda: ['%d' % (_counters[counter_name],)]))
 
1053
        def increment_counter(*args, **kwargs):
 
1054
            _counters[counter_name] += 1
 
1055
        label = 'count %s calls' % (counter_name,)
 
1056
        hooks.install_named_hook(name, increment_counter, label)
 
1057
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1058
 
 
1059
    def _install_config_stats_hooks(self):
 
1060
        """Install config hooks to count hook calls.
 
1061
 
 
1062
        """
 
1063
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1064
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1065
                                       'config.%s' % (hook_name,))
 
1066
 
 
1067
        # The OldConfigHooks are private and need special handling to protect
 
1068
        # against recursive tests (tests that run other tests), so we just do
 
1069
        # manually what registering them into _builtin_known_hooks will provide
 
1070
        # us.
 
1071
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1072
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1073
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1074
                                      'old_config.%s' % (hook_name,))
852
1075
 
853
1076
    def _clear_debug_flags(self):
854
1077
        """Prevent externally set debug flags affecting tests.
865
1088
 
866
1089
    def _clear_hooks(self):
867
1090
        # prevent hooks affecting tests
 
1091
        known_hooks = hooks.known_hooks
868
1092
        self._preserved_hooks = {}
869
 
        for key, factory in hooks.known_hooks.items():
870
 
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
871
 
            current_hooks = hooks.known_hooks_key_to_object(key)
 
1093
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1094
            current_hooks = getattr(parent, name)
872
1095
            self._preserved_hooks[parent] = (name, current_hooks)
 
1096
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1097
        hooks._lazy_hooks = {}
873
1098
        self.addCleanup(self._restoreHooks)
874
 
        for key, factory in hooks.known_hooks.items():
875
 
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
 
1099
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1100
            factory = known_hooks.get(key)
876
1101
            setattr(parent, name, factory())
877
1102
        # this hook should always be installed
878
1103
        request._install_hook()
907
1132
        # break some locks on purpose and should be taken into account by
908
1133
        # considering that breaking a lock is just a dirty way of releasing it.
909
1134
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
910
 
            message = ('Different number of acquired and '
911
 
                       'released or broken locks. (%s, %s + %s)' %
912
 
                       (acquired_locks, released_locks, broken_locks))
 
1135
            message = (
 
1136
                'Different number of acquired and '
 
1137
                'released or broken locks.\n'
 
1138
                'acquired=%s\n'
 
1139
                'released=%s\n'
 
1140
                'broken=%s\n' %
 
1141
                (acquired_locks, released_locks, broken_locks))
913
1142
            if not self._lock_check_thorough:
914
1143
                # Rather than fail, just warn
915
1144
                print "Broken test %s: %s" % (self, message)
943
1172
 
944
1173
    def permit_dir(self, name):
945
1174
        """Permit a directory to be used by this test. See permit_url."""
946
 
        name_transport = get_transport(name)
 
1175
        name_transport = _mod_transport.get_transport_from_path(name)
947
1176
        self.permit_url(name)
948
1177
        self.permit_url(name_transport.base)
949
1178
 
972
1201
            try:
973
1202
                workingtree.WorkingTree.open(path)
974
1203
            except (errors.NotBranchError, errors.NoWorkingTree):
975
 
                return
 
1204
                raise TestSkipped('Needs a working tree of bzr sources')
976
1205
        finally:
977
1206
            self.enable_directory_isolation()
978
1207
 
1028
1257
        self.addCleanup(transport_server.stop_server)
1029
1258
        # Obtain a real transport because if the server supplies a password, it
1030
1259
        # will be hidden from the base on the client side.
1031
 
        t = get_transport(transport_server.get_url())
 
1260
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
1032
1261
        # Some transport servers effectively chroot the backing transport;
1033
1262
        # others like SFTPServer don't - users of the transport can walk up the
1034
1263
        # transport to read the entire backing transport. This wouldn't matter
1090
1319
        except UnicodeError, e:
1091
1320
            # If we can't compare without getting a UnicodeError, then
1092
1321
            # obviously they are different
1093
 
            mutter('UnicodeError: %s', e)
 
1322
            trace.mutter('UnicodeError: %s', e)
1094
1323
        if message:
1095
1324
            message += '\n'
1096
1325
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1097
1326
            % (message,
1098
 
               pformat(a), pformat(b)))
 
1327
               pprint.pformat(a), pprint.pformat(b)))
1099
1328
 
1100
1329
    assertEquals = assertEqual
1101
1330
 
1135
1364
                         'st_mtime did not match')
1136
1365
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1137
1366
                         'st_ctime did not match')
1138
 
        if sys.platform != 'win32':
 
1367
        if sys.platform == 'win32':
1139
1368
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1140
1369
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
1141
 
            # odd. Regardless we shouldn't actually try to assert anything
1142
 
            # about their values
 
1370
            # odd. We just force it to always be 0 to avoid any problems.
 
1371
            self.assertEqual(0, expected.st_dev)
 
1372
            self.assertEqual(0, actual.st_dev)
 
1373
            self.assertEqual(0, expected.st_ino)
 
1374
            self.assertEqual(0, actual.st_ino)
 
1375
        else:
1143
1376
            self.assertEqual(expected.st_dev, actual.st_dev,
1144
1377
                             'st_dev did not match')
1145
1378
            self.assertEqual(expected.st_ino, actual.st_ino,
1154
1387
                length, len(obj_with_len), obj_with_len))
1155
1388
 
1156
1389
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1157
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1390
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1158
1391
        """
1159
 
        from bzrlib import trace
1160
1392
        captured = []
1161
1393
        orig_log_exception_quietly = trace.log_exception_quietly
1162
1394
        try:
1163
1395
            def capture():
1164
1396
                orig_log_exception_quietly()
1165
 
                captured.append(sys.exc_info())
 
1397
                captured.append(sys.exc_info()[1])
1166
1398
            trace.log_exception_quietly = capture
1167
1399
            func(*args, **kwargs)
1168
1400
        finally:
1169
1401
            trace.log_exception_quietly = orig_log_exception_quietly
1170
1402
        self.assertLength(1, captured)
1171
 
        err = captured[0][1]
 
1403
        err = captured[0]
1172
1404
        self.assertIsInstance(err, exception_class)
1173
1405
        return err
1174
1406
 
1211
1443
        if haystack.find(needle) == -1:
1212
1444
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1213
1445
 
 
1446
    def assertNotContainsString(self, haystack, needle):
 
1447
        if haystack.find(needle) != -1:
 
1448
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1449
 
1214
1450
    def assertSubset(self, sublist, superlist):
1215
1451
        """Assert that every entry in sublist is present in superlist."""
1216
1452
        missing = set(sublist) - set(superlist)
1305
1541
 
1306
1542
    def assertFileEqual(self, content, path):
1307
1543
        """Fail if path does not contain 'content'."""
1308
 
        self.failUnlessExists(path)
 
1544
        self.assertPathExists(path)
1309
1545
        f = file(path, 'rb')
1310
1546
        try:
1311
1547
            s = f.read()
1321
1557
        else:
1322
1558
            self.assertEqual(expected_docstring, obj.__doc__)
1323
1559
 
 
1560
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1324
1561
    def failUnlessExists(self, path):
 
1562
        return self.assertPathExists(path)
 
1563
 
 
1564
    def assertPathExists(self, path):
1325
1565
        """Fail unless path or paths, which may be abs or relative, exist."""
1326
1566
        if not isinstance(path, basestring):
1327
1567
            for p in path:
1328
 
                self.failUnlessExists(p)
 
1568
                self.assertPathExists(p)
1329
1569
        else:
1330
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1570
            self.assertTrue(osutils.lexists(path),
 
1571
                path + " does not exist")
1331
1572
 
 
1573
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1332
1574
    def failIfExists(self, path):
 
1575
        return self.assertPathDoesNotExist(path)
 
1576
 
 
1577
    def assertPathDoesNotExist(self, path):
1333
1578
        """Fail if path or paths, which may be abs or relative, exist."""
1334
1579
        if not isinstance(path, basestring):
1335
1580
            for p in path:
1336
 
                self.failIfExists(p)
 
1581
                self.assertPathDoesNotExist(p)
1337
1582
        else:
1338
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1583
            self.assertFalse(osutils.lexists(path),
 
1584
                path + " exists")
1339
1585
 
1340
1586
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1341
1587
        """A helper for callDeprecated and applyDeprecated.
1367
1613
        not other callers that go direct to the warning module.
1368
1614
 
1369
1615
        To test that a deprecated method raises an error, do something like
1370
 
        this::
 
1616
        this (remember that both assertRaises and applyDeprecated delays *args
 
1617
        and **kwargs passing)::
1371
1618
 
1372
1619
            self.assertRaises(errors.ReservedId,
1373
1620
                self.applyDeprecated,
1455
1702
 
1456
1703
        The file is removed as the test is torn down.
1457
1704
        """
1458
 
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
1459
 
        self._log_file = os.fdopen(fileno, 'w+')
1460
 
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
1461
 
        self._log_file_name = name
 
1705
        pseudo_log_file = StringIO()
 
1706
        def _get_log_contents_for_weird_testtools_api():
 
1707
            return [pseudo_log_file.getvalue().decode(
 
1708
                "utf-8", "replace").encode("utf-8")]
 
1709
        self.addDetail("log", content.Content(content.ContentType("text",
 
1710
            "plain", {"charset": "utf8"}),
 
1711
            _get_log_contents_for_weird_testtools_api))
 
1712
        self._log_file = pseudo_log_file
 
1713
        self._log_memento = trace.push_log_file(self._log_file)
1462
1714
        self.addCleanup(self._finishLogFile)
1463
1715
 
1464
1716
    def _finishLogFile(self):
1465
1717
        """Finished with the log file.
1466
1718
 
1467
 
        Close the file and delete it, unless setKeepLogfile was called.
 
1719
        Close the file and delete it.
1468
1720
        """
1469
 
        if bzrlib.trace._trace_file:
 
1721
        if trace._trace_file:
1470
1722
            # flush the log file, to get all content
1471
 
            bzrlib.trace._trace_file.flush()
1472
 
        bzrlib.trace.pop_log_file(self._log_memento)
1473
 
        # Cache the log result and delete the file on disk
1474
 
        self._get_log(False)
 
1723
            trace._trace_file.flush()
 
1724
        trace.pop_log_file(self._log_memento)
1475
1725
 
1476
1726
    def thisFailsStrictLockCheck(self):
1477
1727
        """It is known that this test would fail with -Dstrict_locks.
1486
1736
        """
1487
1737
        debug.debug_flags.discard('strict_locks')
1488
1738
 
1489
 
    def addCleanup(self, callable, *args, **kwargs):
1490
 
        """Arrange to run a callable when this case is torn down.
1491
 
 
1492
 
        Callables are run in the reverse of the order they are registered,
1493
 
        ie last-in first-out.
1494
 
        """
1495
 
        self._cleanups.append((callable, args, kwargs))
1496
 
 
1497
1739
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1498
1740
        """Overrides an object attribute restoring it after the test.
1499
1741
 
 
1742
        :note: This should be used with discretion; you should think about
 
1743
        whether it's better to make the code testable without monkey-patching.
 
1744
 
1500
1745
        :param obj: The object that will be mutated.
1501
1746
 
1502
1747
        :param attr_name: The attribute name we want to preserve/override in
1513
1758
            setattr(obj, attr_name, new)
1514
1759
        return value
1515
1760
 
 
1761
    def overrideEnv(self, name, new):
 
1762
        """Set an environment variable, and reset it after the test.
 
1763
 
 
1764
        :param name: The environment variable name.
 
1765
 
 
1766
        :param new: The value to set the variable to. If None, the 
 
1767
            variable is deleted from the environment.
 
1768
 
 
1769
        :returns: The actual variable value.
 
1770
        """
 
1771
        value = osutils.set_or_unset_env(name, new)
 
1772
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1773
        return value
 
1774
 
 
1775
    def recordCalls(self, obj, attr_name):
 
1776
        """Monkeypatch in a wrapper that will record calls.
 
1777
 
 
1778
        The monkeypatch is automatically removed when the test concludes.
 
1779
 
 
1780
        :param obj: The namespace holding the reference to be replaced;
 
1781
            typically a module, class, or object.
 
1782
        :param attr_name: A string for the name of the attribute to 
 
1783
            patch.
 
1784
        :returns: A list that will be extended with one item every time the
 
1785
            function is called, with a tuple of (args, kwargs).
 
1786
        """
 
1787
        calls = []
 
1788
 
 
1789
        def decorator(*args, **kwargs):
 
1790
            calls.append((args, kwargs))
 
1791
            return orig(*args, **kwargs)
 
1792
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1793
        return calls
 
1794
 
1516
1795
    def _cleanEnvironment(self):
1517
 
        new_env = {
1518
 
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
1519
 
            'HOME': os.getcwd(),
1520
 
            # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
1521
 
            # tests do check our impls match APPDATA
1522
 
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
1523
 
            'VISUAL': None,
1524
 
            'EDITOR': None,
1525
 
            'BZR_EMAIL': None,
1526
 
            'BZREMAIL': None, # may still be present in the environment
1527
 
            'EMAIL': None,
1528
 
            'BZR_PROGRESS_BAR': None,
1529
 
            'BZR_LOG': None,
1530
 
            'BZR_PLUGIN_PATH': None,
1531
 
            'BZR_DISABLE_PLUGINS': None,
1532
 
            'BZR_PLUGINS_AT': None,
1533
 
            'BZR_CONCURRENCY': None,
1534
 
            # Make sure that any text ui tests are consistent regardless of
1535
 
            # the environment the test case is run in; you may want tests that
1536
 
            # test other combinations.  'dumb' is a reasonable guess for tests
1537
 
            # going to a pipe or a StringIO.
1538
 
            'TERM': 'dumb',
1539
 
            'LINES': '25',
1540
 
            'COLUMNS': '80',
1541
 
            'BZR_COLUMNS': '80',
1542
 
            # SSH Agent
1543
 
            'SSH_AUTH_SOCK': None,
1544
 
            # Proxies
1545
 
            'http_proxy': None,
1546
 
            'HTTP_PROXY': None,
1547
 
            'https_proxy': None,
1548
 
            'HTTPS_PROXY': None,
1549
 
            'no_proxy': None,
1550
 
            'NO_PROXY': None,
1551
 
            'all_proxy': None,
1552
 
            'ALL_PROXY': None,
1553
 
            # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
1554
 
            # least. If you do (care), please update this comment
1555
 
            # -- vila 20080401
1556
 
            'ftp_proxy': None,
1557
 
            'FTP_PROXY': None,
1558
 
            'BZR_REMOTE_PATH': None,
1559
 
            # Generally speaking, we don't want apport reporting on crashes in
1560
 
            # the test envirnoment unless we're specifically testing apport,
1561
 
            # so that it doesn't leak into the real system environment.  We
1562
 
            # use an env var so it propagates to subprocesses.
1563
 
            'APPORT_DISABLE': '1',
1564
 
        }
1565
 
        self._old_env = {}
1566
 
        self.addCleanup(self._restoreEnvironment)
1567
 
        for name, value in new_env.iteritems():
1568
 
            self._captureVar(name, value)
1569
 
 
1570
 
    def _captureVar(self, name, newvalue):
1571
 
        """Set an environment variable, and reset it when finished."""
1572
 
        self._old_env[name] = osutils.set_or_unset_env(name, newvalue)
1573
 
 
1574
 
    def _restoreEnvironment(self):
1575
 
        for name, value in self._old_env.iteritems():
1576
 
            osutils.set_or_unset_env(name, value)
 
1796
        for name, value in isolated_environ.iteritems():
 
1797
            self.overrideEnv(name, value)
1577
1798
 
1578
1799
    def _restoreHooks(self):
1579
1800
        for klass, (name, hooks) in self._preserved_hooks.items():
1580
1801
            setattr(klass, name, hooks)
 
1802
        self._preserved_hooks.clear()
 
1803
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1804
        self._preserved_lazy_hooks.clear()
1581
1805
 
1582
1806
    def knownFailure(self, reason):
1583
 
        """This test has failed for some known reason."""
1584
 
        raise KnownFailure(reason)
 
1807
        """Declare that this test fails for a known reason
 
1808
 
 
1809
        Tests that are known to fail should generally be using expectedFailure
 
1810
        with an appropriate reverse assertion if a change could cause the test
 
1811
        to start passing. Conversely if the test has no immediate prospect of
 
1812
        succeeding then using skip is more suitable.
 
1813
 
 
1814
        When this method is called while an exception is being handled, that
 
1815
        traceback will be used, otherwise a new exception will be thrown to
 
1816
        provide one but won't be reported.
 
1817
        """
 
1818
        self._add_reason(reason)
 
1819
        try:
 
1820
            exc_info = sys.exc_info()
 
1821
            if exc_info != (None, None, None):
 
1822
                self._report_traceback(exc_info)
 
1823
            else:
 
1824
                try:
 
1825
                    raise self.failureException(reason)
 
1826
                except self.failureException:
 
1827
                    exc_info = sys.exc_info()
 
1828
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1829
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1830
        finally:
 
1831
            del exc_info
 
1832
 
 
1833
    def _suppress_log(self):
 
1834
        """Remove the log info from details."""
 
1835
        self.discardDetail('log')
1585
1836
 
1586
1837
    def _do_skip(self, result, reason):
 
1838
        self._suppress_log()
1587
1839
        addSkip = getattr(result, 'addSkip', None)
1588
1840
        if not callable(addSkip):
1589
1841
            result.addSuccess(result)
1592
1844
 
1593
1845
    @staticmethod
1594
1846
    def _do_known_failure(self, result, e):
 
1847
        self._suppress_log()
1595
1848
        err = sys.exc_info()
1596
1849
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1597
1850
        if addExpectedFailure is not None:
1605
1858
            reason = 'No reason given'
1606
1859
        else:
1607
1860
            reason = e.args[0]
 
1861
        self._suppress_log ()
1608
1862
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1609
1863
        if addNotApplicable is not None:
1610
1864
            result.addNotApplicable(self, reason)
1612
1866
            self._do_skip(result, reason)
1613
1867
 
1614
1868
    @staticmethod
 
1869
    def _report_skip(self, result, err):
 
1870
        """Override the default _report_skip.
 
1871
 
 
1872
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1873
        already been formatted into the 'reason' string, and we can't pull it
 
1874
        out again.
 
1875
        """
 
1876
        self._suppress_log()
 
1877
        super(TestCase, self)._report_skip(self, result, err)
 
1878
 
 
1879
    @staticmethod
 
1880
    def _report_expected_failure(self, result, err):
 
1881
        """Strip the log.
 
1882
 
 
1883
        See _report_skip for motivation.
 
1884
        """
 
1885
        self._suppress_log()
 
1886
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1887
 
 
1888
    @staticmethod
1615
1889
    def _do_unsupported_or_skip(self, result, e):
1616
1890
        reason = e.args[0]
 
1891
        self._suppress_log()
1617
1892
        addNotSupported = getattr(result, 'addNotSupported', None)
1618
1893
        if addNotSupported is not None:
1619
1894
            result.addNotSupported(self, reason)
1645
1920
            self._benchtime += time.time() - start
1646
1921
 
1647
1922
    def log(self, *args):
1648
 
        mutter(*args)
1649
 
 
1650
 
    def _get_log(self, keep_log_file=False):
1651
 
        """Internal helper to get the log from bzrlib.trace for this test.
1652
 
 
1653
 
        Please use self.getDetails, or self.get_log to access this in test case
1654
 
        code.
1655
 
 
1656
 
        :param keep_log_file: When True, if the log is still a file on disk
1657
 
            leave it as a file on disk. When False, if the log is still a file
1658
 
            on disk, the log file is deleted and the log preserved as
1659
 
            self._log_contents.
1660
 
        :return: A string containing the log.
1661
 
        """
1662
 
        if self._log_contents is not None:
1663
 
            try:
1664
 
                self._log_contents.decode('utf8')
1665
 
            except UnicodeDecodeError:
1666
 
                unicodestr = self._log_contents.decode('utf8', 'replace')
1667
 
                self._log_contents = unicodestr.encode('utf8')
1668
 
            return self._log_contents
1669
 
        import bzrlib.trace
1670
 
        if bzrlib.trace._trace_file:
1671
 
            # flush the log file, to get all content
1672
 
            bzrlib.trace._trace_file.flush()
1673
 
        if self._log_file_name is not None:
1674
 
            logfile = open(self._log_file_name)
1675
 
            try:
1676
 
                log_contents = logfile.read()
1677
 
            finally:
1678
 
                logfile.close()
1679
 
            try:
1680
 
                log_contents.decode('utf8')
1681
 
            except UnicodeDecodeError:
1682
 
                unicodestr = log_contents.decode('utf8', 'replace')
1683
 
                log_contents = unicodestr.encode('utf8')
1684
 
            if not keep_log_file:
1685
 
                close_attempts = 0
1686
 
                max_close_attempts = 100
1687
 
                first_close_error = None
1688
 
                while close_attempts < max_close_attempts:
1689
 
                    close_attempts += 1
1690
 
                    try:
1691
 
                        self._log_file.close()
1692
 
                    except IOError, ioe:
1693
 
                        if ioe.errno is None:
1694
 
                            # No errno implies 'close() called during
1695
 
                            # concurrent operation on the same file object', so
1696
 
                            # retry.  Probably a thread is trying to write to
1697
 
                            # the log file.
1698
 
                            if first_close_error is None:
1699
 
                                first_close_error = ioe
1700
 
                            continue
1701
 
                        raise
1702
 
                    else:
1703
 
                        break
1704
 
                if close_attempts > 1:
1705
 
                    sys.stderr.write(
1706
 
                        'Unable to close log file on first attempt, '
1707
 
                        'will retry: %s\n' % (first_close_error,))
1708
 
                    if close_attempts == max_close_attempts:
1709
 
                        sys.stderr.write(
1710
 
                            'Unable to close log file after %d attempts.\n'
1711
 
                            % (max_close_attempts,))
1712
 
                self._log_file = None
1713
 
                # Permit multiple calls to get_log until we clean it up in
1714
 
                # finishLogFile
1715
 
                self._log_contents = log_contents
1716
 
                try:
1717
 
                    os.remove(self._log_file_name)
1718
 
                except OSError, e:
1719
 
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
1720
 
                        sys.stderr.write(('Unable to delete log file '
1721
 
                                             ' %r\n' % self._log_file_name))
1722
 
                    else:
1723
 
                        raise
1724
 
                self._log_file_name = None
1725
 
            return log_contents
1726
 
        else:
1727
 
            return "No log file content and no log file name."
 
1923
        trace.mutter(*args)
1728
1924
 
1729
1925
    def get_log(self):
1730
1926
        """Get a unicode string containing the log from bzrlib.trace.
1780
1976
 
1781
1977
        try:
1782
1978
            try:
1783
 
                result = self.apply_redirected(ui.ui_factory.stdin,
 
1979
                result = self.apply_redirected(
 
1980
                    ui.ui_factory.stdin,
1784
1981
                    stdout, stderr,
1785
 
                    bzrlib.commands.run_bzr_catch_user_errors,
 
1982
                    _mod_commands.run_bzr_catch_user_errors,
1786
1983
                    args)
1787
1984
            except KeyboardInterrupt:
1788
1985
                # Reraise KeyboardInterrupt with contents of redirected stdout
1930
2127
    def start_bzr_subprocess(self, process_args, env_changes=None,
1931
2128
                             skip_if_plan_to_signal=False,
1932
2129
                             working_dir=None,
1933
 
                             allow_plugins=False):
 
2130
                             allow_plugins=False, stderr=subprocess.PIPE):
1934
2131
        """Start bzr in a subprocess for testing.
1935
2132
 
1936
2133
        This starts a new Python interpreter and runs bzr in there.
1945
2142
            variables. A value of None will unset the env variable.
1946
2143
            The values must be strings. The change will only occur in the
1947
2144
            child, so you don't need to fix the environment after running.
1948
 
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
1949
 
            is not available.
 
2145
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2146
            doesn't support signalling subprocesses.
1950
2147
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
2148
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2149
            are those valid for the stderr argument of `subprocess.Popen`.
 
2150
            Default value is ``subprocess.PIPE``.
1951
2151
 
1952
2152
        :returns: Popen object for the started process.
1953
2153
        """
1954
2154
        if skip_if_plan_to_signal:
1955
 
            if not getattr(os, 'kill', None):
1956
 
                raise TestSkipped("os.kill not available.")
 
2155
            if os.name != "posix":
 
2156
                raise TestSkipped("Sending signals not supported")
1957
2157
 
1958
2158
        if env_changes is None:
1959
2159
            env_changes = {}
1979
2179
            # so we will avoid using it on all platforms, just to
1980
2180
            # make sure the code path is used, and we don't break on win32
1981
2181
            cleanup_environment()
 
2182
            # Include the subprocess's log file in the test details, in case
 
2183
            # the test fails due to an error in the subprocess.
 
2184
            self._add_subprocess_log(trace._get_bzr_log_filename())
1982
2185
            command = [sys.executable]
1983
2186
            # frozen executables don't need the path to bzr
1984
2187
            if getattr(sys, "frozen", None) is None:
1986
2189
            if not allow_plugins:
1987
2190
                command.append('--no-plugins')
1988
2191
            command.extend(process_args)
1989
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
2192
            process = self._popen(command, stdin=subprocess.PIPE,
 
2193
                                  stdout=subprocess.PIPE,
 
2194
                                  stderr=stderr)
1990
2195
        finally:
1991
2196
            restore_environment()
1992
2197
            if cwd is not None:
1994
2199
 
1995
2200
        return process
1996
2201
 
 
2202
    def _add_subprocess_log(self, log_file_path):
 
2203
        if len(self._log_files) == 0:
 
2204
            # Register an addCleanup func.  We do this on the first call to
 
2205
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2206
            # addCleanup is registered after any cleanups for tempdirs that
 
2207
            # subclasses might create, which will probably remove the log file
 
2208
            # we want to read.
 
2209
            self.addCleanup(self._subprocess_log_cleanup)
 
2210
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2211
        # twice.
 
2212
        self._log_files.add(log_file_path)
 
2213
 
 
2214
    def _subprocess_log_cleanup(self):
 
2215
        for count, log_file_path in enumerate(self._log_files):
 
2216
            # We use buffer_now=True to avoid holding the file open beyond
 
2217
            # the life of this function, which might interfere with e.g.
 
2218
            # cleaning tempdirs on Windows.
 
2219
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2220
            #detail_content = content.content_from_file(
 
2221
            #    log_file_path, buffer_now=True)
 
2222
            with open(log_file_path, 'rb') as log_file:
 
2223
                log_file_bytes = log_file.read()
 
2224
            detail_content = content.Content(content.ContentType("text",
 
2225
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2226
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2227
                detail_content)
 
2228
 
1997
2229
    def _popen(self, *args, **kwargs):
1998
2230
        """Place a call to Popen.
1999
2231
 
2000
2232
        Allows tests to override this method to intercept the calls made to
2001
2233
        Popen for introspection.
2002
2234
        """
2003
 
        return Popen(*args, **kwargs)
 
2235
        return subprocess.Popen(*args, **kwargs)
2004
2236
 
2005
2237
    def get_source_path(self):
2006
2238
        """Return the path of the directory containing bzrlib."""
2008
2240
 
2009
2241
    def get_bzr_path(self):
2010
2242
        """Return the path of the 'bzr' executable for this test suite."""
2011
 
        bzr_path = self.get_source_path()+'/bzr'
 
2243
        bzr_path = os.path.join(self.get_source_path(), "bzr")
2012
2244
        if not os.path.isfile(bzr_path):
2013
2245
            # We are probably installed. Assume sys.argv is the right file
2014
2246
            bzr_path = sys.argv[0]
2036
2268
        if retcode is not None and retcode != process.returncode:
2037
2269
            if process_args is None:
2038
2270
                process_args = "(unknown args)"
2039
 
            mutter('Output of bzr %s:\n%s', process_args, out)
2040
 
            mutter('Error for bzr %s:\n%s', process_args, err)
 
2271
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
 
2272
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
2041
2273
            self.fail('Command bzr %s failed with retcode %s != %s'
2042
2274
                      % (process_args, retcode, process.returncode))
2043
2275
        return [out, err]
2044
2276
 
2045
 
    def check_inventory_shape(self, inv, shape):
2046
 
        """Compare an inventory to a list of expected names.
 
2277
    def check_tree_shape(self, tree, shape):
 
2278
        """Compare a tree to a list of expected names.
2047
2279
 
2048
2280
        Fail if they are not precisely equal.
2049
2281
        """
2050
2282
        extras = []
2051
2283
        shape = list(shape)             # copy
2052
 
        for path, ie in inv.entries():
 
2284
        for path, ie in tree.iter_entries_by_dir():
2053
2285
            name = path.replace('\\', '/')
2054
2286
            if ie.kind == 'directory':
2055
2287
                name = name + '/'
2056
 
            if name in shape:
 
2288
            if name == "/":
 
2289
                pass # ignore root entry
 
2290
            elif name in shape:
2057
2291
                shape.remove(name)
2058
2292
            else:
2059
2293
                extras.append(name)
2100
2334
 
2101
2335
        Tests that expect to provoke LockContention errors should call this.
2102
2336
        """
2103
 
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2337
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2104
2338
 
2105
2339
    def make_utf8_encoded_stringio(self, encoding_type=None):
2106
2340
        """Return a StringIOWrapper instance, that will encode Unicode
2149
2383
class TestCaseWithMemoryTransport(TestCase):
2150
2384
    """Common test class for tests that do not need disk resources.
2151
2385
 
2152
 
    Tests that need disk resources should derive from TestCaseWithTransport.
 
2386
    Tests that need disk resources should derive from TestCaseInTempDir
 
2387
    orTestCaseWithTransport.
2153
2388
 
2154
2389
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
2155
2390
 
2156
 
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
2391
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2157
2392
    a directory which does not exist. This serves to help ensure test isolation
2158
 
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
2159
 
    must exist. However, TestCaseWithMemoryTransport does not offer local
2160
 
    file defaults for the transport in tests, nor does it obey the command line
 
2393
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2394
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2395
    defaults for the transport in tests, nor does it obey the command line
2161
2396
    override, so tests that accidentally write to the common directory should
2162
2397
    be rare.
2163
2398
 
2164
 
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
2165
 
    a .bzr directory that stops us ascending higher into the filesystem.
 
2399
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2400
        ``.bzr`` directory that stops us ascending higher into the filesystem.
2166
2401
    """
2167
2402
 
2168
2403
    TEST_ROOT = None
2186
2421
 
2187
2422
        :param relpath: a path relative to the base url.
2188
2423
        """
2189
 
        t = get_transport(self.get_url(relpath))
 
2424
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2190
2425
        self.assertFalse(t.is_readonly())
2191
2426
        return t
2192
2427
 
2198
2433
 
2199
2434
        :param relpath: a path relative to the base url.
2200
2435
        """
2201
 
        t = get_transport(self.get_readonly_url(relpath))
 
2436
        t = _mod_transport.get_transport_from_url(
 
2437
            self.get_readonly_url(relpath))
2202
2438
        self.assertTrue(t.is_readonly())
2203
2439
        return t
2204
2440
 
2325
2561
        real branch.
2326
2562
        """
2327
2563
        root = TestCaseWithMemoryTransport.TEST_ROOT
2328
 
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2564
        try:
 
2565
            # Make sure we get a readable and accessible home for .bzr.log
 
2566
            # and/or config files, and not fallback to weird defaults (see
 
2567
            # http://pad.lv/825027).
 
2568
            self.assertIs(None, os.environ.get('BZR_HOME', None))
 
2569
            os.environ['BZR_HOME'] = root
 
2570
            wt = bzrdir.BzrDir.create_standalone_workingtree(root)
 
2571
            del os.environ['BZR_HOME']
 
2572
        except Exception, e:
 
2573
            self.fail("Fail to initialize the safety net: %r\nExiting\n" % (e,))
 
2574
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2575
        # we don't need to re-open the wt to check it hasn't changed.
 
2576
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2577
            wt.control_transport.get_bytes('dirstate'))
2329
2578
 
2330
2579
    def _check_safety_net(self):
2331
2580
        """Check that the safety .bzr directory have not been touched.
2334
2583
        propagating. This method ensures than a test did not leaked.
2335
2584
        """
2336
2585
        root = TestCaseWithMemoryTransport.TEST_ROOT
2337
 
        self.permit_url(get_transport(root).base)
2338
 
        wt = workingtree.WorkingTree.open(root)
2339
 
        last_rev = wt.last_revision()
2340
 
        if last_rev != 'null:':
 
2586
        t = _mod_transport.get_transport_from_path(root)
 
2587
        self.permit_url(t.base)
 
2588
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2589
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2341
2590
            # The current test have modified the /bzr directory, we need to
2342
2591
            # recreate a new one or all the followng tests will fail.
2343
2592
            # If you need to inspect its content uncomment the following line
2385
2634
            # might be a relative or absolute path
2386
2635
            maybe_a_url = self.get_url(relpath)
2387
2636
            segments = maybe_a_url.rsplit('/', 1)
2388
 
            t = get_transport(maybe_a_url)
 
2637
            t = _mod_transport.get_transport(maybe_a_url)
2389
2638
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2390
2639
                t.ensure_base()
2391
2640
            if format is None:
2408
2657
        made_control = self.make_bzrdir(relpath, format=format)
2409
2658
        return made_control.create_repository(shared=shared)
2410
2659
 
2411
 
    def make_smart_server(self, path):
 
2660
    def make_smart_server(self, path, backing_server=None):
 
2661
        if backing_server is None:
 
2662
            backing_server = self.get_server()
2412
2663
        smart_server = test_server.SmartTCPServer_for_testing()
2413
 
        self.start_server(smart_server, self.get_server())
2414
 
        remote_transport = get_transport(smart_server.get_url()).clone(path)
 
2664
        self.start_server(smart_server, backing_server)
 
2665
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
 
2666
                                                   ).clone(path)
2415
2667
        return remote_transport
2416
2668
 
2417
2669
    def make_branch_and_memory_tree(self, relpath, format=None):
2427
2679
        test_home_dir = self.test_home_dir
2428
2680
        if isinstance(test_home_dir, unicode):
2429
2681
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2430
 
        os.environ['HOME'] = test_home_dir
2431
 
        os.environ['BZR_HOME'] = test_home_dir
 
2682
        self.overrideEnv('HOME', test_home_dir)
 
2683
        self.overrideEnv('BZR_HOME', test_home_dir)
2432
2684
 
2433
2685
    def setUp(self):
2434
2686
        super(TestCaseWithMemoryTransport, self).setUp()
 
2687
        # Ensure that ConnectedTransport doesn't leak sockets
 
2688
        def get_transport_from_url_with_cleanup(*args, **kwargs):
 
2689
            t = orig_get_transport_from_url(*args, **kwargs)
 
2690
            if isinstance(t, _mod_transport.ConnectedTransport):
 
2691
                self.addCleanup(t.disconnect)
 
2692
            return t
 
2693
 
 
2694
        orig_get_transport_from_url = self.overrideAttr(
 
2695
            _mod_transport, 'get_transport_from_url',
 
2696
            get_transport_from_url_with_cleanup)
2435
2697
        self._make_test_root()
2436
2698
        self.addCleanup(os.chdir, os.getcwdu())
2437
2699
        self.makeAndChdirToTestDir()
2480
2742
 
2481
2743
    OVERRIDE_PYTHON = 'python'
2482
2744
 
 
2745
    def setUp(self):
 
2746
        super(TestCaseInTempDir, self).setUp()
 
2747
        # Remove the protection set in isolated_environ, we have a proper
 
2748
        # access to disk resources now.
 
2749
        self.overrideEnv('BZR_LOG', None)
 
2750
 
2483
2751
    def check_file_contents(self, filename, expect):
2484
2752
        self.log("check contents of file %s" % filename)
2485
 
        contents = file(filename, 'r').read()
 
2753
        f = file(filename)
 
2754
        try:
 
2755
            contents = f.read()
 
2756
        finally:
 
2757
            f.close()
2486
2758
        if contents != expect:
2487
2759
            self.log("expected: %r" % expect)
2488
2760
            self.log("actually: %r" % contents)
2562
2834
                "a list or a tuple. Got %r instead" % (shape,))
2563
2835
        # It's OK to just create them using forward slashes on windows.
2564
2836
        if transport is None or transport.is_readonly():
2565
 
            transport = get_transport(".")
 
2837
            transport = _mod_transport.get_transport_from_path(".")
2566
2838
        for name in shape:
2567
2839
            self.assertIsInstance(name, basestring)
2568
2840
            if name[-1] == '/':
2725
2997
    """
2726
2998
 
2727
2999
    def setUp(self):
 
3000
        from bzrlib.tests import http_server
2728
3001
        super(ChrootedTestCase, self).setUp()
2729
3002
        if not self.vfs_transport_factory == memory.MemoryServer:
2730
 
            self.transport_readonly_server = HttpServer
 
3003
            self.transport_readonly_server = http_server.HttpServer
2731
3004
 
2732
3005
 
2733
3006
def condition_id_re(pattern):
2736
3009
    :param pattern: A regular expression string.
2737
3010
    :return: A callable that returns True if the re matches.
2738
3011
    """
2739
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2740
 
        'test filter')
 
3012
    filter_re = re.compile(pattern, 0)
2741
3013
    def condition(test):
2742
3014
        test_id = test.id()
2743
3015
        return filter_re.search(test_id)
2995
3267
 
2996
3268
 
2997
3269
def fork_decorator(suite):
 
3270
    if getattr(os, "fork", None) is None:
 
3271
        raise errors.BzrCommandError("platform does not support fork,"
 
3272
            " try --parallel=subprocess instead.")
2998
3273
    concurrency = osutils.local_concurrency()
2999
3274
    if concurrency == 1:
3000
3275
        return suite
3055
3330
    return suite
3056
3331
 
3057
3332
 
3058
 
class TestDecorator(TestSuite):
 
3333
class TestDecorator(TestUtil.TestSuite):
3059
3334
    """A decorator for TestCase/TestSuite objects.
3060
3335
    
3061
3336
    Usually, subclasses should override __iter__(used when flattening test
3064
3339
    """
3065
3340
 
3066
3341
    def __init__(self, suite):
3067
 
        TestSuite.__init__(self)
 
3342
        TestUtil.TestSuite.__init__(self)
3068
3343
        self.addTest(suite)
3069
3344
 
3070
3345
    def countTestCases(self):
3189
3464
 
3190
3465
def partition_tests(suite, count):
3191
3466
    """Partition suite into count lists of tests."""
3192
 
    result = []
3193
 
    tests = list(iter_suite_tests(suite))
3194
 
    tests_per_process = int(math.ceil(float(len(tests)) / count))
3195
 
    for block in range(count):
3196
 
        low_test = block * tests_per_process
3197
 
        high_test = low_test + tests_per_process
3198
 
        process_tests = tests[low_test:high_test]
3199
 
        result.append(process_tests)
3200
 
    return result
 
3467
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3468
    # splits up blocks of related tests that might run faster if they shared
 
3469
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3470
    # just one partition.  So the slowest partition shouldn't be much slower
 
3471
    # than the fastest.
 
3472
    partitions = [list() for i in range(count)]
 
3473
    tests = iter_suite_tests(suite)
 
3474
    for partition, test in itertools.izip(itertools.cycle(partitions), tests):
 
3475
        partition.append(test)
 
3476
    return partitions
3201
3477
 
3202
3478
 
3203
3479
def workaround_zealous_crypto_random():
3237
3513
 
3238
3514
    test_blocks = partition_tests(suite, concurrency)
3239
3515
    for process_tests in test_blocks:
3240
 
        process_suite = TestSuite()
 
3516
        process_suite = TestUtil.TestSuite()
3241
3517
        process_suite.addTests(process_tests)
3242
3518
        c2pread, c2pwrite = os.pipe()
3243
3519
        pid = os.fork()
3309
3585
                '--subunit']
3310
3586
            if '--no-plugins' in sys.argv:
3311
3587
                argv.append('--no-plugins')
3312
 
            # stderr=STDOUT would be ideal, but until we prevent noise on
3313
 
            # stderr it can interrupt the subunit protocol.
3314
 
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3315
 
                bufsize=1)
 
3588
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3589
            # noise on stderr it can interrupt the subunit protocol.
 
3590
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3591
                                      stdout=subprocess.PIPE,
 
3592
                                      stderr=subprocess.PIPE,
 
3593
                                      bufsize=1)
3316
3594
            test = TestInSubprocess(process, test_list_file_name)
3317
3595
            result.append(test)
3318
3596
        except:
3321
3599
    return result
3322
3600
 
3323
3601
 
3324
 
class ForwardingResult(unittest.TestResult):
3325
 
 
3326
 
    def __init__(self, target):
3327
 
        unittest.TestResult.__init__(self)
3328
 
        self.result = target
3329
 
 
3330
 
    def startTest(self, test):
3331
 
        self.result.startTest(test)
3332
 
 
3333
 
    def stopTest(self, test):
3334
 
        self.result.stopTest(test)
3335
 
 
3336
 
    def startTestRun(self):
3337
 
        self.result.startTestRun()
3338
 
 
3339
 
    def stopTestRun(self):
3340
 
        self.result.stopTestRun()
3341
 
 
3342
 
    def addSkip(self, test, reason):
3343
 
        self.result.addSkip(test, reason)
3344
 
 
3345
 
    def addSuccess(self, test):
3346
 
        self.result.addSuccess(test)
3347
 
 
3348
 
    def addError(self, test, err):
3349
 
        self.result.addError(test, err)
3350
 
 
3351
 
    def addFailure(self, test, err):
3352
 
        self.result.addFailure(test, err)
3353
 
ForwardingResult = testtools.ExtendedToOriginalDecorator
3354
 
 
3355
 
 
3356
 
class ProfileResult(ForwardingResult):
 
3602
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3357
3603
    """Generate profiling data for all activity between start and success.
3358
3604
    
3359
3605
    The profile data is appended to the test's _benchcalls attribute and can
3367
3613
 
3368
3614
    def startTest(self, test):
3369
3615
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3616
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3617
        # unavoidably fail.
 
3618
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3370
3619
        self.profiler.start()
3371
 
        ForwardingResult.startTest(self, test)
 
3620
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3372
3621
 
3373
3622
    def addSuccess(self, test):
3374
3623
        stats = self.profiler.stop()
3378
3627
            test._benchcalls = []
3379
3628
            calls = test._benchcalls
3380
3629
        calls.append(((test.id(), "", ""), stats))
3381
 
        ForwardingResult.addSuccess(self, test)
 
3630
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3382
3631
 
3383
3632
    def stopTest(self, test):
3384
 
        ForwardingResult.stopTest(self, test)
 
3633
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3385
3634
        self.profiler = None
3386
3635
 
3387
3636
 
3393
3642
#                           rather than failing tests. And no longer raise
3394
3643
#                           LockContention when fctnl locks are not being used
3395
3644
#                           with proper exclusion rules.
 
3645
#   -Ethreads               Will display thread ident at creation/join time to
 
3646
#                           help track thread leaks
 
3647
 
 
3648
#   -Econfig_stats          Will collect statistics using addDetail
3396
3649
selftest_debug_flags = set()
3397
3650
 
3398
3651
 
3592
3845
                key, obj, help=help, info=info, override_existing=False)
3593
3846
        except KeyError:
3594
3847
            actual = self.get(key)
3595
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3596
 
                 % (key, actual, obj))
 
3848
            trace.note(
 
3849
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3850
                % (key, actual, obj))
3597
3851
 
3598
3852
    def resolve_alias(self, id_start):
3599
3853
        """Replace the alias by the prefix in the given string.
3631
3885
        'bzrlib.doc',
3632
3886
        'bzrlib.tests.blackbox',
3633
3887
        'bzrlib.tests.commands',
 
3888
        'bzrlib.tests.doc_generate',
3634
3889
        'bzrlib.tests.per_branch',
3635
3890
        'bzrlib.tests.per_bzrdir',
3636
 
        'bzrlib.tests.per_bzrdir_colo',
 
3891
        'bzrlib.tests.per_controldir',
 
3892
        'bzrlib.tests.per_controldir_colo',
3637
3893
        'bzrlib.tests.per_foreign_vcs',
3638
3894
        'bzrlib.tests.per_interrepository',
3639
3895
        'bzrlib.tests.per_intertree',
3647
3903
        'bzrlib.tests.per_repository',
3648
3904
        'bzrlib.tests.per_repository_chk',
3649
3905
        'bzrlib.tests.per_repository_reference',
 
3906
        'bzrlib.tests.per_repository_vf',
3650
3907
        'bzrlib.tests.per_uifactory',
3651
3908
        'bzrlib.tests.per_versionedfile',
3652
3909
        'bzrlib.tests.per_workingtree',
3653
3910
        'bzrlib.tests.test__annotator',
3654
3911
        'bzrlib.tests.test__bencode',
 
3912
        'bzrlib.tests.test__btree_serializer',
3655
3913
        'bzrlib.tests.test__chk_map',
3656
3914
        'bzrlib.tests.test__dirstate_helpers',
3657
3915
        'bzrlib.tests.test__groupcompress',
3685
3943
        'bzrlib.tests.test_commit_merge',
3686
3944
        'bzrlib.tests.test_config',
3687
3945
        'bzrlib.tests.test_conflicts',
 
3946
        'bzrlib.tests.test_controldir',
3688
3947
        'bzrlib.tests.test_counted_lock',
3689
3948
        'bzrlib.tests.test_crash',
3690
3949
        'bzrlib.tests.test_decorators',
3691
3950
        'bzrlib.tests.test_delta',
3692
3951
        'bzrlib.tests.test_debug',
3693
 
        'bzrlib.tests.test_deprecated_graph',
3694
3952
        'bzrlib.tests.test_diff',
3695
3953
        'bzrlib.tests.test_directory_service',
3696
3954
        'bzrlib.tests.test_dirstate',
3698
3956
        'bzrlib.tests.test_eol_filters',
3699
3957
        'bzrlib.tests.test_errors',
3700
3958
        'bzrlib.tests.test_export',
 
3959
        'bzrlib.tests.test_export_pot',
3701
3960
        'bzrlib.tests.test_extract',
 
3961
        'bzrlib.tests.test_features',
3702
3962
        'bzrlib.tests.test_fetch',
 
3963
        'bzrlib.tests.test_fixtures',
3703
3964
        'bzrlib.tests.test_fifo_cache',
3704
3965
        'bzrlib.tests.test_filters',
 
3966
        'bzrlib.tests.test_filter_tree',
3705
3967
        'bzrlib.tests.test_ftp_transport',
3706
3968
        'bzrlib.tests.test_foreign',
3707
3969
        'bzrlib.tests.test_generate_docs',
3716
3978
        'bzrlib.tests.test_http',
3717
3979
        'bzrlib.tests.test_http_response',
3718
3980
        'bzrlib.tests.test_https_ca_bundle',
 
3981
        'bzrlib.tests.test_i18n',
3719
3982
        'bzrlib.tests.test_identitymap',
3720
3983
        'bzrlib.tests.test_ignores',
3721
3984
        'bzrlib.tests.test_index',
3726
3989
        'bzrlib.tests.test_knit',
3727
3990
        'bzrlib.tests.test_lazy_import',
3728
3991
        'bzrlib.tests.test_lazy_regex',
 
3992
        'bzrlib.tests.test_library_state',
3729
3993
        'bzrlib.tests.test_lock',
3730
3994
        'bzrlib.tests.test_lockable_files',
3731
3995
        'bzrlib.tests.test_lockdir',
3733
3997
        'bzrlib.tests.test_lru_cache',
3734
3998
        'bzrlib.tests.test_lsprof',
3735
3999
        'bzrlib.tests.test_mail_client',
 
4000
        'bzrlib.tests.test_matchers',
3736
4001
        'bzrlib.tests.test_memorytree',
3737
4002
        'bzrlib.tests.test_merge',
3738
4003
        'bzrlib.tests.test_merge3',
3739
4004
        'bzrlib.tests.test_merge_core',
3740
4005
        'bzrlib.tests.test_merge_directive',
 
4006
        'bzrlib.tests.test_mergetools',
3741
4007
        'bzrlib.tests.test_missing',
3742
4008
        'bzrlib.tests.test_msgeditor',
3743
4009
        'bzrlib.tests.test_multiparent',
3752
4018
        'bzrlib.tests.test_permissions',
3753
4019
        'bzrlib.tests.test_plugins',
3754
4020
        'bzrlib.tests.test_progress',
 
4021
        'bzrlib.tests.test_pyutils',
3755
4022
        'bzrlib.tests.test_read_bundle',
3756
4023
        'bzrlib.tests.test_reconcile',
3757
4024
        'bzrlib.tests.test_reconfigure',
3766
4033
        'bzrlib.tests.test_rio',
3767
4034
        'bzrlib.tests.test_rules',
3768
4035
        'bzrlib.tests.test_sampler',
 
4036
        'bzrlib.tests.test_scenarios',
3769
4037
        'bzrlib.tests.test_script',
3770
4038
        'bzrlib.tests.test_selftest',
3771
4039
        'bzrlib.tests.test_serializer',
3787
4055
        'bzrlib.tests.test_switch',
3788
4056
        'bzrlib.tests.test_symbol_versioning',
3789
4057
        'bzrlib.tests.test_tag',
 
4058
        'bzrlib.tests.test_test_server',
3790
4059
        'bzrlib.tests.test_testament',
3791
4060
        'bzrlib.tests.test_textfile',
3792
4061
        'bzrlib.tests.test_textmerge',
 
4062
        'bzrlib.tests.test_cethread',
3793
4063
        'bzrlib.tests.test_timestamp',
3794
4064
        'bzrlib.tests.test_trace',
3795
4065
        'bzrlib.tests.test_transactions',
3798
4068
        'bzrlib.tests.test_transport_log',
3799
4069
        'bzrlib.tests.test_tree',
3800
4070
        'bzrlib.tests.test_treebuilder',
 
4071
        'bzrlib.tests.test_treeshape',
3801
4072
        'bzrlib.tests.test_tsort',
3802
4073
        'bzrlib.tests.test_tuned_gzip',
3803
4074
        'bzrlib.tests.test_ui',
3805
4076
        'bzrlib.tests.test_upgrade',
3806
4077
        'bzrlib.tests.test_upgrade_stacked',
3807
4078
        'bzrlib.tests.test_urlutils',
 
4079
        'bzrlib.tests.test_utextwrap',
3808
4080
        'bzrlib.tests.test_version',
3809
4081
        'bzrlib.tests.test_version_info',
 
4082
        'bzrlib.tests.test_versionedfile',
3810
4083
        'bzrlib.tests.test_weave',
3811
4084
        'bzrlib.tests.test_whitebox',
3812
4085
        'bzrlib.tests.test_win32utils',
3826
4099
        'bzrlib',
3827
4100
        'bzrlib.branchbuilder',
3828
4101
        'bzrlib.decorators',
3829
 
        'bzrlib.export',
3830
4102
        'bzrlib.inventory',
3831
4103
        'bzrlib.iterablefile',
3832
4104
        'bzrlib.lockdir',
3833
4105
        'bzrlib.merge3',
3834
4106
        'bzrlib.option',
 
4107
        'bzrlib.pyutils',
3835
4108
        'bzrlib.symbol_versioning',
3836
4109
        'bzrlib.tests',
 
4110
        'bzrlib.tests.fixtures',
3837
4111
        'bzrlib.timestamp',
 
4112
        'bzrlib.transport.http',
3838
4113
        'bzrlib.version_info_formats.format_custom',
3839
4114
        ]
3840
4115
 
3893
4168
        try:
3894
4169
            # note that this really does mean "report only" -- doctest
3895
4170
            # still runs the rest of the examples
3896
 
            doc_suite = doctest.DocTestSuite(mod,
3897
 
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4171
            doc_suite = IsolatedDocTestSuite(
 
4172
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3898
4173
        except ValueError, e:
3899
4174
            print '**failed to get doctest for: %s\n%s' % (mod, e)
3900
4175
            raise
3903
4178
        suite.addTest(doc_suite)
3904
4179
 
3905
4180
    default_encoding = sys.getdefaultencoding()
3906
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4181
    for name, plugin in _mod_plugin.plugins().items():
3907
4182
        if not interesting_module(plugin.module.__name__):
3908
4183
            continue
3909
4184
        plugin_suite = plugin.test_suite()
3915
4190
        if plugin_suite is not None:
3916
4191
            suite.addTest(plugin_suite)
3917
4192
        if default_encoding != sys.getdefaultencoding():
3918
 
            bzrlib.trace.warning(
 
4193
            trace.warning(
3919
4194
                'Plugin "%s" tried to reset default encoding to: %s', name,
3920
4195
                sys.getdefaultencoding())
3921
4196
            reload(sys)
3936
4211
            # Some tests mentioned in the list are not in the test suite. The
3937
4212
            # list may be out of date, report to the tester.
3938
4213
            for id in not_found:
3939
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4214
                trace.warning('"%s" not found in the test suite', id)
3940
4215
        for id in duplicates:
3941
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4216
            trace.warning('"%s" is used as an id by several tests', id)
3942
4217
 
3943
4218
    return suite
3944
4219
 
3945
4220
 
3946
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4221
def multiply_scenarios(*scenarios):
 
4222
    """Multiply two or more iterables of scenarios.
 
4223
 
 
4224
    It is safe to pass scenario generators or iterators.
 
4225
 
 
4226
    :returns: A list of compound scenarios: the cross-product of all 
 
4227
        scenarios, with the names concatenated and the parameters
 
4228
        merged together.
 
4229
    """
 
4230
    return reduce(_multiply_two_scenarios, map(list, scenarios))
 
4231
 
 
4232
 
 
4233
def _multiply_two_scenarios(scenarios_left, scenarios_right):
3947
4234
    """Multiply two sets of scenarios.
3948
4235
 
3949
4236
    :returns: the cartesian product of the two sets of scenarios, that is
3980
4267
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
3981
4268
    ...     [('one', dict(param=1)),
3982
4269
    ...      ('two', dict(param=2))],
3983
 
    ...     TestSuite())
 
4270
    ...     TestUtil.TestSuite())
3984
4271
    >>> tests = list(iter_suite_tests(r))
3985
4272
    >>> len(tests)
3986
4273
    2
4033
4320
    :param new_id: The id to assign to it.
4034
4321
    :return: The new test.
4035
4322
    """
4036
 
    new_test = copy(test)
 
4323
    new_test = copy.copy(test)
4037
4324
    new_test.id = lambda: new_id
 
4325
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4326
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4327
    # read the test output for parameterized tests, because tracebacks will be
 
4328
    # associated with irrelevant tests.
 
4329
    try:
 
4330
        details = new_test._TestCase__details
 
4331
    except AttributeError:
 
4332
        # must be a different version of testtools than expected.  Do nothing.
 
4333
        pass
 
4334
    else:
 
4335
        # Reset the '__details' dict.
 
4336
        new_test._TestCase__details = {}
4038
4337
    return new_test
4039
4338
 
4040
4339
 
4061
4360
        the module is available.
4062
4361
    """
4063
4362
 
4064
 
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4363
    from bzrlib.tests.features import ModuleAvailableFeature
 
4364
    py_module = pyutils.get_named_object(py_module_name)
4065
4365
    scenarios = [
4066
4366
        ('python', {'module': py_module}),
4067
4367
    ]
4100
4400
        if test_id != None:
4101
4401
            ui.ui_factory.clear_term()
4102
4402
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4403
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4404
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4405
                                    ).encode('ascii', 'replace')
4103
4406
        sys.stderr.write('Unable to remove testing dir %s\n%s'
4104
 
                         % (os.path.basename(dirname), e))
4105
 
 
4106
 
 
4107
 
class Feature(object):
4108
 
    """An operating system Feature."""
4109
 
 
4110
 
    def __init__(self):
4111
 
        self._available = None
4112
 
 
4113
 
    def available(self):
4114
 
        """Is the feature available?
4115
 
 
4116
 
        :return: True if the feature is available.
4117
 
        """
4118
 
        if self._available is None:
4119
 
            self._available = self._probe()
4120
 
        return self._available
4121
 
 
4122
 
    def _probe(self):
4123
 
        """Implement this method in concrete features.
4124
 
 
4125
 
        :return: True if the feature is available.
4126
 
        """
4127
 
        raise NotImplementedError
4128
 
 
4129
 
    def __str__(self):
4130
 
        if getattr(self, 'feature_name', None):
4131
 
            return self.feature_name()
4132
 
        return self.__class__.__name__
4133
 
 
4134
 
 
4135
 
class _SymlinkFeature(Feature):
4136
 
 
4137
 
    def _probe(self):
4138
 
        return osutils.has_symlinks()
4139
 
 
4140
 
    def feature_name(self):
4141
 
        return 'symlinks'
4142
 
 
4143
 
SymlinkFeature = _SymlinkFeature()
4144
 
 
4145
 
 
4146
 
class _HardlinkFeature(Feature):
4147
 
 
4148
 
    def _probe(self):
4149
 
        return osutils.has_hardlinks()
4150
 
 
4151
 
    def feature_name(self):
4152
 
        return 'hardlinks'
4153
 
 
4154
 
HardlinkFeature = _HardlinkFeature()
4155
 
 
4156
 
 
4157
 
class _OsFifoFeature(Feature):
4158
 
 
4159
 
    def _probe(self):
4160
 
        return getattr(os, 'mkfifo', None)
4161
 
 
4162
 
    def feature_name(self):
4163
 
        return 'filesystem fifos'
4164
 
 
4165
 
OsFifoFeature = _OsFifoFeature()
4166
 
 
4167
 
 
4168
 
class _UnicodeFilenameFeature(Feature):
4169
 
    """Does the filesystem support Unicode filenames?"""
4170
 
 
4171
 
    def _probe(self):
4172
 
        try:
4173
 
            # Check for character combinations unlikely to be covered by any
4174
 
            # single non-unicode encoding. We use the characters
4175
 
            # - greek small letter alpha (U+03B1) and
4176
 
            # - braille pattern dots-123456 (U+283F).
4177
 
            os.stat(u'\u03b1\u283f')
4178
 
        except UnicodeEncodeError:
4179
 
            return False
4180
 
        except (IOError, OSError):
4181
 
            # The filesystem allows the Unicode filename but the file doesn't
4182
 
            # exist.
4183
 
            return True
4184
 
        else:
4185
 
            # The filesystem allows the Unicode filename and the file exists,
4186
 
            # for some reason.
4187
 
            return True
4188
 
 
4189
 
UnicodeFilenameFeature = _UnicodeFilenameFeature()
4190
 
 
4191
 
 
4192
 
class _CompatabilityThunkFeature(Feature):
4193
 
    """This feature is just a thunk to another feature.
4194
 
 
4195
 
    It issues a deprecation warning if it is accessed, to let you know that you
4196
 
    should really use a different feature.
4197
 
    """
4198
 
 
4199
 
    def __init__(self, dep_version, module, name,
4200
 
                 replacement_name, replacement_module=None):
4201
 
        super(_CompatabilityThunkFeature, self).__init__()
4202
 
        self._module = module
4203
 
        if replacement_module is None:
4204
 
            replacement_module = module
4205
 
        self._replacement_module = replacement_module
4206
 
        self._name = name
4207
 
        self._replacement_name = replacement_name
4208
 
        self._dep_version = dep_version
4209
 
        self._feature = None
4210
 
 
4211
 
    def _ensure(self):
4212
 
        if self._feature is None:
4213
 
            depr_msg = self._dep_version % ('%s.%s'
4214
 
                                            % (self._module, self._name))
4215
 
            use_msg = ' Use %s.%s instead.' % (self._replacement_module,
4216
 
                                               self._replacement_name)
4217
 
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
4218
 
            # Import the new feature and use it as a replacement for the
4219
 
            # deprecated one.
4220
 
            mod = __import__(self._replacement_module, {}, {},
4221
 
                             [self._replacement_name])
4222
 
            self._feature = getattr(mod, self._replacement_name)
4223
 
 
4224
 
    def _probe(self):
4225
 
        self._ensure()
4226
 
        return self._feature._probe()
4227
 
 
4228
 
 
4229
 
class ModuleAvailableFeature(Feature):
4230
 
    """This is a feature than describes a module we want to be available.
4231
 
 
4232
 
    Declare the name of the module in __init__(), and then after probing, the
4233
 
    module will be available as 'self.module'.
4234
 
 
4235
 
    :ivar module: The module if it is available, else None.
4236
 
    """
4237
 
 
4238
 
    def __init__(self, module_name):
4239
 
        super(ModuleAvailableFeature, self).__init__()
4240
 
        self.module_name = module_name
4241
 
 
4242
 
    def _probe(self):
4243
 
        try:
4244
 
            self._module = __import__(self.module_name, {}, {}, [''])
4245
 
            return True
4246
 
        except ImportError:
4247
 
            return False
4248
 
 
4249
 
    @property
4250
 
    def module(self):
4251
 
        if self.available(): # Make sure the probe has been done
4252
 
            return self._module
4253
 
        return None
4254
 
 
4255
 
    def feature_name(self):
4256
 
        return self.module_name
4257
 
 
4258
 
 
4259
 
# This is kept here for compatibility, it is recommended to use
4260
 
# 'bzrlib.tests.feature.paramiko' instead
4261
 
ParamikoFeature = _CompatabilityThunkFeature(
4262
 
    deprecated_in((2,1,0)),
4263
 
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
 
4407
                         % (os.path.basename(dirname), printable_e))
4264
4408
 
4265
4409
 
4266
4410
def probe_unicode_in_user_encoding():
4296
4440
    return None
4297
4441
 
4298
4442
 
4299
 
class _HTTPSServerFeature(Feature):
4300
 
    """Some tests want an https Server, check if one is available.
4301
 
 
4302
 
    Right now, the only way this is available is under python2.6 which provides
4303
 
    an ssl module.
4304
 
    """
4305
 
 
4306
 
    def _probe(self):
4307
 
        try:
4308
 
            import ssl
4309
 
            return True
4310
 
        except ImportError:
4311
 
            return False
4312
 
 
4313
 
    def feature_name(self):
4314
 
        return 'HTTPSServer'
4315
 
 
4316
 
 
4317
 
HTTPSServerFeature = _HTTPSServerFeature()
4318
 
 
4319
 
 
4320
 
class _UnicodeFilename(Feature):
4321
 
    """Does the filesystem support Unicode filenames?"""
4322
 
 
4323
 
    def _probe(self):
4324
 
        try:
4325
 
            os.stat(u'\u03b1')
4326
 
        except UnicodeEncodeError:
4327
 
            return False
4328
 
        except (IOError, OSError):
4329
 
            # The filesystem allows the Unicode filename but the file doesn't
4330
 
            # exist.
4331
 
            return True
4332
 
        else:
4333
 
            # The filesystem allows the Unicode filename and the file exists,
4334
 
            # for some reason.
4335
 
            return True
4336
 
 
4337
 
UnicodeFilename = _UnicodeFilename()
4338
 
 
4339
 
 
4340
 
class _UTF8Filesystem(Feature):
4341
 
    """Is the filesystem UTF-8?"""
4342
 
 
4343
 
    def _probe(self):
4344
 
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
4345
 
            return True
4346
 
        return False
4347
 
 
4348
 
UTF8Filesystem = _UTF8Filesystem()
4349
 
 
4350
 
 
4351
 
class _BreakinFeature(Feature):
4352
 
    """Does this platform support the breakin feature?"""
4353
 
 
4354
 
    def _probe(self):
4355
 
        from bzrlib import breakin
4356
 
        if breakin.determine_signal() is None:
4357
 
            return False
4358
 
        if sys.platform == 'win32':
4359
 
            # Windows doesn't have os.kill, and we catch the SIGBREAK signal.
4360
 
            # We trigger SIGBREAK via a Console api so we need ctypes to
4361
 
            # access the function
4362
 
            try:
4363
 
                import ctypes
4364
 
            except OSError:
4365
 
                return False
4366
 
        return True
4367
 
 
4368
 
    def feature_name(self):
4369
 
        return "SIGQUIT or SIGBREAK w/ctypes on win32"
4370
 
 
4371
 
 
4372
 
BreakinFeature = _BreakinFeature()
4373
 
 
4374
 
 
4375
 
class _CaseInsCasePresFilenameFeature(Feature):
4376
 
    """Is the file-system case insensitive, but case-preserving?"""
4377
 
 
4378
 
    def _probe(self):
4379
 
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
4380
 
        try:
4381
 
            # first check truly case-preserving for created files, then check
4382
 
            # case insensitive when opening existing files.
4383
 
            name = osutils.normpath(name)
4384
 
            base, rel = osutils.split(name)
4385
 
            found_rel = osutils.canonical_relpath(base, name)
4386
 
            return (found_rel == rel
4387
 
                    and os.path.isfile(name.upper())
4388
 
                    and os.path.isfile(name.lower()))
4389
 
        finally:
4390
 
            os.close(fileno)
4391
 
            os.remove(name)
4392
 
 
4393
 
    def feature_name(self):
4394
 
        return "case-insensitive case-preserving filesystem"
4395
 
 
4396
 
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
4397
 
 
4398
 
 
4399
 
class _CaseInsensitiveFilesystemFeature(Feature):
4400
 
    """Check if underlying filesystem is case-insensitive but *not* case
4401
 
    preserving.
4402
 
    """
4403
 
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
4404
 
    # more likely to be case preserving, so this case is rare.
4405
 
 
4406
 
    def _probe(self):
4407
 
        if CaseInsCasePresFilenameFeature.available():
4408
 
            return False
4409
 
 
4410
 
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
4411
 
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
4412
 
            TestCaseWithMemoryTransport.TEST_ROOT = root
4413
 
        else:
4414
 
            root = TestCaseWithMemoryTransport.TEST_ROOT
4415
 
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
4416
 
            dir=root)
4417
 
        name_a = osutils.pathjoin(tdir, 'a')
4418
 
        name_A = osutils.pathjoin(tdir, 'A')
4419
 
        os.mkdir(name_a)
4420
 
        result = osutils.isdir(name_A)
4421
 
        _rmtree_temp_dir(tdir)
4422
 
        return result
4423
 
 
4424
 
    def feature_name(self):
4425
 
        return 'case-insensitive filesystem'
4426
 
 
4427
 
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
4428
 
 
4429
 
 
4430
 
class _CaseSensitiveFilesystemFeature(Feature):
4431
 
 
4432
 
    def _probe(self):
4433
 
        if CaseInsCasePresFilenameFeature.available():
4434
 
            return False
4435
 
        elif CaseInsensitiveFilesystemFeature.available():
4436
 
            return False
4437
 
        else:
4438
 
            return True
4439
 
 
4440
 
    def feature_name(self):
4441
 
        return 'case-sensitive filesystem'
4442
 
 
4443
 
# new coding style is for feature instances to be lowercase
4444
 
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
4445
 
 
4446
 
 
4447
 
# Kept for compatibility, use bzrlib.tests.features.subunit instead
4448
 
SubUnitFeature = _CompatabilityThunkFeature(
4449
 
    deprecated_in((2,1,0)),
4450
 
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
4451
4443
# Only define SubUnitBzrRunner if subunit is available.
4452
4444
try:
4453
4445
    from subunit import TestProtocolClient
4454
4446
    from subunit.test_results import AutoTimingTestResultDecorator
 
4447
    class SubUnitBzrProtocolClient(TestProtocolClient):
 
4448
 
 
4449
        def addSuccess(self, test, details=None):
 
4450
            # The subunit client always includes the details in the subunit
 
4451
            # stream, but we don't want to include it in ours.
 
4452
            if details is not None and 'log' in details:
 
4453
                del details['log']
 
4454
            return super(SubUnitBzrProtocolClient, self).addSuccess(
 
4455
                test, details)
 
4456
 
4455
4457
    class SubUnitBzrRunner(TextTestRunner):
4456
4458
        def run(self, test):
4457
4459
            result = AutoTimingTestResultDecorator(
4458
 
                TestProtocolClient(self.stream))
 
4460
                SubUnitBzrProtocolClient(self.stream))
4459
4461
            test.run(result)
4460
4462
            return result
4461
4463
except ImportError:
4462
4464
    pass
4463
4465
 
4464
 
class _PosixPermissionsFeature(Feature):
4465
 
 
4466
 
    def _probe(self):
4467
 
        def has_perms():
4468
 
            # create temporary file and check if specified perms are maintained.
4469
 
            import tempfile
4470
 
 
4471
 
            write_perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
4472
 
            f = tempfile.mkstemp(prefix='bzr_perms_chk_')
4473
 
            fd, name = f
4474
 
            os.close(fd)
4475
 
            os.chmod(name, write_perms)
4476
 
 
4477
 
            read_perms = os.stat(name).st_mode & 0777
4478
 
            os.unlink(name)
4479
 
            return (write_perms == read_perms)
4480
 
 
4481
 
        return (os.name == 'posix') and has_perms()
4482
 
 
4483
 
    def feature_name(self):
4484
 
        return 'POSIX permissions support'
4485
 
 
4486
 
posix_permissions_feature = _PosixPermissionsFeature()
 
4466
 
 
4467
@deprecated_function(deprecated_in((2, 5, 0)))
 
4468
def ModuleAvailableFeature(name):
 
4469
    from bzrlib.tests import features
 
4470
    return features.ModuleAvailableFeature(name)
 
4471