~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Martin Pool
  • Date: 2011-06-14 02:21:41 UTC
  • mto: This revision was merged to the branch mainline in revision 6001.
  • Revision ID: mbp@canonical.com-20110614022141-18hmm7s0iw3utcbj
Deprecate __contains__ on Tree and Inventory

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
29
29
 
30
30
import atexit
31
31
import codecs
32
 
from copy import copy
 
32
import copy
33
33
from cStringIO import StringIO
34
34
import difflib
35
35
import doctest
36
36
import errno
 
37
import itertools
37
38
import logging
38
 
import math
39
39
import os
40
 
from pprint import pformat
 
40
import platform
 
41
import pprint
41
42
import random
42
43
import re
43
44
import shlex
44
45
import stat
45
 
from subprocess import Popen, PIPE, STDOUT
 
46
import subprocess
46
47
import sys
47
48
import tempfile
48
49
import threading
54
55
import testtools
55
56
# nb: check this before importing anything else from within it
56
57
_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"
 
58
if _testtools_version < (0, 9, 5):
 
59
    raise ImportError("need at least testtools 0.9.5: %s is %r"
59
60
        % (testtools.__file__, _testtools_version))
60
61
from testtools import content
61
62
 
 
63
import bzrlib
62
64
from bzrlib import (
63
65
    branchbuilder,
64
66
    bzrdir,
65
67
    chk_map,
 
68
    commands as _mod_commands,
66
69
    config,
67
70
    debug,
68
71
    errors,
69
72
    hooks,
70
73
    lock as _mod_lock,
 
74
    lockdir,
71
75
    memorytree,
72
76
    osutils,
73
 
    progress,
 
77
    plugin as _mod_plugin,
 
78
    pyutils,
74
79
    ui,
75
80
    urlutils,
76
81
    registry,
 
82
    symbol_versioning,
 
83
    trace,
 
84
    transport as _mod_transport,
77
85
    workingtree,
78
86
    )
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
87
try:
87
88
    import bzrlib.lsprof
88
89
except ImportError:
89
90
    # lsprof not available
90
91
    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
97
 
from bzrlib.symbol_versioning import (
98
 
    DEPRECATED_PARAMETER,
99
 
    deprecated_function,
100
 
    deprecated_in,
101
 
    deprecated_method,
102
 
    deprecated_passed,
103
 
    )
104
 
import bzrlib.trace
 
92
from bzrlib.smart import client, request
105
93
from bzrlib.transport import (
106
 
    get_transport,
107
94
    memory,
108
95
    pathfilter,
109
96
    )
110
 
import bzrlib.transport
111
 
from bzrlib.trace import mutter, note
112
97
from bzrlib.tests import (
113
98
    test_server,
114
99
    TestUtil,
 
100
    treeshape,
115
101
    )
116
 
from bzrlib.tests.http_server import HttpServer
117
 
from bzrlib.tests.TestUtil import (
118
 
                          TestSuite,
119
 
                          TestLoader,
120
 
                          )
121
 
from bzrlib.tests.treeshape import build_tree_contents
122
102
from bzrlib.ui import NullProgressView
123
103
from bzrlib.ui.text import TextUIFactory
124
 
import bzrlib.version_info_formats.format_custom
125
 
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
126
104
 
127
105
# Mark this python module as being part of the implementation
128
106
# of unittest: this gives us better tracebacks where the last
140
118
SUBUNIT_SEEK_SET = 0
141
119
SUBUNIT_SEEK_CUR = 1
142
120
 
143
 
 
144
 
class ExtendedTestResult(unittest._TextTestResult):
 
121
# These are intentionally brought into this namespace. That way plugins, etc
 
122
# can just "from bzrlib.tests import TestCase, TestLoader, etc"
 
123
TestSuite = TestUtil.TestSuite
 
124
TestLoader = TestUtil.TestLoader
 
125
 
 
126
# Tests should run in a clean and clearly defined environment. The goal is to
 
127
# keep them isolated from the running environment as mush as possible. The test
 
128
# framework ensures the variables defined below are set (or deleted if the
 
129
# value is None) before a test is run and reset to their original value after
 
130
# the test is run. Generally if some code depends on an environment variable,
 
131
# the tests should start without this variable in the environment. There are a
 
132
# few exceptions but you shouldn't violate this rule lightly.
 
133
isolated_environ = {
 
134
    'BZR_HOME': None,
 
135
    'HOME': None,
 
136
    # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
 
137
    # tests do check our impls match APPDATA
 
138
    'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
139
    'VISUAL': None,
 
140
    'EDITOR': None,
 
141
    'BZR_EMAIL': None,
 
142
    'BZREMAIL': None, # may still be present in the environment
 
143
    'EMAIL': 'jrandom@example.com', # set EMAIL as bzr does not guess
 
144
    'BZR_PROGRESS_BAR': None,
 
145
    'BZR_LOG': None,
 
146
    'BZR_PLUGIN_PATH': None,
 
147
    'BZR_DISABLE_PLUGINS': None,
 
148
    'BZR_PLUGINS_AT': None,
 
149
    'BZR_CONCURRENCY': None,
 
150
    # Make sure that any text ui tests are consistent regardless of
 
151
    # the environment the test case is run in; you may want tests that
 
152
    # test other combinations.  'dumb' is a reasonable guess for tests
 
153
    # going to a pipe or a StringIO.
 
154
    'TERM': 'dumb',
 
155
    'LINES': '25',
 
156
    'COLUMNS': '80',
 
157
    'BZR_COLUMNS': '80',
 
158
    # Disable SSH Agent
 
159
    'SSH_AUTH_SOCK': None,
 
160
    # Proxies
 
161
    'http_proxy': None,
 
162
    'HTTP_PROXY': None,
 
163
    'https_proxy': None,
 
164
    'HTTPS_PROXY': None,
 
165
    'no_proxy': None,
 
166
    'NO_PROXY': None,
 
167
    'all_proxy': None,
 
168
    'ALL_PROXY': None,
 
169
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
170
    # least. If you do (care), please update this comment
 
171
    # -- vila 20080401
 
172
    'ftp_proxy': None,
 
173
    'FTP_PROXY': None,
 
174
    'BZR_REMOTE_PATH': None,
 
175
    # Generally speaking, we don't want apport reporting on crashes in
 
176
    # the test envirnoment unless we're specifically testing apport,
 
177
    # so that it doesn't leak into the real system environment.  We
 
178
    # use an env var so it propagates to subprocesses.
 
179
    'APPORT_DISABLE': '1',
 
180
    }
 
181
 
 
182
 
 
183
def override_os_environ(test, env=None):
 
184
    """Modify os.environ keeping a copy.
 
185
    
 
186
    :param test: A test instance
 
187
 
 
188
    :param env: A dict containing variable definitions to be installed
 
189
    """
 
190
    if env is None:
 
191
        env = isolated_environ
 
192
    test._original_os_environ = dict([(var, value)
 
193
                                      for var, value in os.environ.iteritems()])
 
194
    for var, value in env.iteritems():
 
195
        osutils.set_or_unset_env(var, value)
 
196
        if var not in test._original_os_environ:
 
197
            # The var is new, add it with a value of None, so
 
198
            # restore_os_environ will delete it
 
199
            test._original_os_environ[var] = None
 
200
 
 
201
 
 
202
def restore_os_environ(test):
 
203
    """Restore os.environ to its original state.
 
204
 
 
205
    :param test: A test instance previously passed to override_os_environ.
 
206
    """
 
207
    for var, value in test._original_os_environ.iteritems():
 
208
        # Restore the original value (or delete it if the value has been set to
 
209
        # None in override_os_environ).
 
210
        osutils.set_or_unset_env(var, value)
 
211
 
 
212
 
 
213
class ExtendedTestResult(testtools.TextTestResult):
145
214
    """Accepts, reports and accumulates the results of running tests.
146
215
 
147
216
    Compared to the unittest version this class adds support for
168
237
        :param bench_history: Optionally, a writable file object to accumulate
169
238
            benchmark results.
170
239
        """
171
 
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
240
        testtools.TextTestResult.__init__(self, stream)
172
241
        if bench_history is not None:
173
242
            from bzrlib.version import _get_bzr_source_tree
174
243
            src_tree = _get_bzr_source_tree()
195
264
        self.count = 0
196
265
        self._overall_start_time = time.time()
197
266
        self._strict = strict
 
267
        self._first_thread_leaker_id = None
 
268
        self._tests_leaking_threads_count = 0
 
269
        self._traceback_from_test = None
198
270
 
199
271
    def stopTestRun(self):
200
272
        run = self.testsRun
201
273
        actionTaken = "Ran"
202
274
        stopTime = time.time()
203
275
        timeTaken = stopTime - self.startTime
204
 
        self.printErrors()
205
 
        self.stream.writeln(self.separator2)
206
 
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
276
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
 
277
        #                the parent class method is similar have to duplicate
 
278
        self._show_list('ERROR', self.errors)
 
279
        self._show_list('FAIL', self.failures)
 
280
        self.stream.write(self.sep2)
 
281
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
207
282
                            run, run != 1 and "s" or "", timeTaken))
208
 
        self.stream.writeln()
209
283
        if not self.wasSuccessful():
210
284
            self.stream.write("FAILED (")
211
285
            failed, errored = map(len, (self.failures, self.errors))
218
292
                if failed or errored: self.stream.write(", ")
219
293
                self.stream.write("known_failure_count=%d" %
220
294
                    self.known_failure_count)
221
 
            self.stream.writeln(")")
 
295
            self.stream.write(")\n")
222
296
        else:
223
297
            if self.known_failure_count:
224
 
                self.stream.writeln("OK (known_failures=%d)" %
 
298
                self.stream.write("OK (known_failures=%d)\n" %
225
299
                    self.known_failure_count)
226
300
            else:
227
 
                self.stream.writeln("OK")
 
301
                self.stream.write("OK\n")
228
302
        if self.skip_count > 0:
229
303
            skipped = self.skip_count
230
 
            self.stream.writeln('%d test%s skipped' %
 
304
            self.stream.write('%d test%s skipped\n' %
231
305
                                (skipped, skipped != 1 and "s" or ""))
232
306
        if self.unsupported:
233
307
            for feature, count in sorted(self.unsupported.items()):
234
 
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
308
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
235
309
                    (feature, count))
236
310
        if self._strict:
237
311
            ok = self.wasStrictlySuccessful()
238
312
        else:
239
313
            ok = self.wasSuccessful()
240
 
        if TestCase._first_thread_leaker_id:
 
314
        if self._first_thread_leaker_id:
241
315
            self.stream.write(
242
316
                '%s is leaking threads among %d leaking tests.\n' % (
243
 
                TestCase._first_thread_leaker_id,
244
 
                TestCase._leaking_threads_tests))
 
317
                self._first_thread_leaker_id,
 
318
                self._tests_leaking_threads_count))
245
319
            # We don't report the main thread as an active one.
246
320
            self.stream.write(
247
321
                '%d non-main threads were left active in the end.\n'
248
 
                % (TestCase._active_threads - 1))
 
322
                % (len(self._active_threads) - 1))
249
323
 
250
324
    def getDescription(self, test):
251
325
        return test.id()
258
332
 
259
333
    def _elapsedTestTimeString(self):
260
334
        """Return a time string for the overall time the current test has taken."""
261
 
        return self._formatTime(time.time() - self._start_time)
 
335
        return self._formatTime(self._delta_to_float(
 
336
            self._now() - self._start_datetime))
262
337
 
263
338
    def _testTimeString(self, testCase):
264
339
        benchmark_time = self._extractBenchmarkTime(testCase)
275
350
 
276
351
    def _shortened_test_description(self, test):
277
352
        what = test.id()
278
 
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
353
        what = re.sub(r'^bzrlib\.tests\.', '', what)
279
354
        return what
280
355
 
 
356
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
357
    #                multiple times in a row, because the handler is added for
 
358
    #                each test but the container list is shared between cases.
 
359
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
360
    def _record_traceback_from_test(self, exc_info):
 
361
        """Store the traceback from passed exc_info tuple till"""
 
362
        self._traceback_from_test = exc_info[2]
 
363
 
281
364
    def startTest(self, test):
282
 
        unittest.TestResult.startTest(self, test)
 
365
        super(ExtendedTestResult, self).startTest(test)
283
366
        if self.count == 0:
284
367
            self.startTests()
 
368
        self.count += 1
285
369
        self.report_test_start(test)
286
370
        test.number = self.count
287
371
        self._recordTestStartTime()
 
372
        # Make testtools cases give us the real traceback on failure
 
373
        addOnException = getattr(test, "addOnException", None)
 
374
        if addOnException is not None:
 
375
            addOnException(self._record_traceback_from_test)
 
376
        # Only check for thread leaks on bzrlib derived test cases
 
377
        if isinstance(test, TestCase):
 
378
            test.addCleanup(self._check_leaked_threads, test)
 
379
 
 
380
    def stopTest(self, test):
 
381
        super(ExtendedTestResult, self).stopTest(test)
 
382
        # Manually break cycles, means touching various private things but hey
 
383
        getDetails = getattr(test, "getDetails", None)
 
384
        if getDetails is not None:
 
385
            getDetails().clear()
 
386
        type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
387
        if type_equality_funcs is not None:
 
388
            type_equality_funcs.clear()
 
389
        self._traceback_from_test = None
288
390
 
289
391
    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')
 
392
        self.report_tests_starting()
 
393
        self._active_threads = threading.enumerate()
 
394
 
 
395
    def _check_leaked_threads(self, test):
 
396
        """See if any threads have leaked since last call
 
397
 
 
398
        A sample of live threads is stored in the _active_threads attribute,
 
399
        when this method runs it compares the current live threads and any not
 
400
        in the previous sample are treated as having leaked.
 
401
        """
 
402
        now_active_threads = set(threading.enumerate())
 
403
        threads_leaked = now_active_threads.difference(self._active_threads)
 
404
        if threads_leaked:
 
405
            self._report_thread_leak(test, threads_leaked, now_active_threads)
 
406
            self._tests_leaking_threads_count += 1
 
407
            if self._first_thread_leaker_id is None:
 
408
                self._first_thread_leaker_id = test.id()
 
409
            self._active_threads = now_active_threads
307
410
 
308
411
    def _recordTestStartTime(self):
309
412
        """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()
 
413
        self._start_datetime = self._now()
318
414
 
319
415
    def addError(self, test, err):
320
416
        """Tell result that test finished with an error.
322
418
        Called from the TestCase run() method when the test
323
419
        fails with an unexpected error.
324
420
        """
325
 
        self._post_mortem()
326
 
        unittest.TestResult.addError(self, test, err)
 
421
        self._post_mortem(self._traceback_from_test)
 
422
        super(ExtendedTestResult, self).addError(test, err)
327
423
        self.error_count += 1
328
424
        self.report_error(test, err)
329
425
        if self.stop_early:
330
426
            self.stop()
331
 
        self._cleanupLogFile(test)
332
427
 
333
428
    def addFailure(self, test, err):
334
429
        """Tell result that test failed.
336
431
        Called from the TestCase run() method when the test
337
432
        fails because e.g. an assert() method failed.
338
433
        """
339
 
        self._post_mortem()
340
 
        unittest.TestResult.addFailure(self, test, err)
 
434
        self._post_mortem(self._traceback_from_test)
 
435
        super(ExtendedTestResult, self).addFailure(test, err)
341
436
        self.failure_count += 1
342
437
        self.report_failure(test, err)
343
438
        if self.stop_early:
344
439
            self.stop()
345
 
        self._cleanupLogFile(test)
346
440
 
347
441
    def addSuccess(self, test, details=None):
348
442
        """Tell result that test completed successfully.
356
450
                    self._formatTime(benchmark_time),
357
451
                    test.id()))
358
452
        self.report_success(test)
359
 
        self._cleanupLogFile(test)
360
 
        unittest.TestResult.addSuccess(self, test)
 
453
        super(ExtendedTestResult, self).addSuccess(test)
361
454
        test._log_contents = ''
362
455
 
363
456
    def addExpectedFailure(self, test, err):
364
457
        self.known_failure_count += 1
365
458
        self.report_known_failure(test, err)
366
459
 
 
460
    def addUnexpectedSuccess(self, test, details=None):
 
461
        """Tell result the test unexpectedly passed, counting as a failure
 
462
 
 
463
        When the minimum version of testtools required becomes 0.9.8 this
 
464
        can be updated to use the new handling there.
 
465
        """
 
466
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
467
        self.failure_count += 1
 
468
        self.report_unexpected_success(test,
 
469
            "".join(details["reason"].iter_text()))
 
470
        if self.stop_early:
 
471
            self.stop()
 
472
 
367
473
    def addNotSupported(self, test, feature):
368
474
        """The test will not be run because of a missing feature.
369
475
        """
386
492
        self.not_applicable_count += 1
387
493
        self.report_not_applicable(test, reason)
388
494
 
389
 
    def _post_mortem(self):
 
495
    def _post_mortem(self, tb=None):
390
496
        """Start a PDB post mortem session."""
391
497
        if os.environ.get('BZR_TEST_PDB', None):
392
 
            import pdb;pdb.post_mortem()
 
498
            import pdb
 
499
            pdb.post_mortem(tb)
393
500
 
394
501
    def progress(self, offset, whence):
395
502
        """The test is adjusting the count of tests to run."""
400
507
        else:
401
508
            raise errors.BzrError("Unknown whence %r" % whence)
402
509
 
403
 
    def report_cleaning_up(self):
404
 
        pass
 
510
    def report_tests_starting(self):
 
511
        """Display information before the test run begins"""
 
512
        if getattr(sys, 'frozen', None) is None:
 
513
            bzr_path = osutils.realpath(sys.argv[0])
 
514
        else:
 
515
            bzr_path = sys.executable
 
516
        self.stream.write(
 
517
            'bzr selftest: %s\n' % (bzr_path,))
 
518
        self.stream.write(
 
519
            '   %s\n' % (
 
520
                    bzrlib.__path__[0],))
 
521
        self.stream.write(
 
522
            '   bzr-%s python-%s %s\n' % (
 
523
                    bzrlib.version_string,
 
524
                    bzrlib._format_version_tuple(sys.version_info),
 
525
                    platform.platform(aliased=1),
 
526
                    ))
 
527
        self.stream.write('\n')
 
528
 
 
529
    def report_test_start(self, test):
 
530
        """Display information on the test just about to be run"""
 
531
 
 
532
    def _report_thread_leak(self, test, leaked_threads, active_threads):
 
533
        """Display information on a test that leaked one or more threads"""
 
534
        # GZ 2010-09-09: A leak summary reported separately from the general
 
535
        #                thread debugging would be nice. Tests under subunit
 
536
        #                need something not using stream, perhaps adding a
 
537
        #                testtools details object would be fitting.
 
538
        if 'threads' in selftest_debug_flags:
 
539
            self.stream.write('%s is leaking, active is now %d\n' %
 
540
                (test.id(), len(active_threads)))
405
541
 
406
542
    def startTestRun(self):
407
543
        self.startTime = time.time()
444
580
        self.pb.finished()
445
581
        super(TextTestResult, self).stopTestRun()
446
582
 
447
 
    def startTestRun(self):
448
 
        super(TextTestResult, self).startTestRun()
 
583
    def report_tests_starting(self):
 
584
        super(TextTestResult, self).report_tests_starting()
449
585
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
450
586
 
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
587
    def _progress_prefix_text(self):
457
588
        # the longer this text, the less space we have to show the test
458
589
        # name...
480
611
        return a
481
612
 
482
613
    def report_test_start(self, test):
483
 
        self.count += 1
484
614
        self.pb.update(
485
615
                self._progress_prefix_text()
486
616
                + ' '
504
634
    def report_known_failure(self, test, err):
505
635
        pass
506
636
 
 
637
    def report_unexpected_success(self, test, reason):
 
638
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
 
639
            self._test_description(test),
 
640
            "Unexpected success. Should have failed",
 
641
            reason,
 
642
            ))
 
643
 
507
644
    def report_skip(self, test, reason):
508
645
        pass
509
646
 
513
650
    def report_unsupported(self, test, feature):
514
651
        """test cannot be run because feature is missing."""
515
652
 
516
 
    def report_cleaning_up(self):
517
 
        self.pb.update('Cleaning up')
518
 
 
519
653
 
520
654
class VerboseTestResult(ExtendedTestResult):
521
655
    """Produce long output, with one line per test run plus times"""
528
662
            result = a_string
529
663
        return result.ljust(final_width)
530
664
 
531
 
    def startTestRun(self):
532
 
        super(VerboseTestResult, self).startTestRun()
 
665
    def report_tests_starting(self):
533
666
        self.stream.write('running %d tests...\n' % self.num_tests)
 
667
        super(VerboseTestResult, self).report_tests_starting()
534
668
 
535
669
    def report_test_start(self, test):
536
 
        self.count += 1
537
670
        name = self._shortened_test_description(test)
538
671
        width = osutils.terminal_width()
539
672
        if width is not None:
551
684
        return '%s%s' % (indent, err[1])
552
685
 
553
686
    def report_error(self, test, err):
554
 
        self.stream.writeln('ERROR %s\n%s'
 
687
        self.stream.write('ERROR %s\n%s\n'
555
688
                % (self._testTimeString(test),
556
689
                   self._error_summary(err)))
557
690
 
558
691
    def report_failure(self, test, err):
559
 
        self.stream.writeln(' FAIL %s\n%s'
 
692
        self.stream.write(' FAIL %s\n%s\n'
560
693
                % (self._testTimeString(test),
561
694
                   self._error_summary(err)))
562
695
 
563
696
    def report_known_failure(self, test, err):
564
 
        self.stream.writeln('XFAIL %s\n%s'
 
697
        self.stream.write('XFAIL %s\n%s\n'
565
698
                % (self._testTimeString(test),
566
699
                   self._error_summary(err)))
567
700
 
 
701
    def report_unexpected_success(self, test, reason):
 
702
        self.stream.write(' FAIL %s\n%s: %s\n'
 
703
                % (self._testTimeString(test),
 
704
                   "Unexpected success. Should have failed",
 
705
                   reason))
 
706
 
568
707
    def report_success(self, test):
569
 
        self.stream.writeln('   OK %s' % self._testTimeString(test))
 
708
        self.stream.write('   OK %s\n' % self._testTimeString(test))
570
709
        for bench_called, stats in getattr(test, '_benchcalls', []):
571
 
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
710
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
572
711
            stats.pprint(file=self.stream)
573
712
        # flush the stream so that we get smooth output. This verbose mode is
574
713
        # used to show the output in PQM.
575
714
        self.stream.flush()
576
715
 
577
716
    def report_skip(self, test, reason):
578
 
        self.stream.writeln(' SKIP %s\n%s'
 
717
        self.stream.write(' SKIP %s\n%s\n'
579
718
                % (self._testTimeString(test), reason))
580
719
 
581
720
    def report_not_applicable(self, test, reason):
582
 
        self.stream.writeln('  N/A %s\n    %s'
 
721
        self.stream.write('  N/A %s\n    %s\n'
583
722
                % (self._testTimeString(test), reason))
584
723
 
585
724
    def report_unsupported(self, test, feature):
586
725
        """test cannot be run because feature is missing."""
587
 
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
 
726
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
588
727
                %(self._testTimeString(test), feature))
589
728
 
590
729
 
617
756
            encode = codec[0]
618
757
        else:
619
758
            encode = codec.encode
620
 
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream)
 
759
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
760
        #                so should swap to the plain codecs.StreamWriter
 
761
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
762
            "backslashreplace")
621
763
        stream.encoding = new_encoding
622
 
        self.stream = unittest._WritelnDecorator(stream)
 
764
        self.stream = stream
623
765
        self.descriptions = descriptions
624
766
        self.verbosity = verbosity
625
767
        self._bench_history = bench_history
749
891
    # XXX: Should probably unify more with CannedInputUIFactory or a
750
892
    # particular configuration of TextUIFactory, or otherwise have a clearer
751
893
    # idea of how they're supposed to be different.
752
 
    # See https://bugs.edge.launchpad.net/bzr/+bug/408213
 
894
    # See https://bugs.launchpad.net/bzr/+bug/408213
753
895
 
754
896
    def __init__(self, stdout=None, stderr=None, stdin=None):
755
897
        if stdin is not None:
773
915
        return NullProgressView()
774
916
 
775
917
 
 
918
def isolated_doctest_setUp(test):
 
919
    override_os_environ(test)
 
920
 
 
921
 
 
922
def isolated_doctest_tearDown(test):
 
923
    restore_os_environ(test)
 
924
 
 
925
 
 
926
def IsolatedDocTestSuite(*args, **kwargs):
 
927
    """Overrides doctest.DocTestSuite to handle isolation.
 
928
 
 
929
    The method is really a factory and users are expected to use it as such.
 
930
    """
 
931
    
 
932
    kwargs['setUp'] = isolated_doctest_setUp
 
933
    kwargs['tearDown'] = isolated_doctest_tearDown
 
934
    return doctest.DocTestSuite(*args, **kwargs)
 
935
 
 
936
 
776
937
class TestCase(testtools.TestCase):
777
938
    """Base class for bzr unit tests.
778
939
 
789
950
    routine, and to build and check bzr trees.
790
951
 
791
952
    In addition to the usual method of overriding tearDown(), this class also
792
 
    allows subclasses to register functions into the _cleanups list, which is
 
953
    allows subclasses to register cleanup functions via addCleanup, which are
793
954
    run in order as the object is torn down.  It's less likely this will be
794
955
    accidentally overlooked.
795
956
    """
796
957
 
797
 
    _active_threads = None
798
 
    _leaking_threads_tests = 0
799
 
    _first_thread_leaker_id = None
800
 
    _log_file_name = None
 
958
    _log_file = None
801
959
    # record lsprof data when performing benchmark calls.
802
960
    _gather_lsprof_in_benchmarks = False
803
961
 
804
962
    def __init__(self, methodName='testMethod'):
805
963
        super(TestCase, self).__init__(methodName)
806
 
        self._cleanups = []
807
964
        self._directory_isolation = True
808
965
        self.exception_handlers.insert(0,
809
966
            (UnavailableFeature, self._do_unsupported_or_skip))
814
971
        super(TestCase, self).setUp()
815
972
        for feature in getattr(self, '_test_needs_features', []):
816
973
            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
974
        self._cleanEnvironment()
822
975
        self._silenceUI()
823
976
        self._startLogFile()
827
980
        self._track_transports()
828
981
        self._track_locks()
829
982
        self._clear_debug_flags()
830
 
        TestCase._active_threads = threading.activeCount()
831
 
        self.addCleanup(self._check_leaked_threads)
 
983
        # Isolate global verbosity level, to make sure it's reproducible
 
984
        # between tests.  We should get rid of this altogether: bug 656694. --
 
985
        # mbp 20101008
 
986
        self.overrideAttr(bzrlib.trace, '_verbosity_level', 0)
 
987
        # Isolate config option expansion until its default value for bzrlib is
 
988
        # settled on or a the FIXME associated with _get_expand_default_value
 
989
        # is addressed -- vila 20110219
 
990
        self.overrideAttr(config, '_expand_default_value', None)
 
991
        self._log_files = set()
832
992
 
833
993
    def debug(self):
834
994
        # debug a frame up.
835
995
        import pdb
836
996
        pdb.Pdb().set_trace(sys._getframe().f_back)
837
997
 
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()
 
998
    def discardDetail(self, name):
 
999
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1000
 
 
1001
        eg. bzr always adds the 'log' detail at startup, but we don't want to
 
1002
        include it for skipped, xfail, etc tests.
 
1003
 
 
1004
        It is safe to call this for a detail that doesn't exist, in case this
 
1005
        gets called multiple times.
 
1006
        """
 
1007
        # We cheat. details is stored in __details which means we shouldn't
 
1008
        # touch it. but getDetails() returns the dict directly, so we can
 
1009
        # mutate it.
 
1010
        details = self.getDetails()
 
1011
        if name in details:
 
1012
            del details[name]
852
1013
 
853
1014
    def _clear_debug_flags(self):
854
1015
        """Prevent externally set debug flags affecting tests.
865
1026
 
866
1027
    def _clear_hooks(self):
867
1028
        # prevent hooks affecting tests
 
1029
        known_hooks = hooks.known_hooks
868
1030
        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)
 
1031
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1032
            current_hooks = getattr(parent, name)
872
1033
            self._preserved_hooks[parent] = (name, current_hooks)
 
1034
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1035
        hooks._lazy_hooks = {}
873
1036
        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)
 
1037
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1038
            factory = known_hooks.get(key)
876
1039
            setattr(parent, name, factory())
877
1040
        # this hook should always be installed
878
1041
        request._install_hook()
943
1106
 
944
1107
    def permit_dir(self, name):
945
1108
        """Permit a directory to be used by this test. See permit_url."""
946
 
        name_transport = get_transport(name)
 
1109
        name_transport = _mod_transport.get_transport(name)
947
1110
        self.permit_url(name)
948
1111
        self.permit_url(name_transport.base)
949
1112
 
972
1135
            try:
973
1136
                workingtree.WorkingTree.open(path)
974
1137
            except (errors.NotBranchError, errors.NoWorkingTree):
975
 
                return
 
1138
                raise TestSkipped('Needs a working tree of bzr sources')
976
1139
        finally:
977
1140
            self.enable_directory_isolation()
978
1141
 
1028
1191
        self.addCleanup(transport_server.stop_server)
1029
1192
        # Obtain a real transport because if the server supplies a password, it
1030
1193
        # will be hidden from the base on the client side.
1031
 
        t = get_transport(transport_server.get_url())
 
1194
        t = _mod_transport.get_transport(transport_server.get_url())
1032
1195
        # Some transport servers effectively chroot the backing transport;
1033
1196
        # others like SFTPServer don't - users of the transport can walk up the
1034
1197
        # transport to read the entire backing transport. This wouldn't matter
1090
1253
        except UnicodeError, e:
1091
1254
            # If we can't compare without getting a UnicodeError, then
1092
1255
            # obviously they are different
1093
 
            mutter('UnicodeError: %s', e)
 
1256
            trace.mutter('UnicodeError: %s', e)
1094
1257
        if message:
1095
1258
            message += '\n'
1096
1259
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1097
1260
            % (message,
1098
 
               pformat(a), pformat(b)))
 
1261
               pprint.pformat(a), pprint.pformat(b)))
1099
1262
 
1100
1263
    assertEquals = assertEqual
1101
1264
 
1135
1298
                         'st_mtime did not match')
1136
1299
        self.assertEqual(expected.st_ctime, actual.st_ctime,
1137
1300
                         'st_ctime did not match')
1138
 
        if sys.platform != 'win32':
 
1301
        if sys.platform == 'win32':
1139
1302
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1140
1303
            # 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
 
1304
            # odd. We just force it to always be 0 to avoid any problems.
 
1305
            self.assertEqual(0, expected.st_dev)
 
1306
            self.assertEqual(0, actual.st_dev)
 
1307
            self.assertEqual(0, expected.st_ino)
 
1308
            self.assertEqual(0, actual.st_ino)
 
1309
        else:
1143
1310
            self.assertEqual(expected.st_dev, actual.st_dev,
1144
1311
                             'st_dev did not match')
1145
1312
            self.assertEqual(expected.st_ino, actual.st_ino,
1154
1321
                length, len(obj_with_len), obj_with_len))
1155
1322
 
1156
1323
    def assertLogsError(self, exception_class, func, *args, **kwargs):
1157
 
        """Assert that func(*args, **kwargs) quietly logs a specific exception.
 
1324
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
1158
1325
        """
1159
 
        from bzrlib import trace
1160
1326
        captured = []
1161
1327
        orig_log_exception_quietly = trace.log_exception_quietly
1162
1328
        try:
1163
1329
            def capture():
1164
1330
                orig_log_exception_quietly()
1165
 
                captured.append(sys.exc_info())
 
1331
                captured.append(sys.exc_info()[1])
1166
1332
            trace.log_exception_quietly = capture
1167
1333
            func(*args, **kwargs)
1168
1334
        finally:
1169
1335
            trace.log_exception_quietly = orig_log_exception_quietly
1170
1336
        self.assertLength(1, captured)
1171
 
        err = captured[0][1]
 
1337
        err = captured[0]
1172
1338
        self.assertIsInstance(err, exception_class)
1173
1339
        return err
1174
1340
 
1211
1377
        if haystack.find(needle) == -1:
1212
1378
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
1213
1379
 
 
1380
    def assertNotContainsString(self, haystack, needle):
 
1381
        if haystack.find(needle) != -1:
 
1382
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1383
 
1214
1384
    def assertSubset(self, sublist, superlist):
1215
1385
        """Assert that every entry in sublist is present in superlist."""
1216
1386
        missing = set(sublist) - set(superlist)
1305
1475
 
1306
1476
    def assertFileEqual(self, content, path):
1307
1477
        """Fail if path does not contain 'content'."""
1308
 
        self.failUnlessExists(path)
 
1478
        self.assertPathExists(path)
1309
1479
        f = file(path, 'rb')
1310
1480
        try:
1311
1481
            s = f.read()
1321
1491
        else:
1322
1492
            self.assertEqual(expected_docstring, obj.__doc__)
1323
1493
 
 
1494
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1324
1495
    def failUnlessExists(self, path):
 
1496
        return self.assertPathExists(path)
 
1497
 
 
1498
    def assertPathExists(self, path):
1325
1499
        """Fail unless path or paths, which may be abs or relative, exist."""
1326
1500
        if not isinstance(path, basestring):
1327
1501
            for p in path:
1328
 
                self.failUnlessExists(p)
 
1502
                self.assertPathExists(p)
1329
1503
        else:
1330
 
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1504
            self.assertTrue(osutils.lexists(path),
 
1505
                path + " does not exist")
1331
1506
 
 
1507
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4)))
1332
1508
    def failIfExists(self, path):
 
1509
        return self.assertPathDoesNotExist(path)
 
1510
 
 
1511
    def assertPathDoesNotExist(self, path):
1333
1512
        """Fail if path or paths, which may be abs or relative, exist."""
1334
1513
        if not isinstance(path, basestring):
1335
1514
            for p in path:
1336
 
                self.failIfExists(p)
 
1515
                self.assertPathDoesNotExist(p)
1337
1516
        else:
1338
 
            self.failIf(osutils.lexists(path),path+" exists")
 
1517
            self.assertFalse(osutils.lexists(path),
 
1518
                path + " exists")
1339
1519
 
1340
1520
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1341
1521
        """A helper for callDeprecated and applyDeprecated.
1367
1547
        not other callers that go direct to the warning module.
1368
1548
 
1369
1549
        To test that a deprecated method raises an error, do something like
1370
 
        this::
 
1550
        this (remember that both assertRaises and applyDeprecated delays *args
 
1551
        and **kwargs passing)::
1371
1552
 
1372
1553
            self.assertRaises(errors.ReservedId,
1373
1554
                self.applyDeprecated,
1455
1636
 
1456
1637
        The file is removed as the test is torn down.
1457
1638
        """
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
 
1639
        pseudo_log_file = StringIO()
 
1640
        def _get_log_contents_for_weird_testtools_api():
 
1641
            return [pseudo_log_file.getvalue().decode(
 
1642
                "utf-8", "replace").encode("utf-8")]
 
1643
        self.addDetail("log", content.Content(content.ContentType("text",
 
1644
            "plain", {"charset": "utf8"}),
 
1645
            _get_log_contents_for_weird_testtools_api))
 
1646
        self._log_file = pseudo_log_file
 
1647
        self._log_memento = trace.push_log_file(self._log_file)
1462
1648
        self.addCleanup(self._finishLogFile)
1463
1649
 
1464
1650
    def _finishLogFile(self):
1466
1652
 
1467
1653
        Close the file and delete it, unless setKeepLogfile was called.
1468
1654
        """
1469
 
        if bzrlib.trace._trace_file:
 
1655
        if trace._trace_file:
1470
1656
            # 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)
 
1657
            trace._trace_file.flush()
 
1658
        trace.pop_log_file(self._log_memento)
1475
1659
 
1476
1660
    def thisFailsStrictLockCheck(self):
1477
1661
        """It is known that this test would fail with -Dstrict_locks.
1486
1670
        """
1487
1671
        debug.debug_flags.discard('strict_locks')
1488
1672
 
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
1673
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1498
1674
        """Overrides an object attribute restoring it after the test.
1499
1675
 
1513
1689
            setattr(obj, attr_name, new)
1514
1690
        return value
1515
1691
 
 
1692
    def overrideEnv(self, name, new):
 
1693
        """Set an environment variable, and reset it after the test.
 
1694
 
 
1695
        :param name: The environment variable name.
 
1696
 
 
1697
        :param new: The value to set the variable to. If None, the 
 
1698
            variable is deleted from the environment.
 
1699
 
 
1700
        :returns: The actual variable value.
 
1701
        """
 
1702
        value = osutils.set_or_unset_env(name, new)
 
1703
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1704
        return value
 
1705
 
1516
1706
    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)
 
1707
        for name, value in isolated_environ.iteritems():
 
1708
            self.overrideEnv(name, value)
1577
1709
 
1578
1710
    def _restoreHooks(self):
1579
1711
        for klass, (name, hooks) in self._preserved_hooks.items():
1580
1712
            setattr(klass, name, hooks)
 
1713
        self._preserved_hooks.clear()
 
1714
        bzrlib.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1715
        self._preserved_lazy_hooks.clear()
1581
1716
 
1582
1717
    def knownFailure(self, reason):
1583
1718
        """This test has failed for some known reason."""
1584
1719
        raise KnownFailure(reason)
1585
1720
 
 
1721
    def _suppress_log(self):
 
1722
        """Remove the log info from details."""
 
1723
        self.discardDetail('log')
 
1724
 
1586
1725
    def _do_skip(self, result, reason):
 
1726
        self._suppress_log()
1587
1727
        addSkip = getattr(result, 'addSkip', None)
1588
1728
        if not callable(addSkip):
1589
1729
            result.addSuccess(result)
1592
1732
 
1593
1733
    @staticmethod
1594
1734
    def _do_known_failure(self, result, e):
 
1735
        self._suppress_log()
1595
1736
        err = sys.exc_info()
1596
1737
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1597
1738
        if addExpectedFailure is not None:
1605
1746
            reason = 'No reason given'
1606
1747
        else:
1607
1748
            reason = e.args[0]
 
1749
        self._suppress_log ()
1608
1750
        addNotApplicable = getattr(result, 'addNotApplicable', None)
1609
1751
        if addNotApplicable is not None:
1610
1752
            result.addNotApplicable(self, reason)
1612
1754
            self._do_skip(result, reason)
1613
1755
 
1614
1756
    @staticmethod
 
1757
    def _report_skip(self, result, err):
 
1758
        """Override the default _report_skip.
 
1759
 
 
1760
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1761
        already been formatted into the 'reason' string, and we can't pull it
 
1762
        out again.
 
1763
        """
 
1764
        self._suppress_log()
 
1765
        super(TestCase, self)._report_skip(self, result, err)
 
1766
 
 
1767
    @staticmethod
 
1768
    def _report_expected_failure(self, result, err):
 
1769
        """Strip the log.
 
1770
 
 
1771
        See _report_skip for motivation.
 
1772
        """
 
1773
        self._suppress_log()
 
1774
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1775
 
 
1776
    @staticmethod
1615
1777
    def _do_unsupported_or_skip(self, result, e):
1616
1778
        reason = e.args[0]
 
1779
        self._suppress_log()
1617
1780
        addNotSupported = getattr(result, 'addNotSupported', None)
1618
1781
        if addNotSupported is not None:
1619
1782
            result.addNotSupported(self, reason)
1645
1808
            self._benchtime += time.time() - start
1646
1809
 
1647
1810
    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."
 
1811
        trace.mutter(*args)
1728
1812
 
1729
1813
    def get_log(self):
1730
1814
        """Get a unicode string containing the log from bzrlib.trace.
1780
1864
 
1781
1865
        try:
1782
1866
            try:
1783
 
                result = self.apply_redirected(ui.ui_factory.stdin,
 
1867
                result = self.apply_redirected(
 
1868
                    ui.ui_factory.stdin,
1784
1869
                    stdout, stderr,
1785
 
                    bzrlib.commands.run_bzr_catch_user_errors,
 
1870
                    _mod_commands.run_bzr_catch_user_errors,
1786
1871
                    args)
1787
1872
            except KeyboardInterrupt:
1788
1873
                # Reraise KeyboardInterrupt with contents of redirected stdout
1930
2015
    def start_bzr_subprocess(self, process_args, env_changes=None,
1931
2016
                             skip_if_plan_to_signal=False,
1932
2017
                             working_dir=None,
1933
 
                             allow_plugins=False):
 
2018
                             allow_plugins=False, stderr=subprocess.PIPE):
1934
2019
        """Start bzr in a subprocess for testing.
1935
2020
 
1936
2021
        This starts a new Python interpreter and runs bzr in there.
1945
2030
            variables. A value of None will unset the env variable.
1946
2031
            The values must be strings. The change will only occur in the
1947
2032
            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.
 
2033
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2034
            doesn't support signalling subprocesses.
1950
2035
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
2036
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2037
            are those valid for the stderr argument of `subprocess.Popen`.
 
2038
            Default value is ``subprocess.PIPE``.
1951
2039
 
1952
2040
        :returns: Popen object for the started process.
1953
2041
        """
1954
2042
        if skip_if_plan_to_signal:
1955
 
            if not getattr(os, 'kill', None):
1956
 
                raise TestSkipped("os.kill not available.")
 
2043
            if os.name != "posix":
 
2044
                raise TestSkipped("Sending signals not supported")
1957
2045
 
1958
2046
        if env_changes is None:
1959
2047
            env_changes = {}
1979
2067
            # so we will avoid using it on all platforms, just to
1980
2068
            # make sure the code path is used, and we don't break on win32
1981
2069
            cleanup_environment()
 
2070
            # Include the subprocess's log file in the test details, in case
 
2071
            # the test fails due to an error in the subprocess.
 
2072
            self._add_subprocess_log(trace._get_bzr_log_filename())
1982
2073
            command = [sys.executable]
1983
2074
            # frozen executables don't need the path to bzr
1984
2075
            if getattr(sys, "frozen", None) is None:
1986
2077
            if not allow_plugins:
1987
2078
                command.append('--no-plugins')
1988
2079
            command.extend(process_args)
1989
 
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
2080
            process = self._popen(command, stdin=subprocess.PIPE,
 
2081
                                  stdout=subprocess.PIPE,
 
2082
                                  stderr=stderr)
1990
2083
        finally:
1991
2084
            restore_environment()
1992
2085
            if cwd is not None:
1994
2087
 
1995
2088
        return process
1996
2089
 
 
2090
    def _add_subprocess_log(self, log_file_path):
 
2091
        if len(self._log_files) == 0:
 
2092
            # Register an addCleanup func.  We do this on the first call to
 
2093
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2094
            # addCleanup is registered after any cleanups for tempdirs that
 
2095
            # subclasses might create, which will probably remove the log file
 
2096
            # we want to read.
 
2097
            self.addCleanup(self._subprocess_log_cleanup)
 
2098
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2099
        # twice.
 
2100
        self._log_files.add(log_file_path)
 
2101
 
 
2102
    def _subprocess_log_cleanup(self):
 
2103
        for count, log_file_path in enumerate(self._log_files):
 
2104
            # We use buffer_now=True to avoid holding the file open beyond
 
2105
            # the life of this function, which might interfere with e.g.
 
2106
            # cleaning tempdirs on Windows.
 
2107
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2108
            #detail_content = content.content_from_file(
 
2109
            #    log_file_path, buffer_now=True)
 
2110
            with open(log_file_path, 'rb') as log_file:
 
2111
                log_file_bytes = log_file.read()
 
2112
            detail_content = content.Content(content.ContentType("text",
 
2113
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2114
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2115
                detail_content)
 
2116
 
1997
2117
    def _popen(self, *args, **kwargs):
1998
2118
        """Place a call to Popen.
1999
2119
 
2000
2120
        Allows tests to override this method to intercept the calls made to
2001
2121
        Popen for introspection.
2002
2122
        """
2003
 
        return Popen(*args, **kwargs)
 
2123
        return subprocess.Popen(*args, **kwargs)
2004
2124
 
2005
2125
    def get_source_path(self):
2006
2126
        """Return the path of the directory containing bzrlib."""
2008
2128
 
2009
2129
    def get_bzr_path(self):
2010
2130
        """Return the path of the 'bzr' executable for this test suite."""
2011
 
        bzr_path = self.get_source_path()+'/bzr'
 
2131
        bzr_path = os.path.join(self.get_source_path(), "bzr")
2012
2132
        if not os.path.isfile(bzr_path):
2013
2133
            # We are probably installed. Assume sys.argv is the right file
2014
2134
            bzr_path = sys.argv[0]
2036
2156
        if retcode is not None and retcode != process.returncode:
2037
2157
            if process_args is None:
2038
2158
                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)
 
2159
            trace.mutter('Output of bzr %s:\n%s', process_args, out)
 
2160
            trace.mutter('Error for bzr %s:\n%s', process_args, err)
2041
2161
            self.fail('Command bzr %s failed with retcode %s != %s'
2042
2162
                      % (process_args, retcode, process.returncode))
2043
2163
        return [out, err]
2044
2164
 
2045
 
    def check_inventory_shape(self, inv, shape):
2046
 
        """Compare an inventory to a list of expected names.
 
2165
    def check_tree_shape(self, tree, shape):
 
2166
        """Compare a tree to a list of expected names.
2047
2167
 
2048
2168
        Fail if they are not precisely equal.
2049
2169
        """
2050
2170
        extras = []
2051
2171
        shape = list(shape)             # copy
2052
 
        for path, ie in inv.entries():
 
2172
        for path, ie in tree.iter_entries_by_dir():
2053
2173
            name = path.replace('\\', '/')
2054
2174
            if ie.kind == 'directory':
2055
2175
                name = name + '/'
2056
 
            if name in shape:
 
2176
            if name == "/":
 
2177
                pass # ignore root entry
 
2178
            elif name in shape:
2057
2179
                shape.remove(name)
2058
2180
            else:
2059
2181
                extras.append(name)
2100
2222
 
2101
2223
        Tests that expect to provoke LockContention errors should call this.
2102
2224
        """
2103
 
        self.overrideAttr(bzrlib.lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2225
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2104
2226
 
2105
2227
    def make_utf8_encoded_stringio(self, encoding_type=None):
2106
2228
        """Return a StringIOWrapper instance, that will encode Unicode
2186
2308
 
2187
2309
        :param relpath: a path relative to the base url.
2188
2310
        """
2189
 
        t = get_transport(self.get_url(relpath))
 
2311
        t = _mod_transport.get_transport(self.get_url(relpath))
2190
2312
        self.assertFalse(t.is_readonly())
2191
2313
        return t
2192
2314
 
2198
2320
 
2199
2321
        :param relpath: a path relative to the base url.
2200
2322
        """
2201
 
        t = get_transport(self.get_readonly_url(relpath))
 
2323
        t = _mod_transport.get_transport(self.get_readonly_url(relpath))
2202
2324
        self.assertTrue(t.is_readonly())
2203
2325
        return t
2204
2326
 
2334
2456
        propagating. This method ensures than a test did not leaked.
2335
2457
        """
2336
2458
        root = TestCaseWithMemoryTransport.TEST_ROOT
2337
 
        self.permit_url(get_transport(root).base)
 
2459
        self.permit_url(_mod_transport.get_transport(root).base)
2338
2460
        wt = workingtree.WorkingTree.open(root)
2339
2461
        last_rev = wt.last_revision()
2340
2462
        if last_rev != 'null:':
2385
2507
            # might be a relative or absolute path
2386
2508
            maybe_a_url = self.get_url(relpath)
2387
2509
            segments = maybe_a_url.rsplit('/', 1)
2388
 
            t = get_transport(maybe_a_url)
 
2510
            t = _mod_transport.get_transport(maybe_a_url)
2389
2511
            if len(segments) > 1 and segments[-1] not in ('', '.'):
2390
2512
                t.ensure_base()
2391
2513
            if format is None:
2408
2530
        made_control = self.make_bzrdir(relpath, format=format)
2409
2531
        return made_control.create_repository(shared=shared)
2410
2532
 
2411
 
    def make_smart_server(self, path):
 
2533
    def make_smart_server(self, path, backing_server=None):
 
2534
        if backing_server is None:
 
2535
            backing_server = self.get_server()
2412
2536
        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)
 
2537
        self.start_server(smart_server, backing_server)
 
2538
        remote_transport = _mod_transport.get_transport(smart_server.get_url()
 
2539
                                                   ).clone(path)
2415
2540
        return remote_transport
2416
2541
 
2417
2542
    def make_branch_and_memory_tree(self, relpath, format=None):
2427
2552
        test_home_dir = self.test_home_dir
2428
2553
        if isinstance(test_home_dir, unicode):
2429
2554
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2430
 
        os.environ['HOME'] = test_home_dir
2431
 
        os.environ['BZR_HOME'] = test_home_dir
 
2555
        self.overrideEnv('HOME', test_home_dir)
 
2556
        self.overrideEnv('BZR_HOME', test_home_dir)
2432
2557
 
2433
2558
    def setUp(self):
2434
2559
        super(TestCaseWithMemoryTransport, self).setUp()
 
2560
        # Ensure that ConnectedTransport doesn't leak sockets
 
2561
        def get_transport_with_cleanup(*args, **kwargs):
 
2562
            t = orig_get_transport(*args, **kwargs)
 
2563
            if isinstance(t, _mod_transport.ConnectedTransport):
 
2564
                self.addCleanup(t.disconnect)
 
2565
            return t
 
2566
 
 
2567
        orig_get_transport = self.overrideAttr(_mod_transport, 'get_transport',
 
2568
                                               get_transport_with_cleanup)
2435
2569
        self._make_test_root()
2436
2570
        self.addCleanup(os.chdir, os.getcwdu())
2437
2571
        self.makeAndChdirToTestDir()
2482
2616
 
2483
2617
    def check_file_contents(self, filename, expect):
2484
2618
        self.log("check contents of file %s" % filename)
2485
 
        contents = file(filename, 'r').read()
 
2619
        f = file(filename)
 
2620
        try:
 
2621
            contents = f.read()
 
2622
        finally:
 
2623
            f.close()
2486
2624
        if contents != expect:
2487
2625
            self.log("expected: %r" % expect)
2488
2626
            self.log("actually: %r" % contents)
2562
2700
                "a list or a tuple. Got %r instead" % (shape,))
2563
2701
        # It's OK to just create them using forward slashes on windows.
2564
2702
        if transport is None or transport.is_readonly():
2565
 
            transport = get_transport(".")
 
2703
            transport = _mod_transport.get_transport(".")
2566
2704
        for name in shape:
2567
2705
            self.assertIsInstance(name, basestring)
2568
2706
            if name[-1] == '/':
2578
2716
                content = "contents of %s%s" % (name.encode('utf-8'), end)
2579
2717
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
2580
2718
 
2581
 
    def build_tree_contents(self, shape):
2582
 
        build_tree_contents(shape)
 
2719
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
2583
2720
 
2584
2721
    def assertInWorkingTree(self, path, root_path='.', tree=None):
2585
2722
        """Assert whether path or paths are in the WorkingTree"""
2726
2863
    """
2727
2864
 
2728
2865
    def setUp(self):
 
2866
        from bzrlib.tests import http_server
2729
2867
        super(ChrootedTestCase, self).setUp()
2730
2868
        if not self.vfs_transport_factory == memory.MemoryServer:
2731
 
            self.transport_readonly_server = HttpServer
 
2869
            self.transport_readonly_server = http_server.HttpServer
2732
2870
 
2733
2871
 
2734
2872
def condition_id_re(pattern):
2737
2875
    :param pattern: A regular expression string.
2738
2876
    :return: A callable that returns True if the re matches.
2739
2877
    """
2740
 
    filter_re = osutils.re_compile_checked(pattern, 0,
2741
 
        'test filter')
 
2878
    filter_re = re.compile(pattern, 0)
2742
2879
    def condition(test):
2743
2880
        test_id = test.id()
2744
2881
        return filter_re.search(test_id)
2996
3133
 
2997
3134
 
2998
3135
def fork_decorator(suite):
 
3136
    if getattr(os, "fork", None) is None:
 
3137
        raise errors.BzrCommandError("platform does not support fork,"
 
3138
            " try --parallel=subprocess instead.")
2999
3139
    concurrency = osutils.local_concurrency()
3000
3140
    if concurrency == 1:
3001
3141
        return suite
3056
3196
    return suite
3057
3197
 
3058
3198
 
3059
 
class TestDecorator(TestSuite):
 
3199
class TestDecorator(TestUtil.TestSuite):
3060
3200
    """A decorator for TestCase/TestSuite objects.
3061
3201
    
3062
3202
    Usually, subclasses should override __iter__(used when flattening test
3065
3205
    """
3066
3206
 
3067
3207
    def __init__(self, suite):
3068
 
        TestSuite.__init__(self)
 
3208
        TestUtil.TestSuite.__init__(self)
3069
3209
        self.addTest(suite)
3070
3210
 
3071
3211
    def countTestCases(self):
3190
3330
 
3191
3331
def partition_tests(suite, count):
3192
3332
    """Partition suite into count lists of tests."""
3193
 
    result = []
3194
 
    tests = list(iter_suite_tests(suite))
3195
 
    tests_per_process = int(math.ceil(float(len(tests)) / count))
3196
 
    for block in range(count):
3197
 
        low_test = block * tests_per_process
3198
 
        high_test = low_test + tests_per_process
3199
 
        process_tests = tests[low_test:high_test]
3200
 
        result.append(process_tests)
3201
 
    return result
 
3333
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3334
    # splits up blocks of related tests that might run faster if they shared
 
3335
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3336
    # just one partition.  So the slowest partition shouldn't be much slower
 
3337
    # than the fastest.
 
3338
    partitions = [list() for i in range(count)]
 
3339
    tests = iter_suite_tests(suite)
 
3340
    for partition, test in itertools.izip(itertools.cycle(partitions), tests):
 
3341
        partition.append(test)
 
3342
    return partitions
3202
3343
 
3203
3344
 
3204
3345
def workaround_zealous_crypto_random():
3238
3379
 
3239
3380
    test_blocks = partition_tests(suite, concurrency)
3240
3381
    for process_tests in test_blocks:
3241
 
        process_suite = TestSuite()
 
3382
        process_suite = TestUtil.TestSuite()
3242
3383
        process_suite.addTests(process_tests)
3243
3384
        c2pread, c2pwrite = os.pipe()
3244
3385
        pid = os.fork()
3310
3451
                '--subunit']
3311
3452
            if '--no-plugins' in sys.argv:
3312
3453
                argv.append('--no-plugins')
3313
 
            # stderr=STDOUT would be ideal, but until we prevent noise on
3314
 
            # stderr it can interrupt the subunit protocol.
3315
 
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
3316
 
                bufsize=1)
 
3454
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3455
            # noise on stderr it can interrupt the subunit protocol.
 
3456
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3457
                                      stdout=subprocess.PIPE,
 
3458
                                      stderr=subprocess.PIPE,
 
3459
                                      bufsize=1)
3317
3460
            test = TestInSubprocess(process, test_list_file_name)
3318
3461
            result.append(test)
3319
3462
        except:
3322
3465
    return result
3323
3466
 
3324
3467
 
3325
 
class ForwardingResult(unittest.TestResult):
3326
 
 
3327
 
    def __init__(self, target):
3328
 
        unittest.TestResult.__init__(self)
3329
 
        self.result = target
3330
 
 
3331
 
    def startTest(self, test):
3332
 
        self.result.startTest(test)
3333
 
 
3334
 
    def stopTest(self, test):
3335
 
        self.result.stopTest(test)
3336
 
 
3337
 
    def startTestRun(self):
3338
 
        self.result.startTestRun()
3339
 
 
3340
 
    def stopTestRun(self):
3341
 
        self.result.stopTestRun()
3342
 
 
3343
 
    def addSkip(self, test, reason):
3344
 
        self.result.addSkip(test, reason)
3345
 
 
3346
 
    def addSuccess(self, test):
3347
 
        self.result.addSuccess(test)
3348
 
 
3349
 
    def addError(self, test, err):
3350
 
        self.result.addError(test, err)
3351
 
 
3352
 
    def addFailure(self, test, err):
3353
 
        self.result.addFailure(test, err)
3354
 
ForwardingResult = testtools.ExtendedToOriginalDecorator
3355
 
 
3356
 
 
3357
 
class ProfileResult(ForwardingResult):
 
3468
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3358
3469
    """Generate profiling data for all activity between start and success.
3359
3470
    
3360
3471
    The profile data is appended to the test's _benchcalls attribute and can
3368
3479
 
3369
3480
    def startTest(self, test):
3370
3481
        self.profiler = bzrlib.lsprof.BzrProfiler()
 
3482
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3483
        # unavoidably fail.
 
3484
        bzrlib.lsprof.BzrProfiler.profiler_block = 0
3371
3485
        self.profiler.start()
3372
 
        ForwardingResult.startTest(self, test)
 
3486
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
3373
3487
 
3374
3488
    def addSuccess(self, test):
3375
3489
        stats = self.profiler.stop()
3379
3493
            test._benchcalls = []
3380
3494
            calls = test._benchcalls
3381
3495
        calls.append(((test.id(), "", ""), stats))
3382
 
        ForwardingResult.addSuccess(self, test)
 
3496
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3383
3497
 
3384
3498
    def stopTest(self, test):
3385
 
        ForwardingResult.stopTest(self, test)
 
3499
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3386
3500
        self.profiler = None
3387
3501
 
3388
3502
 
3394
3508
#                           rather than failing tests. And no longer raise
3395
3509
#                           LockContention when fctnl locks are not being used
3396
3510
#                           with proper exclusion rules.
 
3511
#   -Ethreads               Will display thread ident at creation/join time to
 
3512
#                           help track thread leaks
3397
3513
selftest_debug_flags = set()
3398
3514
 
3399
3515
 
3593
3709
                key, obj, help=help, info=info, override_existing=False)
3594
3710
        except KeyError:
3595
3711
            actual = self.get(key)
3596
 
            note('Test prefix alias %s is already used for %s, ignoring %s'
3597
 
                 % (key, actual, obj))
 
3712
            trace.note(
 
3713
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3714
                % (key, actual, obj))
3598
3715
 
3599
3716
    def resolve_alias(self, id_start):
3600
3717
        """Replace the alias by the prefix in the given string.
3632
3749
        'bzrlib.doc',
3633
3750
        'bzrlib.tests.blackbox',
3634
3751
        'bzrlib.tests.commands',
 
3752
        'bzrlib.tests.doc_generate',
3635
3753
        'bzrlib.tests.per_branch',
3636
3754
        'bzrlib.tests.per_bzrdir',
3637
 
        'bzrlib.tests.per_bzrdir_colo',
 
3755
        'bzrlib.tests.per_controldir',
 
3756
        'bzrlib.tests.per_controldir_colo',
3638
3757
        'bzrlib.tests.per_foreign_vcs',
3639
3758
        'bzrlib.tests.per_interrepository',
3640
3759
        'bzrlib.tests.per_intertree',
3648
3767
        'bzrlib.tests.per_repository',
3649
3768
        'bzrlib.tests.per_repository_chk',
3650
3769
        'bzrlib.tests.per_repository_reference',
 
3770
        'bzrlib.tests.per_repository_vf',
3651
3771
        'bzrlib.tests.per_uifactory',
3652
3772
        'bzrlib.tests.per_versionedfile',
3653
3773
        'bzrlib.tests.per_workingtree',
3654
3774
        'bzrlib.tests.test__annotator',
3655
3775
        'bzrlib.tests.test__bencode',
 
3776
        'bzrlib.tests.test__btree_serializer',
3656
3777
        'bzrlib.tests.test__chk_map',
3657
3778
        'bzrlib.tests.test__dirstate_helpers',
3658
3779
        'bzrlib.tests.test__groupcompress',
3686
3807
        'bzrlib.tests.test_commit_merge',
3687
3808
        'bzrlib.tests.test_config',
3688
3809
        'bzrlib.tests.test_conflicts',
 
3810
        'bzrlib.tests.test_controldir',
3689
3811
        'bzrlib.tests.test_counted_lock',
3690
3812
        'bzrlib.tests.test_crash',
3691
3813
        'bzrlib.tests.test_decorators',
3692
3814
        'bzrlib.tests.test_delta',
3693
3815
        'bzrlib.tests.test_debug',
3694
 
        'bzrlib.tests.test_deprecated_graph',
3695
3816
        'bzrlib.tests.test_diff',
3696
3817
        'bzrlib.tests.test_directory_service',
3697
3818
        'bzrlib.tests.test_dirstate',
3699
3820
        'bzrlib.tests.test_eol_filters',
3700
3821
        'bzrlib.tests.test_errors',
3701
3822
        'bzrlib.tests.test_export',
 
3823
        'bzrlib.tests.test_export_pot',
3702
3824
        'bzrlib.tests.test_extract',
3703
3825
        'bzrlib.tests.test_fetch',
 
3826
        'bzrlib.tests.test_fixtures',
3704
3827
        'bzrlib.tests.test_fifo_cache',
3705
3828
        'bzrlib.tests.test_filters',
3706
3829
        'bzrlib.tests.test_ftp_transport',
3717
3840
        'bzrlib.tests.test_http',
3718
3841
        'bzrlib.tests.test_http_response',
3719
3842
        'bzrlib.tests.test_https_ca_bundle',
 
3843
        'bzrlib.tests.test_i18n',
3720
3844
        'bzrlib.tests.test_identitymap',
3721
3845
        'bzrlib.tests.test_ignores',
3722
3846
        'bzrlib.tests.test_index',
3727
3851
        'bzrlib.tests.test_knit',
3728
3852
        'bzrlib.tests.test_lazy_import',
3729
3853
        'bzrlib.tests.test_lazy_regex',
 
3854
        'bzrlib.tests.test_library_state',
3730
3855
        'bzrlib.tests.test_lock',
3731
3856
        'bzrlib.tests.test_lockable_files',
3732
3857
        'bzrlib.tests.test_lockdir',
3734
3859
        'bzrlib.tests.test_lru_cache',
3735
3860
        'bzrlib.tests.test_lsprof',
3736
3861
        'bzrlib.tests.test_mail_client',
 
3862
        'bzrlib.tests.test_matchers',
3737
3863
        'bzrlib.tests.test_memorytree',
3738
3864
        'bzrlib.tests.test_merge',
3739
3865
        'bzrlib.tests.test_merge3',
3740
3866
        'bzrlib.tests.test_merge_core',
3741
3867
        'bzrlib.tests.test_merge_directive',
 
3868
        'bzrlib.tests.test_mergetools',
3742
3869
        'bzrlib.tests.test_missing',
3743
3870
        'bzrlib.tests.test_msgeditor',
3744
3871
        'bzrlib.tests.test_multiparent',
3753
3880
        'bzrlib.tests.test_permissions',
3754
3881
        'bzrlib.tests.test_plugins',
3755
3882
        'bzrlib.tests.test_progress',
 
3883
        'bzrlib.tests.test_pyutils',
3756
3884
        'bzrlib.tests.test_read_bundle',
3757
3885
        'bzrlib.tests.test_reconcile',
3758
3886
        'bzrlib.tests.test_reconfigure',
3767
3895
        'bzrlib.tests.test_rio',
3768
3896
        'bzrlib.tests.test_rules',
3769
3897
        'bzrlib.tests.test_sampler',
 
3898
        'bzrlib.tests.test_scenarios',
3770
3899
        'bzrlib.tests.test_script',
3771
3900
        'bzrlib.tests.test_selftest',
3772
3901
        'bzrlib.tests.test_serializer',
3788
3917
        'bzrlib.tests.test_switch',
3789
3918
        'bzrlib.tests.test_symbol_versioning',
3790
3919
        'bzrlib.tests.test_tag',
 
3920
        'bzrlib.tests.test_test_server',
3791
3921
        'bzrlib.tests.test_testament',
3792
3922
        'bzrlib.tests.test_textfile',
3793
3923
        'bzrlib.tests.test_textmerge',
 
3924
        'bzrlib.tests.test_cethread',
3794
3925
        'bzrlib.tests.test_timestamp',
3795
3926
        'bzrlib.tests.test_trace',
3796
3927
        'bzrlib.tests.test_transactions',
3799
3930
        'bzrlib.tests.test_transport_log',
3800
3931
        'bzrlib.tests.test_tree',
3801
3932
        'bzrlib.tests.test_treebuilder',
 
3933
        'bzrlib.tests.test_treeshape',
3802
3934
        'bzrlib.tests.test_tsort',
3803
3935
        'bzrlib.tests.test_tuned_gzip',
3804
3936
        'bzrlib.tests.test_ui',
3806
3938
        'bzrlib.tests.test_upgrade',
3807
3939
        'bzrlib.tests.test_upgrade_stacked',
3808
3940
        'bzrlib.tests.test_urlutils',
 
3941
        'bzrlib.tests.test_utextwrap',
3809
3942
        'bzrlib.tests.test_version',
3810
3943
        'bzrlib.tests.test_version_info',
 
3944
        'bzrlib.tests.test_versionedfile',
3811
3945
        'bzrlib.tests.test_weave',
3812
3946
        'bzrlib.tests.test_whitebox',
3813
3947
        'bzrlib.tests.test_win32utils',
3827
3961
        'bzrlib',
3828
3962
        'bzrlib.branchbuilder',
3829
3963
        'bzrlib.decorators',
3830
 
        'bzrlib.export',
3831
3964
        'bzrlib.inventory',
3832
3965
        'bzrlib.iterablefile',
3833
3966
        'bzrlib.lockdir',
3834
3967
        'bzrlib.merge3',
3835
3968
        'bzrlib.option',
 
3969
        'bzrlib.pyutils',
3836
3970
        'bzrlib.symbol_versioning',
3837
3971
        'bzrlib.tests',
 
3972
        'bzrlib.tests.fixtures',
3838
3973
        'bzrlib.timestamp',
 
3974
        'bzrlib.transport.http',
3839
3975
        'bzrlib.version_info_formats.format_custom',
3840
3976
        ]
3841
3977
 
3894
4030
        try:
3895
4031
            # note that this really does mean "report only" -- doctest
3896
4032
            # still runs the rest of the examples
3897
 
            doc_suite = doctest.DocTestSuite(mod,
3898
 
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4033
            doc_suite = IsolatedDocTestSuite(
 
4034
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
3899
4035
        except ValueError, e:
3900
4036
            print '**failed to get doctest for: %s\n%s' % (mod, e)
3901
4037
            raise
3904
4040
        suite.addTest(doc_suite)
3905
4041
 
3906
4042
    default_encoding = sys.getdefaultencoding()
3907
 
    for name, plugin in bzrlib.plugin.plugins().items():
 
4043
    for name, plugin in _mod_plugin.plugins().items():
3908
4044
        if not interesting_module(plugin.module.__name__):
3909
4045
            continue
3910
4046
        plugin_suite = plugin.test_suite()
3916
4052
        if plugin_suite is not None:
3917
4053
            suite.addTest(plugin_suite)
3918
4054
        if default_encoding != sys.getdefaultencoding():
3919
 
            bzrlib.trace.warning(
 
4055
            trace.warning(
3920
4056
                'Plugin "%s" tried to reset default encoding to: %s', name,
3921
4057
                sys.getdefaultencoding())
3922
4058
            reload(sys)
3937
4073
            # Some tests mentioned in the list are not in the test suite. The
3938
4074
            # list may be out of date, report to the tester.
3939
4075
            for id in not_found:
3940
 
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
4076
                trace.warning('"%s" not found in the test suite', id)
3941
4077
        for id in duplicates:
3942
 
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
4078
            trace.warning('"%s" is used as an id by several tests', id)
3943
4079
 
3944
4080
    return suite
3945
4081
 
3946
4082
 
3947
 
def multiply_scenarios(scenarios_left, scenarios_right):
 
4083
def multiply_scenarios(*scenarios):
 
4084
    """Multiply two or more iterables of scenarios.
 
4085
 
 
4086
    It is safe to pass scenario generators or iterators.
 
4087
 
 
4088
    :returns: A list of compound scenarios: the cross-product of all 
 
4089
        scenarios, with the names concatenated and the parameters
 
4090
        merged together.
 
4091
    """
 
4092
    return reduce(_multiply_two_scenarios, map(list, scenarios))
 
4093
 
 
4094
 
 
4095
def _multiply_two_scenarios(scenarios_left, scenarios_right):
3948
4096
    """Multiply two sets of scenarios.
3949
4097
 
3950
4098
    :returns: the cartesian product of the two sets of scenarios, that is
3981
4129
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
3982
4130
    ...     [('one', dict(param=1)),
3983
4131
    ...      ('two', dict(param=2))],
3984
 
    ...     TestSuite())
 
4132
    ...     TestUtil.TestSuite())
3985
4133
    >>> tests = list(iter_suite_tests(r))
3986
4134
    >>> len(tests)
3987
4135
    2
4034
4182
    :param new_id: The id to assign to it.
4035
4183
    :return: The new test.
4036
4184
    """
4037
 
    new_test = copy(test)
 
4185
    new_test = copy.copy(test)
4038
4186
    new_test.id = lambda: new_id
 
4187
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4188
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4189
    # read the test output for parameterized tests, because tracebacks will be
 
4190
    # associated with irrelevant tests.
 
4191
    try:
 
4192
        details = new_test._TestCase__details
 
4193
    except AttributeError:
 
4194
        # must be a different version of testtools than expected.  Do nothing.
 
4195
        pass
 
4196
    else:
 
4197
        # Reset the '__details' dict.
 
4198
        new_test._TestCase__details = {}
4039
4199
    return new_test
4040
4200
 
4041
4201
 
4062
4222
        the module is available.
4063
4223
    """
4064
4224
 
4065
 
    py_module = __import__(py_module_name, {}, {}, ['NO_SUCH_ATTRIB'])
 
4225
    py_module = pyutils.get_named_object(py_module_name)
4066
4226
    scenarios = [
4067
4227
        ('python', {'module': py_module}),
4068
4228
    ]
4101
4261
        if test_id != None:
4102
4262
            ui.ui_factory.clear_term()
4103
4263
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4264
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4265
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4266
                                    ).encode('ascii', 'replace')
4104
4267
        sys.stderr.write('Unable to remove testing dir %s\n%s'
4105
 
                         % (os.path.basename(dirname), e))
 
4268
                         % (os.path.basename(dirname), printable_e))
4106
4269
 
4107
4270
 
4108
4271
class Feature(object):
4218
4381
            symbol_versioning.warn(depr_msg + use_msg, DeprecationWarning)
4219
4382
            # Import the new feature and use it as a replacement for the
4220
4383
            # deprecated one.
4221
 
            mod = __import__(self._replacement_module, {}, {},
4222
 
                             [self._replacement_name])
4223
 
            self._feature = getattr(mod, self._replacement_name)
 
4384
            self._feature = pyutils.get_named_object(
 
4385
                self._replacement_module, self._replacement_name)
4224
4386
 
4225
4387
    def _probe(self):
4226
4388
        self._ensure()
4257
4419
        return self.module_name
4258
4420
 
4259
4421
 
4260
 
# This is kept here for compatibility, it is recommended to use
4261
 
# 'bzrlib.tests.feature.paramiko' instead
4262
 
ParamikoFeature = _CompatabilityThunkFeature(
4263
 
    deprecated_in((2,1,0)),
4264
 
    'bzrlib.tests.features', 'ParamikoFeature', 'paramiko')
4265
 
 
4266
 
 
4267
4422
def probe_unicode_in_user_encoding():
4268
4423
    """Try to encode several unicode strings to use in unicode-aware tests.
4269
4424
    Return first successfull match.
4338
4493
UnicodeFilename = _UnicodeFilename()
4339
4494
 
4340
4495
 
 
4496
class _ByteStringNamedFilesystem(Feature):
 
4497
    """Is the filesystem based on bytes?"""
 
4498
 
 
4499
    def _probe(self):
 
4500
        if os.name == "posix":
 
4501
            return True
 
4502
        return False
 
4503
 
 
4504
ByteStringNamedFilesystem = _ByteStringNamedFilesystem()
 
4505
 
 
4506
 
4341
4507
class _UTF8Filesystem(Feature):
4342
4508
    """Is the filesystem UTF-8?"""
4343
4509
 
4445
4611
case_sensitive_filesystem_feature = _CaseSensitiveFilesystemFeature()
4446
4612
 
4447
4613
 
4448
 
# Kept for compatibility, use bzrlib.tests.features.subunit instead
4449
 
SubUnitFeature = _CompatabilityThunkFeature(
4450
 
    deprecated_in((2,1,0)),
4451
 
    'bzrlib.tests.features', 'SubUnitFeature', 'subunit')
4452
4614
# Only define SubUnitBzrRunner if subunit is available.
4453
4615
try:
4454
4616
    from subunit import TestProtocolClient
4455
4617
    from subunit.test_results import AutoTimingTestResultDecorator
 
4618
    class SubUnitBzrProtocolClient(TestProtocolClient):
 
4619
 
 
4620
        def addSuccess(self, test, details=None):
 
4621
            # The subunit client always includes the details in the subunit
 
4622
            # stream, but we don't want to include it in ours.
 
4623
            if details is not None and 'log' in details:
 
4624
                del details['log']
 
4625
            return super(SubUnitBzrProtocolClient, self).addSuccess(
 
4626
                test, details)
 
4627
 
4456
4628
    class SubUnitBzrRunner(TextTestRunner):
4457
4629
        def run(self, test):
4458
4630
            result = AutoTimingTestResultDecorator(
4459
 
                TestProtocolClient(self.stream))
 
4631
                SubUnitBzrProtocolClient(self.stream))
4460
4632
            test.run(result)
4461
4633
            return result
4462
4634
except ImportError: