/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 breezy/tests/__init__.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-08 00:00:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6672.
  • Revision ID: jelmer@jelmer.uk-20170608000028-e3ggtt4wjbcjh91j
Drop pycurl support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2013, 2015, 2016 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Testing framework extensions"""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
# NOTE: Some classes in here use camelCaseNaming() rather than
 
22
# underscore_naming().  That's for consistency with unittest; it's not the
 
23
# general style of breezy.  Please continue that consistency when adding e.g.
 
24
# new assertFoo() methods.
 
25
 
 
26
import atexit
 
27
import codecs
 
28
import copy
 
29
import difflib
 
30
import doctest
 
31
import errno
 
32
import functools
 
33
import itertools
 
34
import logging
 
35
import math
 
36
import os
 
37
import platform
 
38
import pprint
 
39
import random
 
40
import re
 
41
import shlex
 
42
import site
 
43
import stat
 
44
import subprocess
 
45
import sys
 
46
import tempfile
 
47
import threading
 
48
import time
 
49
import traceback
 
50
import unittest
 
51
import warnings
 
52
 
 
53
import testtools
 
54
# nb: check this before importing anything else from within it
 
55
_testtools_version = getattr(testtools, '__version__', ())
 
56
if _testtools_version < (0, 9, 5):
 
57
    raise ImportError("need at least testtools 0.9.5: %s is %r"
 
58
        % (testtools.__file__, _testtools_version))
 
59
from testtools import content
 
60
 
 
61
import breezy
 
62
from .. import (
 
63
    branchbuilder,
 
64
    controldir,
 
65
    chk_map,
 
66
    commands as _mod_commands,
 
67
    config,
 
68
    i18n,
 
69
    debug,
 
70
    errors,
 
71
    hooks,
 
72
    lock as _mod_lock,
 
73
    lockdir,
 
74
    memorytree,
 
75
    osutils,
 
76
    plugin as _mod_plugin,
 
77
    pyutils,
 
78
    ui,
 
79
    urlutils,
 
80
    registry,
 
81
    symbol_versioning,
 
82
    trace,
 
83
    transport as _mod_transport,
 
84
    workingtree,
 
85
    )
 
86
try:
 
87
    import breezy.lsprof
 
88
except ImportError:
 
89
    # lsprof not available
 
90
    pass
 
91
from ..sixish import (
 
92
    BytesIO,
 
93
    string_types,
 
94
    text_type,
 
95
    )
 
96
from ..smart import client, request
 
97
from ..transport import (
 
98
    memory,
 
99
    pathfilter,
 
100
    )
 
101
from ..tests import (
 
102
    fixtures,
 
103
    test_server,
 
104
    TestUtil,
 
105
    treeshape,
 
106
    ui_testing,
 
107
    )
 
108
from ..tests.features import _CompatabilityThunkFeature
 
109
 
 
110
# Mark this python module as being part of the implementation
 
111
# of unittest: this gives us better tracebacks where the last
 
112
# shown frame is the test code, not our assertXYZ.
 
113
__unittest = 1
 
114
 
 
115
default_transport = test_server.LocalURLServer
 
116
 
 
117
 
 
118
_unitialized_attr = object()
 
119
"""A sentinel needed to act as a default value in a method signature."""
 
120
 
 
121
 
 
122
# Subunit result codes, defined here to prevent a hard dependency on subunit.
 
123
SUBUNIT_SEEK_SET = 0
 
124
SUBUNIT_SEEK_CUR = 1
 
125
 
 
126
# These are intentionally brought into this namespace. That way plugins, etc
 
127
# can just "from breezy.tests import TestCase, TestLoader, etc"
 
128
TestSuite = TestUtil.TestSuite
 
129
TestLoader = TestUtil.TestLoader
 
130
 
 
131
# Tests should run in a clean and clearly defined environment. The goal is to
 
132
# keep them isolated from the running environment as mush as possible. The test
 
133
# framework ensures the variables defined below are set (or deleted if the
 
134
# value is None) before a test is run and reset to their original value after
 
135
# the test is run. Generally if some code depends on an environment variable,
 
136
# the tests should start without this variable in the environment. There are a
 
137
# few exceptions but you shouldn't violate this rule lightly.
 
138
isolated_environ = {
 
139
    'BRZ_HOME': None,
 
140
    'HOME': None,
 
141
    'XDG_CONFIG_HOME': None,
 
142
    # brz now uses the Win32 API and doesn't rely on APPDATA, but the
 
143
    # tests do check our impls match APPDATA
 
144
    'BRZ_EDITOR': None, # test_msgeditor manipulates this variable
 
145
    'VISUAL': None,
 
146
    'EDITOR': None,
 
147
    'BRZ_EMAIL': None,
 
148
    'BZREMAIL': None, # may still be present in the environment
 
149
    'EMAIL': 'jrandom@example.com', # set EMAIL as brz does not guess
 
150
    'BRZ_PROGRESS_BAR': None,
 
151
    # This should trap leaks to ~/.brz.log. This occurs when tests use TestCase
 
152
    # as a base class instead of TestCaseInTempDir. Tests inheriting from
 
153
    # TestCase should not use disk resources, BRZ_LOG is one.
 
154
    'BRZ_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
 
155
    'BRZ_PLUGIN_PATH': '-site',
 
156
    'BRZ_DISABLE_PLUGINS': None,
 
157
    'BRZ_PLUGINS_AT': None,
 
158
    'BRZ_CONCURRENCY': None,
 
159
    # Make sure that any text ui tests are consistent regardless of
 
160
    # the environment the test case is run in; you may want tests that
 
161
    # test other combinations.  'dumb' is a reasonable guess for tests
 
162
    # going to a pipe or a BytesIO.
 
163
    'TERM': 'dumb',
 
164
    'LINES': '25',
 
165
    'COLUMNS': '80',
 
166
    'BRZ_COLUMNS': '80',
 
167
    # Disable SSH Agent
 
168
    'SSH_AUTH_SOCK': None,
 
169
    # Proxies
 
170
    'http_proxy': None,
 
171
    'HTTP_PROXY': None,
 
172
    'https_proxy': None,
 
173
    'HTTPS_PROXY': None,
 
174
    'no_proxy': None,
 
175
    'NO_PROXY': None,
 
176
    'all_proxy': None,
 
177
    'ALL_PROXY': None,
 
178
    # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
179
    # least. If you do (care), please update this comment
 
180
    # -- vila 20080401
 
181
    'ftp_proxy': None,
 
182
    'FTP_PROXY': None,
 
183
    'BZR_REMOTE_PATH': None,
 
184
    # Generally speaking, we don't want apport reporting on crashes in
 
185
    # the test envirnoment unless we're specifically testing apport,
 
186
    # so that it doesn't leak into the real system environment.  We
 
187
    # use an env var so it propagates to subprocesses.
 
188
    'APPORT_DISABLE': '1',
 
189
    }
 
190
 
 
191
 
 
192
def override_os_environ(test, env=None):
 
193
    """Modify os.environ keeping a copy.
 
194
    
 
195
    :param test: A test instance
 
196
 
 
197
    :param env: A dict containing variable definitions to be installed
 
198
    """
 
199
    if env is None:
 
200
        env = isolated_environ
 
201
    test._original_os_environ = dict(**os.environ)
 
202
    for var in env:
 
203
        osutils.set_or_unset_env(var, env[var])
 
204
        if var not in test._original_os_environ:
 
205
            # The var is new, add it with a value of None, so
 
206
            # restore_os_environ will delete it
 
207
            test._original_os_environ[var] = None
 
208
 
 
209
 
 
210
def restore_os_environ(test):
 
211
    """Restore os.environ to its original state.
 
212
 
 
213
    :param test: A test instance previously passed to override_os_environ.
 
214
    """
 
215
    for var, value in test._original_os_environ.items():
 
216
        # Restore the original value (or delete it if the value has been set to
 
217
        # None in override_os_environ).
 
218
        osutils.set_or_unset_env(var, value)
 
219
 
 
220
 
 
221
def _clear__type_equality_funcs(test):
 
222
    """Cleanup bound methods stored on TestCase instances
 
223
 
 
224
    Clear the dict breaking a few (mostly) harmless cycles in the affected
 
225
    unittests released with Python 2.6 and initial Python 2.7 versions.
 
226
 
 
227
    For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
 
228
    shipped in Oneiric, an object with no clear method was used, hence the
 
229
    extra complications, see bug 809048 for details.
 
230
    """
 
231
    type_equality_funcs = getattr(test, "_type_equality_funcs", None)
 
232
    if type_equality_funcs is not None:
 
233
        tef_clear = getattr(type_equality_funcs, "clear", None)
 
234
        if tef_clear is None:
 
235
            tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
 
236
            if tef_instance_dict is not None:
 
237
                tef_clear = tef_instance_dict.clear
 
238
        if tef_clear is not None:
 
239
            tef_clear()
 
240
 
 
241
 
 
242
class ExtendedTestResult(testtools.TextTestResult):
 
243
    """Accepts, reports and accumulates the results of running tests.
 
244
 
 
245
    Compared to the unittest version this class adds support for
 
246
    profiling, benchmarking, stopping as soon as a test fails,  and
 
247
    skipping tests.  There are further-specialized subclasses for
 
248
    different types of display.
 
249
 
 
250
    When a test finishes, in whatever way, it calls one of the addSuccess,
 
251
    addFailure or addError methods.  These in turn may redirect to a more
 
252
    specific case for the special test results supported by our extended
 
253
    tests.
 
254
 
 
255
    Note that just one of these objects is fed the results from many tests.
 
256
    """
 
257
 
 
258
    stop_early = False
 
259
 
 
260
    def __init__(self, stream, descriptions, verbosity,
 
261
                 bench_history=None,
 
262
                 strict=False,
 
263
                 ):
 
264
        """Construct new TestResult.
 
265
 
 
266
        :param bench_history: Optionally, a writable file object to accumulate
 
267
            benchmark results.
 
268
        """
 
269
        testtools.TextTestResult.__init__(self, stream)
 
270
        if bench_history is not None:
 
271
            from breezy.version import _get_bzr_source_tree
 
272
            src_tree = _get_bzr_source_tree()
 
273
            if src_tree:
 
274
                try:
 
275
                    revision_id = src_tree.get_parent_ids()[0]
 
276
                except IndexError:
 
277
                    # XXX: if this is a brand new tree, do the same as if there
 
278
                    # is no branch.
 
279
                    revision_id = ''
 
280
            else:
 
281
                # XXX: If there's no branch, what should we do?
 
282
                revision_id = ''
 
283
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
 
284
        self._bench_history = bench_history
 
285
        self.ui = ui.ui_factory
 
286
        self.num_tests = 0
 
287
        self.error_count = 0
 
288
        self.failure_count = 0
 
289
        self.known_failure_count = 0
 
290
        self.skip_count = 0
 
291
        self.not_applicable_count = 0
 
292
        self.unsupported = {}
 
293
        self.count = 0
 
294
        self._overall_start_time = time.time()
 
295
        self._strict = strict
 
296
        self._first_thread_leaker_id = None
 
297
        self._tests_leaking_threads_count = 0
 
298
        self._traceback_from_test = None
 
299
 
 
300
    def stopTestRun(self):
 
301
        run = self.testsRun
 
302
        actionTaken = "Ran"
 
303
        stopTime = time.time()
 
304
        timeTaken = stopTime - self.startTime
 
305
        # GZ 2010-07-19: Seems testtools has no printErrors method, and though
 
306
        #                the parent class method is similar have to duplicate
 
307
        self._show_list('ERROR', self.errors)
 
308
        self._show_list('FAIL', self.failures)
 
309
        self.stream.write(self.sep2)
 
310
        self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
 
311
                            run, run != 1 and "s" or "", timeTaken))
 
312
        if not self.wasSuccessful():
 
313
            self.stream.write("FAILED (")
 
314
            failed, errored = map(len, (self.failures, self.errors))
 
315
            if failed:
 
316
                self.stream.write("failures=%d" % failed)
 
317
            if errored:
 
318
                if failed: self.stream.write(", ")
 
319
                self.stream.write("errors=%d" % errored)
 
320
            if self.known_failure_count:
 
321
                if failed or errored: self.stream.write(", ")
 
322
                self.stream.write("known_failure_count=%d" %
 
323
                    self.known_failure_count)
 
324
            self.stream.write(")\n")
 
325
        else:
 
326
            if self.known_failure_count:
 
327
                self.stream.write("OK (known_failures=%d)\n" %
 
328
                    self.known_failure_count)
 
329
            else:
 
330
                self.stream.write("OK\n")
 
331
        if self.skip_count > 0:
 
332
            skipped = self.skip_count
 
333
            self.stream.write('%d test%s skipped\n' %
 
334
                                (skipped, skipped != 1 and "s" or ""))
 
335
        if self.unsupported:
 
336
            for feature, count in sorted(self.unsupported.items()):
 
337
                self.stream.write("Missing feature '%s' skipped %d tests.\n" %
 
338
                    (feature, count))
 
339
        if self._strict:
 
340
            ok = self.wasStrictlySuccessful()
 
341
        else:
 
342
            ok = self.wasSuccessful()
 
343
        if self._first_thread_leaker_id:
 
344
            self.stream.write(
 
345
                '%s is leaking threads among %d leaking tests.\n' % (
 
346
                self._first_thread_leaker_id,
 
347
                self._tests_leaking_threads_count))
 
348
            # We don't report the main thread as an active one.
 
349
            self.stream.write(
 
350
                '%d non-main threads were left active in the end.\n'
 
351
                % (len(self._active_threads) - 1))
 
352
 
 
353
    def getDescription(self, test):
 
354
        return test.id()
 
355
 
 
356
    def _extractBenchmarkTime(self, testCase, details=None):
 
357
        """Add a benchmark time for the current test case."""
 
358
        if details and 'benchtime' in details:
 
359
            return float(''.join(details['benchtime'].iter_bytes()))
 
360
        return getattr(testCase, "_benchtime", None)
 
361
 
 
362
    def _delta_to_float(self, a_timedelta, precision):
 
363
        # This calls ceiling to ensure that the most pessimistic view of time
 
364
        # taken is shown (rather than leaving it to the Python %f operator
 
365
        # to decide whether to round/floor/ceiling. This was added when we
 
366
        # had pyp3 test failures that suggest a floor was happening.
 
367
        shift = 10 ** precision
 
368
        return math.ceil((a_timedelta.days * 86400.0 + a_timedelta.seconds +
 
369
            a_timedelta.microseconds / 1000000.0) * shift) / shift
 
370
 
 
371
    def _elapsedTestTimeString(self):
 
372
        """Return a time string for the overall time the current test has taken."""
 
373
        return self._formatTime(self._delta_to_float(
 
374
            self._now() - self._start_datetime, 3))
 
375
 
 
376
    def _testTimeString(self, testCase):
 
377
        benchmark_time = self._extractBenchmarkTime(testCase)
 
378
        if benchmark_time is not None:
 
379
            return self._formatTime(benchmark_time) + "*"
 
380
        else:
 
381
            return self._elapsedTestTimeString()
 
382
 
 
383
    def _formatTime(self, seconds):
 
384
        """Format seconds as milliseconds with leading spaces."""
 
385
        # some benchmarks can take thousands of seconds to run, so we need 8
 
386
        # places
 
387
        return "%8dms" % (1000 * seconds)
 
388
 
 
389
    def _shortened_test_description(self, test):
 
390
        what = test.id()
 
391
        what = re.sub(r'^breezy\.tests\.', '', what)
 
392
        return what
 
393
 
 
394
    # GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
 
395
    #                multiple times in a row, because the handler is added for
 
396
    #                each test but the container list is shared between cases.
 
397
    #                See lp:498869 lp:625574 and lp:637725 for background.
 
398
    def _record_traceback_from_test(self, exc_info):
 
399
        """Store the traceback from passed exc_info tuple till"""
 
400
        self._traceback_from_test = exc_info[2]
 
401
 
 
402
    def startTest(self, test):
 
403
        super(ExtendedTestResult, self).startTest(test)
 
404
        if self.count == 0:
 
405
            self.startTests()
 
406
        self.count += 1
 
407
        self.report_test_start(test)
 
408
        test.number = self.count
 
409
        self._recordTestStartTime()
 
410
        # Make testtools cases give us the real traceback on failure
 
411
        addOnException = getattr(test, "addOnException", None)
 
412
        if addOnException is not None:
 
413
            addOnException(self._record_traceback_from_test)
 
414
        # Only check for thread leaks on breezy derived test cases
 
415
        if isinstance(test, TestCase):
 
416
            test.addCleanup(self._check_leaked_threads, test)
 
417
 
 
418
    def stopTest(self, test):
 
419
        super(ExtendedTestResult, self).stopTest(test)
 
420
        # Manually break cycles, means touching various private things but hey
 
421
        getDetails = getattr(test, "getDetails", None)
 
422
        if getDetails is not None:
 
423
            getDetails().clear()
 
424
        _clear__type_equality_funcs(test)
 
425
        self._traceback_from_test = None
 
426
 
 
427
    def startTests(self):
 
428
        self.report_tests_starting()
 
429
        self._active_threads = threading.enumerate()
 
430
 
 
431
    def _check_leaked_threads(self, test):
 
432
        """See if any threads have leaked since last call
 
433
 
 
434
        A sample of live threads is stored in the _active_threads attribute,
 
435
        when this method runs it compares the current live threads and any not
 
436
        in the previous sample are treated as having leaked.
 
437
        """
 
438
        now_active_threads = set(threading.enumerate())
 
439
        threads_leaked = now_active_threads.difference(self._active_threads)
 
440
        if threads_leaked:
 
441
            self._report_thread_leak(test, threads_leaked, now_active_threads)
 
442
            self._tests_leaking_threads_count += 1
 
443
            if self._first_thread_leaker_id is None:
 
444
                self._first_thread_leaker_id = test.id()
 
445
            self._active_threads = now_active_threads
 
446
 
 
447
    def _recordTestStartTime(self):
 
448
        """Record that a test has started."""
 
449
        self._start_datetime = self._now()
 
450
 
 
451
    def addError(self, test, err):
 
452
        """Tell result that test finished with an error.
 
453
 
 
454
        Called from the TestCase run() method when the test
 
455
        fails with an unexpected error.
 
456
        """
 
457
        self._post_mortem(self._traceback_from_test)
 
458
        super(ExtendedTestResult, self).addError(test, err)
 
459
        self.error_count += 1
 
460
        self.report_error(test, err)
 
461
        if self.stop_early:
 
462
            self.stop()
 
463
 
 
464
    def addFailure(self, test, err):
 
465
        """Tell result that test failed.
 
466
 
 
467
        Called from the TestCase run() method when the test
 
468
        fails because e.g. an assert() method failed.
 
469
        """
 
470
        self._post_mortem(self._traceback_from_test)
 
471
        super(ExtendedTestResult, self).addFailure(test, err)
 
472
        self.failure_count += 1
 
473
        self.report_failure(test, err)
 
474
        if self.stop_early:
 
475
            self.stop()
 
476
 
 
477
    def addSuccess(self, test, details=None):
 
478
        """Tell result that test completed successfully.
 
479
 
 
480
        Called from the TestCase run()
 
481
        """
 
482
        if self._bench_history is not None:
 
483
            benchmark_time = self._extractBenchmarkTime(test, details)
 
484
            if benchmark_time is not None:
 
485
                self._bench_history.write("%s %s\n" % (
 
486
                    self._formatTime(benchmark_time),
 
487
                    test.id()))
 
488
        self.report_success(test)
 
489
        super(ExtendedTestResult, self).addSuccess(test)
 
490
        test._log_contents = ''
 
491
 
 
492
    def addExpectedFailure(self, test, err):
 
493
        self.known_failure_count += 1
 
494
        self.report_known_failure(test, err)
 
495
 
 
496
    def addUnexpectedSuccess(self, test, details=None):
 
497
        """Tell result the test unexpectedly passed, counting as a failure
 
498
 
 
499
        When the minimum version of testtools required becomes 0.9.8 this
 
500
        can be updated to use the new handling there.
 
501
        """
 
502
        super(ExtendedTestResult, self).addFailure(test, details=details)
 
503
        self.failure_count += 1
 
504
        self.report_unexpected_success(test,
 
505
            "".join(details["reason"].iter_text()))
 
506
        if self.stop_early:
 
507
            self.stop()
 
508
 
 
509
    def addNotSupported(self, test, feature):
 
510
        """The test will not be run because of a missing feature.
 
511
        """
 
512
        # this can be called in two different ways: it may be that the
 
513
        # test started running, and then raised (through requireFeature)
 
514
        # UnavailableFeature.  Alternatively this method can be called
 
515
        # while probing for features before running the test code proper; in
 
516
        # that case we will see startTest and stopTest, but the test will
 
517
        # never actually run.
 
518
        self.unsupported.setdefault(str(feature), 0)
 
519
        self.unsupported[str(feature)] += 1
 
520
        self.report_unsupported(test, feature)
 
521
 
 
522
    def addSkip(self, test, reason):
 
523
        """A test has not run for 'reason'."""
 
524
        self.skip_count += 1
 
525
        self.report_skip(test, reason)
 
526
 
 
527
    def addNotApplicable(self, test, reason):
 
528
        self.not_applicable_count += 1
 
529
        self.report_not_applicable(test, reason)
 
530
 
 
531
    def _count_stored_tests(self):
 
532
        """Count of tests instances kept alive due to not succeeding"""
 
533
        return self.error_count + self.failure_count + self.known_failure_count
 
534
 
 
535
    def _post_mortem(self, tb=None):
 
536
        """Start a PDB post mortem session."""
 
537
        if os.environ.get('BRZ_TEST_PDB', None):
 
538
            import pdb
 
539
            pdb.post_mortem(tb)
 
540
 
 
541
    def progress(self, offset, whence):
 
542
        """The test is adjusting the count of tests to run."""
 
543
        if whence == SUBUNIT_SEEK_SET:
 
544
            self.num_tests = offset
 
545
        elif whence == SUBUNIT_SEEK_CUR:
 
546
            self.num_tests += offset
 
547
        else:
 
548
            raise errors.BzrError("Unknown whence %r" % whence)
 
549
 
 
550
    def report_tests_starting(self):
 
551
        """Display information before the test run begins"""
 
552
        if getattr(sys, 'frozen', None) is None:
 
553
            bzr_path = osutils.realpath(sys.argv[0])
 
554
        else:
 
555
            bzr_path = sys.executable
 
556
        self.stream.write(
 
557
            'brz selftest: %s\n' % (bzr_path,))
 
558
        self.stream.write(
 
559
            '   %s\n' % (
 
560
                    breezy.__path__[0],))
 
561
        self.stream.write(
 
562
            '   bzr-%s python-%s %s\n' % (
 
563
                    breezy.version_string,
 
564
                    breezy._format_version_tuple(sys.version_info),
 
565
                    platform.platform(aliased=1),
 
566
                    ))
 
567
        self.stream.write('\n')
 
568
 
 
569
    def report_test_start(self, test):
 
570
        """Display information on the test just about to be run"""
 
571
 
 
572
    def _report_thread_leak(self, test, leaked_threads, active_threads):
 
573
        """Display information on a test that leaked one or more threads"""
 
574
        # GZ 2010-09-09: A leak summary reported separately from the general
 
575
        #                thread debugging would be nice. Tests under subunit
 
576
        #                need something not using stream, perhaps adding a
 
577
        #                testtools details object would be fitting.
 
578
        if 'threads' in selftest_debug_flags:
 
579
            self.stream.write('%s is leaking, active is now %d\n' %
 
580
                (test.id(), len(active_threads)))
 
581
 
 
582
    def startTestRun(self):
 
583
        self.startTime = time.time()
 
584
 
 
585
    def report_success(self, test):
 
586
        pass
 
587
 
 
588
    def wasStrictlySuccessful(self):
 
589
        if self.unsupported or self.known_failure_count:
 
590
            return False
 
591
        return self.wasSuccessful()
 
592
 
 
593
 
 
594
class TextTestResult(ExtendedTestResult):
 
595
    """Displays progress and results of tests in text form"""
 
596
 
 
597
    def __init__(self, stream, descriptions, verbosity,
 
598
                 bench_history=None,
 
599
                 pb=None,
 
600
                 strict=None,
 
601
                 ):
 
602
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
 
603
            bench_history, strict)
 
604
        # We no longer pass them around, but just rely on the UIFactory stack
 
605
        # for state
 
606
        if pb is not None:
 
607
            warnings.warn("Passing pb to TextTestResult is deprecated")
 
608
        self.pb = self.ui.nested_progress_bar()
 
609
        self.pb.show_pct = False
 
610
        self.pb.show_spinner = False
 
611
        self.pb.show_eta = False,
 
612
        self.pb.show_count = False
 
613
        self.pb.show_bar = False
 
614
        self.pb.update_latency = 0
 
615
        self.pb.show_transport_activity = False
 
616
 
 
617
    def stopTestRun(self):
 
618
        # called when the tests that are going to run have run
 
619
        self.pb.clear()
 
620
        self.pb.finished()
 
621
        super(TextTestResult, self).stopTestRun()
 
622
 
 
623
    def report_tests_starting(self):
 
624
        super(TextTestResult, self).report_tests_starting()
 
625
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
 
626
 
 
627
    def _progress_prefix_text(self):
 
628
        # the longer this text, the less space we have to show the test
 
629
        # name...
 
630
        a = '[%d' % self.count              # total that have been run
 
631
        # tests skipped as known not to be relevant are not important enough
 
632
        # to show here
 
633
        ## if self.skip_count:
 
634
        ##     a += ', %d skip' % self.skip_count
 
635
        ## if self.known_failure_count:
 
636
        ##     a += '+%dX' % self.known_failure_count
 
637
        if self.num_tests:
 
638
            a +='/%d' % self.num_tests
 
639
        a += ' in '
 
640
        runtime = time.time() - self._overall_start_time
 
641
        if runtime >= 60:
 
642
            a += '%dm%ds' % (runtime / 60, runtime % 60)
 
643
        else:
 
644
            a += '%ds' % runtime
 
645
        total_fail_count = self.error_count + self.failure_count
 
646
        if total_fail_count:
 
647
            a += ', %d failed' % total_fail_count
 
648
        # if self.unsupported:
 
649
        #     a += ', %d missing' % len(self.unsupported)
 
650
        a += ']'
 
651
        return a
 
652
 
 
653
    def report_test_start(self, test):
 
654
        self.pb.update(
 
655
                self._progress_prefix_text()
 
656
                + ' '
 
657
                + self._shortened_test_description(test))
 
658
 
 
659
    def _test_description(self, test):
 
660
        return self._shortened_test_description(test)
 
661
 
 
662
    def report_error(self, test, err):
 
663
        self.stream.write('ERROR: %s\n    %s\n' % (
 
664
            self._test_description(test),
 
665
            err[1],
 
666
            ))
 
667
 
 
668
    def report_failure(self, test, err):
 
669
        self.stream.write('FAIL: %s\n    %s\n' % (
 
670
            self._test_description(test),
 
671
            err[1],
 
672
            ))
 
673
 
 
674
    def report_known_failure(self, test, err):
 
675
        pass
 
676
 
 
677
    def report_unexpected_success(self, test, reason):
 
678
        self.stream.write('FAIL: %s\n    %s: %s\n' % (
 
679
            self._test_description(test),
 
680
            "Unexpected success. Should have failed",
 
681
            reason,
 
682
            ))
 
683
 
 
684
    def report_skip(self, test, reason):
 
685
        pass
 
686
 
 
687
    def report_not_applicable(self, test, reason):
 
688
        pass
 
689
 
 
690
    def report_unsupported(self, test, feature):
 
691
        """test cannot be run because feature is missing."""
 
692
 
 
693
 
 
694
class VerboseTestResult(ExtendedTestResult):
 
695
    """Produce long output, with one line per test run plus times"""
 
696
 
 
697
    def _ellipsize_to_right(self, a_string, final_width):
 
698
        """Truncate and pad a string, keeping the right hand side"""
 
699
        if len(a_string) > final_width:
 
700
            result = '...' + a_string[3-final_width:]
 
701
        else:
 
702
            result = a_string
 
703
        return result.ljust(final_width)
 
704
 
 
705
    def report_tests_starting(self):
 
706
        self.stream.write('running %d tests...\n' % self.num_tests)
 
707
        super(VerboseTestResult, self).report_tests_starting()
 
708
 
 
709
    def report_test_start(self, test):
 
710
        name = self._shortened_test_description(test)
 
711
        width = osutils.terminal_width()
 
712
        if width is not None:
 
713
            # width needs space for 6 char status, plus 1 for slash, plus an
 
714
            # 11-char time string, plus a trailing blank
 
715
            # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on
 
716
            # space
 
717
            self.stream.write(self._ellipsize_to_right(name, width-18))
 
718
        else:
 
719
            self.stream.write(name)
 
720
        self.stream.flush()
 
721
 
 
722
    def _error_summary(self, err):
 
723
        indent = ' ' * 4
 
724
        return '%s%s' % (indent, err[1])
 
725
 
 
726
    def report_error(self, test, err):
 
727
        self.stream.write('ERROR %s\n%s\n'
 
728
                % (self._testTimeString(test),
 
729
                   self._error_summary(err)))
 
730
 
 
731
    def report_failure(self, test, err):
 
732
        self.stream.write(' FAIL %s\n%s\n'
 
733
                % (self._testTimeString(test),
 
734
                   self._error_summary(err)))
 
735
 
 
736
    def report_known_failure(self, test, err):
 
737
        self.stream.write('XFAIL %s\n%s\n'
 
738
                % (self._testTimeString(test),
 
739
                   self._error_summary(err)))
 
740
 
 
741
    def report_unexpected_success(self, test, reason):
 
742
        self.stream.write(' FAIL %s\n%s: %s\n'
 
743
                % (self._testTimeString(test),
 
744
                   "Unexpected success. Should have failed",
 
745
                   reason))
 
746
 
 
747
    def report_success(self, test):
 
748
        self.stream.write('   OK %s\n' % self._testTimeString(test))
 
749
        for bench_called, stats in getattr(test, '_benchcalls', []):
 
750
            self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
 
751
            stats.pprint(file=self.stream)
 
752
        # flush the stream so that we get smooth output. This verbose mode is
 
753
        # used to show the output in PQM.
 
754
        self.stream.flush()
 
755
 
 
756
    def report_skip(self, test, reason):
 
757
        self.stream.write(' SKIP %s\n%s\n'
 
758
                % (self._testTimeString(test), reason))
 
759
 
 
760
    def report_not_applicable(self, test, reason):
 
761
        self.stream.write('  N/A %s\n    %s\n'
 
762
                % (self._testTimeString(test), reason))
 
763
 
 
764
    def report_unsupported(self, test, feature):
 
765
        """test cannot be run because feature is missing."""
 
766
        self.stream.write("NODEP %s\n    The feature '%s' is not available.\n"
 
767
                %(self._testTimeString(test), feature))
 
768
 
 
769
 
 
770
class TextTestRunner(object):
 
771
    stop_on_failure = False
 
772
 
 
773
    def __init__(self,
 
774
                 stream=sys.stderr,
 
775
                 descriptions=0,
 
776
                 verbosity=1,
 
777
                 bench_history=None,
 
778
                 strict=False,
 
779
                 result_decorators=None,
 
780
                 ):
 
781
        """Create a TextTestRunner.
 
782
 
 
783
        :param result_decorators: An optional list of decorators to apply
 
784
            to the result object being used by the runner. Decorators are
 
785
            applied left to right - the first element in the list is the 
 
786
            innermost decorator.
 
787
        """
 
788
        # stream may know claim to know to write unicode strings, but in older
 
789
        # pythons this goes sufficiently wrong that it is a bad idea. (
 
790
        # specifically a built in file with encoding 'UTF-8' will still try
 
791
        # to encode using ascii.
 
792
        new_encoding = osutils.get_terminal_encoding()
 
793
        codec = codecs.lookup(new_encoding)
 
794
        if isinstance(codec, tuple):
 
795
            # Python 2.4
 
796
            encode = codec[0]
 
797
        else:
 
798
            encode = codec.encode
 
799
        # GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
 
800
        #                so should swap to the plain codecs.StreamWriter
 
801
        stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
 
802
            "backslashreplace")
 
803
        stream.encoding = new_encoding
 
804
        self.stream = stream
 
805
        self.descriptions = descriptions
 
806
        self.verbosity = verbosity
 
807
        self._bench_history = bench_history
 
808
        self._strict = strict
 
809
        self._result_decorators = result_decorators or []
 
810
 
 
811
    def run(self, test):
 
812
        "Run the given test case or test suite."
 
813
        if self.verbosity == 1:
 
814
            result_class = TextTestResult
 
815
        elif self.verbosity >= 2:
 
816
            result_class = VerboseTestResult
 
817
        original_result = result_class(self.stream,
 
818
                              self.descriptions,
 
819
                              self.verbosity,
 
820
                              bench_history=self._bench_history,
 
821
                              strict=self._strict,
 
822
                              )
 
823
        # Signal to result objects that look at stop early policy to stop,
 
824
        original_result.stop_early = self.stop_on_failure
 
825
        result = original_result
 
826
        for decorator in self._result_decorators:
 
827
            result = decorator(result)
 
828
            result.stop_early = self.stop_on_failure
 
829
        result.startTestRun()
 
830
        try:
 
831
            test.run(result)
 
832
        finally:
 
833
            result.stopTestRun()
 
834
        # higher level code uses our extended protocol to determine
 
835
        # what exit code to give.
 
836
        return original_result
 
837
 
 
838
 
 
839
def iter_suite_tests(suite):
 
840
    """Return all tests in a suite, recursing through nested suites"""
 
841
    if isinstance(suite, unittest.TestCase):
 
842
        yield suite
 
843
    elif isinstance(suite, unittest.TestSuite):
 
844
        for item in suite:
 
845
            for r in iter_suite_tests(item):
 
846
                yield r
 
847
    else:
 
848
        raise Exception('unknown type %r for object %r'
 
849
                        % (type(suite), suite))
 
850
 
 
851
 
 
852
TestSkipped = testtools.testcase.TestSkipped
 
853
 
 
854
 
 
855
class TestNotApplicable(TestSkipped):
 
856
    """A test is not applicable to the situation where it was run.
 
857
 
 
858
    This is only normally raised by parameterized tests, if they find that
 
859
    the instance they're constructed upon does not support one aspect
 
860
    of its interface.
 
861
    """
 
862
 
 
863
 
 
864
# traceback._some_str fails to format exceptions that have the default
 
865
# __str__ which does an implicit ascii conversion. However, repr() on those
 
866
# objects works, for all that its not quite what the doctor may have ordered.
 
867
def _clever_some_str(value):
 
868
    try:
 
869
        return str(value)
 
870
    except:
 
871
        try:
 
872
            return repr(value).replace('\\n', '\n')
 
873
        except:
 
874
            return '<unprintable %s object>' % type(value).__name__
 
875
 
 
876
traceback._some_str = _clever_some_str
 
877
 
 
878
 
 
879
# deprecated - use self.knownFailure(), or self.expectFailure.
 
880
KnownFailure = testtools.testcase._ExpectedFailure
 
881
 
 
882
 
 
883
class UnavailableFeature(Exception):
 
884
    """A feature required for this test was not available.
 
885
 
 
886
    This can be considered a specialised form of SkippedTest.
 
887
 
 
888
    The feature should be used to construct the exception.
 
889
    """
 
890
 
 
891
 
 
892
class StringIOWrapper(ui_testing.BytesIOWithEncoding):
 
893
 
 
894
    @symbol_versioning.deprecated_method(
 
895
        symbol_versioning.deprecated_in((3, 0)))
 
896
    def __init__(self, s=None):
 
897
        super(StringIOWrapper, self).__init__(s)
 
898
 
 
899
 
 
900
TestUIFactory = ui_testing.TestUIFactory
 
901
 
 
902
 
 
903
def isolated_doctest_setUp(test):
 
904
    override_os_environ(test)
 
905
    test._orig_ui_factory = ui.ui_factory
 
906
    ui.ui_factory = ui.SilentUIFactory()
 
907
 
 
908
 
 
909
def isolated_doctest_tearDown(test):
 
910
    restore_os_environ(test)
 
911
    ui.ui_factory = test._orig_ui_factory
 
912
 
 
913
 
 
914
def IsolatedDocTestSuite(*args, **kwargs):
 
915
    """Overrides doctest.DocTestSuite to handle isolation.
 
916
 
 
917
    The method is really a factory and users are expected to use it as such.
 
918
    """
 
919
 
 
920
    kwargs['setUp'] = isolated_doctest_setUp
 
921
    kwargs['tearDown'] = isolated_doctest_tearDown
 
922
    return doctest.DocTestSuite(*args, **kwargs)
 
923
 
 
924
 
 
925
class TestCase(testtools.TestCase):
 
926
    """Base class for brz unit tests.
 
927
 
 
928
    Tests that need access to disk resources should subclass
 
929
    TestCaseInTempDir not TestCase.
 
930
 
 
931
    Error and debug log messages are redirected from their usual
 
932
    location into a temporary file, the contents of which can be
 
933
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
 
934
    so that it can also capture file IO.  When the test completes this file
 
935
    is read into memory and removed from disk.
 
936
 
 
937
    There are also convenience functions to invoke bzr's command-line
 
938
    routine, and to build and check brz trees.
 
939
 
 
940
    In addition to the usual method of overriding tearDown(), this class also
 
941
    allows subclasses to register cleanup functions via addCleanup, which are
 
942
    run in order as the object is torn down.  It's less likely this will be
 
943
    accidentally overlooked.
 
944
    """
 
945
 
 
946
    _log_file = None
 
947
    # record lsprof data when performing benchmark calls.
 
948
    _gather_lsprof_in_benchmarks = False
 
949
 
 
950
    def __init__(self, methodName='testMethod'):
 
951
        super(TestCase, self).__init__(methodName)
 
952
        self._directory_isolation = True
 
953
        self.exception_handlers.insert(0,
 
954
            (UnavailableFeature, self._do_unsupported_or_skip))
 
955
        self.exception_handlers.insert(0,
 
956
            (TestNotApplicable, self._do_not_applicable))
 
957
 
 
958
    def setUp(self):
 
959
        super(TestCase, self).setUp()
 
960
 
 
961
        # At this point we're still accessing the config files in $BRZ_HOME (as
 
962
        # set by the user running selftest).
 
963
        timeout = config.GlobalStack().get('selftest.timeout')
 
964
        if timeout:
 
965
            timeout_fixture = fixtures.TimeoutFixture(timeout)
 
966
            timeout_fixture.setUp()
 
967
            self.addCleanup(timeout_fixture.cleanUp)
 
968
 
 
969
        for feature in getattr(self, '_test_needs_features', []):
 
970
            self.requireFeature(feature)
 
971
        self._cleanEnvironment()
 
972
 
 
973
        if breezy.global_state is not None:
 
974
            self.overrideAttr(breezy.global_state, 'cmdline_overrides',
 
975
                              config.CommandLineStore())
 
976
 
 
977
        self._silenceUI()
 
978
        self._startLogFile()
 
979
        self._benchcalls = []
 
980
        self._benchtime = None
 
981
        self._clear_hooks()
 
982
        self._track_transports()
 
983
        self._track_locks()
 
984
        self._clear_debug_flags()
 
985
        # Isolate global verbosity level, to make sure it's reproducible
 
986
        # between tests.  We should get rid of this altogether: bug 656694. --
 
987
        # mbp 20101008
 
988
        self.overrideAttr(breezy.trace, '_verbosity_level', 0)
 
989
        self._log_files = set()
 
990
        # Each key in the ``_counters`` dict holds a value for a different
 
991
        # counter. When the test ends, addDetail() should be used to output the
 
992
        # counter values. This happens in install_counter_hook().
 
993
        self._counters = {}
 
994
        if 'config_stats' in selftest_debug_flags:
 
995
            self._install_config_stats_hooks()
 
996
        # Do not use i18n for tests (unless the test reverses this)
 
997
        i18n.disable_i18n()
 
998
 
 
999
    def debug(self):
 
1000
        # debug a frame up.
 
1001
        import pdb
 
1002
        # The sys preserved stdin/stdout should allow blackbox tests debugging
 
1003
        pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
 
1004
                ).set_trace(sys._getframe().f_back)
 
1005
 
 
1006
    def discardDetail(self, name):
 
1007
        """Extend the addDetail, getDetails api so we can remove a detail.
 
1008
 
 
1009
        eg. brz always adds the 'log' detail at startup, but we don't want to
 
1010
        include it for skipped, xfail, etc tests.
 
1011
 
 
1012
        It is safe to call this for a detail that doesn't exist, in case this
 
1013
        gets called multiple times.
 
1014
        """
 
1015
        # We cheat. details is stored in __details which means we shouldn't
 
1016
        # touch it. but getDetails() returns the dict directly, so we can
 
1017
        # mutate it.
 
1018
        details = self.getDetails()
 
1019
        if name in details:
 
1020
            del details[name]
 
1021
 
 
1022
    def install_counter_hook(self, hooks, name, counter_name=None):
 
1023
        """Install a counting hook.
 
1024
 
 
1025
        Any hook can be counted as long as it doesn't need to return a value.
 
1026
 
 
1027
        :param hooks: Where the hook should be installed.
 
1028
 
 
1029
        :param name: The hook name that will be counted.
 
1030
 
 
1031
        :param counter_name: The counter identifier in ``_counters``, defaults
 
1032
            to ``name``.
 
1033
        """
 
1034
        _counters = self._counters # Avoid closing over self
 
1035
        if counter_name is None:
 
1036
            counter_name = name
 
1037
        if counter_name in _counters:
 
1038
            raise AssertionError('%s is already used as a counter name'
 
1039
                                  % (counter_name,))
 
1040
        _counters[counter_name] = 0
 
1041
        self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
 
1042
            lambda: ['%d' % (_counters[counter_name],)]))
 
1043
        def increment_counter(*args, **kwargs):
 
1044
            _counters[counter_name] += 1
 
1045
        label = 'count %s calls' % (counter_name,)
 
1046
        hooks.install_named_hook(name, increment_counter, label)
 
1047
        self.addCleanup(hooks.uninstall_named_hook, name, label)
 
1048
 
 
1049
    def _install_config_stats_hooks(self):
 
1050
        """Install config hooks to count hook calls.
 
1051
 
 
1052
        """
 
1053
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1054
            self.install_counter_hook(config.ConfigHooks, hook_name,
 
1055
                                       'config.%s' % (hook_name,))
 
1056
 
 
1057
        # The OldConfigHooks are private and need special handling to protect
 
1058
        # against recursive tests (tests that run other tests), so we just do
 
1059
        # manually what registering them into _builtin_known_hooks will provide
 
1060
        # us.
 
1061
        self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
 
1062
        for hook_name in ('get', 'set', 'remove', 'load', 'save'):
 
1063
            self.install_counter_hook(config.OldConfigHooks, hook_name,
 
1064
                                      'old_config.%s' % (hook_name,))
 
1065
 
 
1066
    def _clear_debug_flags(self):
 
1067
        """Prevent externally set debug flags affecting tests.
 
1068
 
 
1069
        Tests that want to use debug flags can just set them in the
 
1070
        debug_flags set during setup/teardown.
 
1071
        """
 
1072
        # Start with a copy of the current debug flags we can safely modify.
 
1073
        self.overrideAttr(debug, 'debug_flags', set(debug.debug_flags))
 
1074
        if 'allow_debug' not in selftest_debug_flags:
 
1075
            debug.debug_flags.clear()
 
1076
        if 'disable_lock_checks' not in selftest_debug_flags:
 
1077
            debug.debug_flags.add('strict_locks')
 
1078
 
 
1079
    def _clear_hooks(self):
 
1080
        # prevent hooks affecting tests
 
1081
        known_hooks = hooks.known_hooks
 
1082
        self._preserved_hooks = {}
 
1083
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1084
            current_hooks = getattr(parent, name)
 
1085
            self._preserved_hooks[parent] = (name, current_hooks)
 
1086
        self._preserved_lazy_hooks = hooks._lazy_hooks
 
1087
        hooks._lazy_hooks = {}
 
1088
        self.addCleanup(self._restoreHooks)
 
1089
        for key, (parent, name) in known_hooks.iter_parent_objects():
 
1090
            factory = known_hooks.get(key)
 
1091
            setattr(parent, name, factory())
 
1092
        # this hook should always be installed
 
1093
        request._install_hook()
 
1094
 
 
1095
    def disable_directory_isolation(self):
 
1096
        """Turn off directory isolation checks."""
 
1097
        self._directory_isolation = False
 
1098
 
 
1099
    def enable_directory_isolation(self):
 
1100
        """Enable directory isolation checks."""
 
1101
        self._directory_isolation = True
 
1102
 
 
1103
    def _silenceUI(self):
 
1104
        """Turn off UI for duration of test"""
 
1105
        # by default the UI is off; tests can turn it on if they want it.
 
1106
        self.overrideAttr(ui, 'ui_factory', ui.SilentUIFactory())
 
1107
 
 
1108
    def _check_locks(self):
 
1109
        """Check that all lock take/release actions have been paired."""
 
1110
        # We always check for mismatched locks. If a mismatch is found, we
 
1111
        # fail unless -Edisable_lock_checks is supplied to selftest, in which
 
1112
        # case we just print a warning.
 
1113
        # unhook:
 
1114
        acquired_locks = [lock for action, lock in self._lock_actions
 
1115
                          if action == 'acquired']
 
1116
        released_locks = [lock for action, lock in self._lock_actions
 
1117
                          if action == 'released']
 
1118
        broken_locks = [lock for action, lock in self._lock_actions
 
1119
                        if action == 'broken']
 
1120
        # trivially, given the tests for lock acquistion and release, if we
 
1121
        # have as many in each list, it should be ok. Some lock tests also
 
1122
        # break some locks on purpose and should be taken into account by
 
1123
        # considering that breaking a lock is just a dirty way of releasing it.
 
1124
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
 
1125
            message = (
 
1126
                'Different number of acquired and '
 
1127
                'released or broken locks.\n'
 
1128
                'acquired=%s\n'
 
1129
                'released=%s\n'
 
1130
                'broken=%s\n' %
 
1131
                (acquired_locks, released_locks, broken_locks))
 
1132
            if not self._lock_check_thorough:
 
1133
                # Rather than fail, just warn
 
1134
                print("Broken test %s: %s" % (self, message))
 
1135
                return
 
1136
            self.fail(message)
 
1137
 
 
1138
    def _track_locks(self):
 
1139
        """Track lock activity during tests."""
 
1140
        self._lock_actions = []
 
1141
        if 'disable_lock_checks' in selftest_debug_flags:
 
1142
            self._lock_check_thorough = False
 
1143
        else:
 
1144
            self._lock_check_thorough = True
 
1145
 
 
1146
        self.addCleanup(self._check_locks)
 
1147
        _mod_lock.Lock.hooks.install_named_hook('lock_acquired',
 
1148
                                                self._lock_acquired, None)
 
1149
        _mod_lock.Lock.hooks.install_named_hook('lock_released',
 
1150
                                                self._lock_released, None)
 
1151
        _mod_lock.Lock.hooks.install_named_hook('lock_broken',
 
1152
                                                self._lock_broken, None)
 
1153
 
 
1154
    def _lock_acquired(self, result):
 
1155
        self._lock_actions.append(('acquired', result))
 
1156
 
 
1157
    def _lock_released(self, result):
 
1158
        self._lock_actions.append(('released', result))
 
1159
 
 
1160
    def _lock_broken(self, result):
 
1161
        self._lock_actions.append(('broken', result))
 
1162
 
 
1163
    def permit_dir(self, name):
 
1164
        """Permit a directory to be used by this test. See permit_url."""
 
1165
        name_transport = _mod_transport.get_transport_from_path(name)
 
1166
        self.permit_url(name)
 
1167
        self.permit_url(name_transport.base)
 
1168
 
 
1169
    def permit_url(self, url):
 
1170
        """Declare that url is an ok url to use in this test.
 
1171
 
 
1172
        Do this for memory transports, temporary test directory etc.
 
1173
 
 
1174
        Do not do this for the current working directory, /tmp, or any other
 
1175
        preexisting non isolated url.
 
1176
        """
 
1177
        if not url.endswith('/'):
 
1178
            url += '/'
 
1179
        self._bzr_selftest_roots.append(url)
 
1180
 
 
1181
    def permit_source_tree_branch_repo(self):
 
1182
        """Permit the source tree brz is running from to be opened.
 
1183
 
 
1184
        Some code such as breezy.version attempts to read from the brz branch
 
1185
        that brz is executing from (if any). This method permits that directory
 
1186
        to be used in the test suite.
 
1187
        """
 
1188
        path = self.get_source_path()
 
1189
        self.record_directory_isolation()
 
1190
        try:
 
1191
            try:
 
1192
                workingtree.WorkingTree.open(path)
 
1193
            except (errors.NotBranchError, errors.NoWorkingTree):
 
1194
                raise TestSkipped('Needs a working tree of brz sources')
 
1195
        finally:
 
1196
            self.enable_directory_isolation()
 
1197
 
 
1198
    def _preopen_isolate_transport(self, transport):
 
1199
        """Check that all transport openings are done in the test work area."""
 
1200
        while isinstance(transport, pathfilter.PathFilteringTransport):
 
1201
            # Unwrap pathfiltered transports
 
1202
            transport = transport.server.backing_transport.clone(
 
1203
                transport._filter('.'))
 
1204
        url = transport.base
 
1205
        # ReadonlySmartTCPServer_for_testing decorates the backing transport
 
1206
        # urls it is given by prepending readonly+. This is appropriate as the
 
1207
        # client shouldn't know that the server is readonly (or not readonly).
 
1208
        # We could register all servers twice, with readonly+ prepending, but
 
1209
        # that makes for a long list; this is about the same but easier to
 
1210
        # read.
 
1211
        if url.startswith('readonly+'):
 
1212
            url = url[len('readonly+'):]
 
1213
        self._preopen_isolate_url(url)
 
1214
 
 
1215
    def _preopen_isolate_url(self, url):
 
1216
        if not self._directory_isolation:
 
1217
            return
 
1218
        if self._directory_isolation == 'record':
 
1219
            self._bzr_selftest_roots.append(url)
 
1220
            return
 
1221
        # This prevents all transports, including e.g. sftp ones backed on disk
 
1222
        # from working unless they are explicitly granted permission. We then
 
1223
        # depend on the code that sets up test transports to check that they are
 
1224
        # appropriately isolated and enable their use by calling
 
1225
        # self.permit_transport()
 
1226
        if not osutils.is_inside_any(self._bzr_selftest_roots, url):
 
1227
            raise errors.BzrError("Attempt to escape test isolation: %r %r"
 
1228
                % (url, self._bzr_selftest_roots))
 
1229
 
 
1230
    def record_directory_isolation(self):
 
1231
        """Gather accessed directories to permit later access.
 
1232
 
 
1233
        This is used for tests that access the branch brz is running from.
 
1234
        """
 
1235
        self._directory_isolation = "record"
 
1236
 
 
1237
    def start_server(self, transport_server, backing_server=None):
 
1238
        """Start transport_server for this test.
 
1239
 
 
1240
        This starts the server, registers a cleanup for it and permits the
 
1241
        server's urls to be used.
 
1242
        """
 
1243
        if backing_server is None:
 
1244
            transport_server.start_server()
 
1245
        else:
 
1246
            transport_server.start_server(backing_server)
 
1247
        self.addCleanup(transport_server.stop_server)
 
1248
        # Obtain a real transport because if the server supplies a password, it
 
1249
        # will be hidden from the base on the client side.
 
1250
        t = _mod_transport.get_transport_from_url(transport_server.get_url())
 
1251
        # Some transport servers effectively chroot the backing transport;
 
1252
        # others like SFTPServer don't - users of the transport can walk up the
 
1253
        # transport to read the entire backing transport. This wouldn't matter
 
1254
        # except that the workdir tests are given - and that they expect the
 
1255
        # server's url to point at - is one directory under the safety net. So
 
1256
        # Branch operations into the transport will attempt to walk up one
 
1257
        # directory. Chrooting all servers would avoid this but also mean that
 
1258
        # we wouldn't be testing directly against non-root urls. Alternatively
 
1259
        # getting the test framework to start the server with a backing server
 
1260
        # at the actual safety net directory would work too, but this then
 
1261
        # means that the self.get_url/self.get_transport methods would need
 
1262
        # to transform all their results. On balance its cleaner to handle it
 
1263
        # here, and permit a higher url when we have one of these transports.
 
1264
        if t.base.endswith('/work/'):
 
1265
            # we have safety net/test root/work
 
1266
            t = t.clone('../..')
 
1267
        elif isinstance(transport_server,
 
1268
                        test_server.SmartTCPServer_for_testing):
 
1269
            # The smart server adds a path similar to work, which is traversed
 
1270
            # up from by the client. But the server is chrooted - the actual
 
1271
            # backing transport is not escaped from, and VFS requests to the
 
1272
            # root will error (because they try to escape the chroot).
 
1273
            t2 = t.clone('..')
 
1274
            while t2.base != t.base:
 
1275
                t = t2
 
1276
                t2 = t.clone('..')
 
1277
        self.permit_url(t.base)
 
1278
 
 
1279
    def _track_transports(self):
 
1280
        """Install checks for transport usage."""
 
1281
        # TestCase has no safe place it can write to.
 
1282
        self._bzr_selftest_roots = []
 
1283
        # Currently the easiest way to be sure that nothing is going on is to
 
1284
        # hook into brz dir opening. This leaves a small window of error for
 
1285
        # transport tests, but they are well known, and we can improve on this
 
1286
        # step.
 
1287
        controldir.ControlDir.hooks.install_named_hook("pre_open",
 
1288
            self._preopen_isolate_transport, "Check brz directories are safe.")
 
1289
 
 
1290
    def _ndiff_strings(self, a, b):
 
1291
        """Return ndiff between two strings containing lines.
 
1292
 
 
1293
        A trailing newline is added if missing to make the strings
 
1294
        print properly."""
 
1295
        if b and b[-1] != '\n':
 
1296
            b += '\n'
 
1297
        if a and a[-1] != '\n':
 
1298
            a += '\n'
 
1299
        difflines = difflib.ndiff(a.splitlines(True),
 
1300
                                  b.splitlines(True),
 
1301
                                  linejunk=lambda x: False,
 
1302
                                  charjunk=lambda x: False)
 
1303
        return ''.join(difflines)
 
1304
 
 
1305
    def assertEqual(self, a, b, message=''):
 
1306
        try:
 
1307
            if a == b:
 
1308
                return
 
1309
        except UnicodeError as e:
 
1310
            # If we can't compare without getting a UnicodeError, then
 
1311
            # obviously they are different
 
1312
            trace.mutter('UnicodeError: %s', e)
 
1313
        if message:
 
1314
            message += '\n'
 
1315
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
 
1316
            % (message,
 
1317
               pprint.pformat(a), pprint.pformat(b)))
 
1318
 
 
1319
    # FIXME: This is deprecated in unittest2 but plugins may still use it so we
 
1320
    # need a deprecation period for them -- vila 2016-02-01
 
1321
    assertEquals = assertEqual
 
1322
 
 
1323
    def assertEqualDiff(self, a, b, message=None):
 
1324
        """Assert two texts are equal, if not raise an exception.
 
1325
 
 
1326
        This is intended for use with multi-line strings where it can
 
1327
        be hard to find the differences by eye.
 
1328
        """
 
1329
        # TODO: perhaps override assertEqual to call this for strings?
 
1330
        if a == b:
 
1331
            return
 
1332
        if message is None:
 
1333
            message = "texts not equal:\n"
 
1334
        if a + '\n' == b:
 
1335
            message = 'first string is missing a final newline.\n'
 
1336
        if a == b + '\n':
 
1337
            message = 'second string is missing a final newline.\n'
 
1338
        raise AssertionError(message +
 
1339
                             self._ndiff_strings(a, b))
 
1340
 
 
1341
    def assertEqualMode(self, mode, mode_test):
 
1342
        self.assertEqual(mode, mode_test,
 
1343
                         'mode mismatch %o != %o' % (mode, mode_test))
 
1344
 
 
1345
    def assertEqualStat(self, expected, actual):
 
1346
        """assert that expected and actual are the same stat result.
 
1347
 
 
1348
        :param expected: A stat result.
 
1349
        :param actual: A stat result.
 
1350
        :raises AssertionError: If the expected and actual stat values differ
 
1351
            other than by atime.
 
1352
        """
 
1353
        self.assertEqual(expected.st_size, actual.st_size,
 
1354
                         'st_size did not match')
 
1355
        self.assertEqual(expected.st_mtime, actual.st_mtime,
 
1356
                         'st_mtime did not match')
 
1357
        self.assertEqual(expected.st_ctime, actual.st_ctime,
 
1358
                         'st_ctime did not match')
 
1359
        if sys.platform == 'win32':
 
1360
            # On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
 
1361
            # is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
 
1362
            # odd. We just force it to always be 0 to avoid any problems.
 
1363
            self.assertEqual(0, expected.st_dev)
 
1364
            self.assertEqual(0, actual.st_dev)
 
1365
            self.assertEqual(0, expected.st_ino)
 
1366
            self.assertEqual(0, actual.st_ino)
 
1367
        else:
 
1368
            self.assertEqual(expected.st_dev, actual.st_dev,
 
1369
                             'st_dev did not match')
 
1370
            self.assertEqual(expected.st_ino, actual.st_ino,
 
1371
                             'st_ino did not match')
 
1372
        self.assertEqual(expected.st_mode, actual.st_mode,
 
1373
                         'st_mode did not match')
 
1374
 
 
1375
    def assertLength(self, length, obj_with_len):
 
1376
        """Assert that obj_with_len is of length length."""
 
1377
        if len(obj_with_len) != length:
 
1378
            self.fail("Incorrect length: wanted %d, got %d for %r" % (
 
1379
                length, len(obj_with_len), obj_with_len))
 
1380
 
 
1381
    def assertLogsError(self, exception_class, func, *args, **kwargs):
 
1382
        """Assert that `func(*args, **kwargs)` quietly logs a specific error.
 
1383
        """
 
1384
        captured = []
 
1385
        orig_log_exception_quietly = trace.log_exception_quietly
 
1386
        try:
 
1387
            def capture():
 
1388
                orig_log_exception_quietly()
 
1389
                captured.append(sys.exc_info()[1])
 
1390
            trace.log_exception_quietly = capture
 
1391
            func(*args, **kwargs)
 
1392
        finally:
 
1393
            trace.log_exception_quietly = orig_log_exception_quietly
 
1394
        self.assertLength(1, captured)
 
1395
        err = captured[0]
 
1396
        self.assertIsInstance(err, exception_class)
 
1397
        return err
 
1398
 
 
1399
    def assertPositive(self, val):
 
1400
        """Assert that val is greater than 0."""
 
1401
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
 
1402
 
 
1403
    def assertNegative(self, val):
 
1404
        """Assert that val is less than 0."""
 
1405
        self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
 
1406
 
 
1407
    def assertStartsWith(self, s, prefix):
 
1408
        if not s.startswith(prefix):
 
1409
            raise AssertionError('string %r does not start with %r' % (s, prefix))
 
1410
 
 
1411
    def assertEndsWith(self, s, suffix):
 
1412
        """Asserts that s ends with suffix."""
 
1413
        if not s.endswith(suffix):
 
1414
            raise AssertionError('string %r does not end with %r' % (s, suffix))
 
1415
 
 
1416
    def assertContainsRe(self, haystack, needle_re, flags=0):
 
1417
        """Assert that a contains something matching a regular expression."""
 
1418
        if not re.search(needle_re, haystack, flags):
 
1419
            if '\n' in haystack or len(haystack) > 60:
 
1420
                # a long string, format it in a more readable way
 
1421
                raise AssertionError(
 
1422
                        'pattern "%s" not found in\n"""\\\n%s"""\n'
 
1423
                        % (needle_re, haystack))
 
1424
            else:
 
1425
                raise AssertionError('pattern "%s" not found in "%s"'
 
1426
                        % (needle_re, haystack))
 
1427
 
 
1428
    def assertNotContainsRe(self, haystack, needle_re, flags=0):
 
1429
        """Assert that a does not match a regular expression"""
 
1430
        if re.search(needle_re, haystack, flags):
 
1431
            raise AssertionError('pattern "%s" found in "%s"'
 
1432
                    % (needle_re, haystack))
 
1433
 
 
1434
    def assertContainsString(self, haystack, needle):
 
1435
        if haystack.find(needle) == -1:
 
1436
            self.fail("string %r not found in '''%s'''" % (needle, haystack))
 
1437
 
 
1438
    def assertNotContainsString(self, haystack, needle):
 
1439
        if haystack.find(needle) != -1:
 
1440
            self.fail("string %r found in '''%s'''" % (needle, haystack))
 
1441
 
 
1442
    def assertSubset(self, sublist, superlist):
 
1443
        """Assert that every entry in sublist is present in superlist."""
 
1444
        missing = set(sublist) - set(superlist)
 
1445
        if len(missing) > 0:
 
1446
            raise AssertionError("value(s) %r not present in container %r" %
 
1447
                                 (missing, superlist))
 
1448
 
 
1449
    def assertListRaises(self, excClass, func, *args, **kwargs):
 
1450
        """Fail unless excClass is raised when the iterator from func is used.
 
1451
 
 
1452
        Many functions can return generators this makes sure
 
1453
        to wrap them in a list() call to make sure the whole generator
 
1454
        is run, and that the proper exception is raised.
 
1455
        """
 
1456
        try:
 
1457
            list(func(*args, **kwargs))
 
1458
        except excClass as e:
 
1459
            return e
 
1460
        else:
 
1461
            if getattr(excClass,'__name__', None) is not None:
 
1462
                excName = excClass.__name__
 
1463
            else:
 
1464
                excName = str(excClass)
 
1465
            raise self.failureException("%s not raised" % excName)
 
1466
 
 
1467
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
 
1468
        """Assert that a callable raises a particular exception.
 
1469
 
 
1470
        :param excClass: As for the except statement, this may be either an
 
1471
            exception class, or a tuple of classes.
 
1472
        :param callableObj: A callable, will be passed ``*args`` and
 
1473
            ``**kwargs``.
 
1474
 
 
1475
        Returns the exception so that you can examine it.
 
1476
        """
 
1477
        try:
 
1478
            callableObj(*args, **kwargs)
 
1479
        except excClass as e:
 
1480
            return e
 
1481
        else:
 
1482
            if getattr(excClass,'__name__', None) is not None:
 
1483
                excName = excClass.__name__
 
1484
            else:
 
1485
                # probably a tuple
 
1486
                excName = str(excClass)
 
1487
            raise self.failureException("%s not raised" % excName)
 
1488
 
 
1489
    def assertIs(self, left, right, message=None):
 
1490
        if not (left is right):
 
1491
            if message is not None:
 
1492
                raise AssertionError(message)
 
1493
            else:
 
1494
                raise AssertionError("%r is not %r." % (left, right))
 
1495
 
 
1496
    def assertIsNot(self, left, right, message=None):
 
1497
        if (left is right):
 
1498
            if message is not None:
 
1499
                raise AssertionError(message)
 
1500
            else:
 
1501
                raise AssertionError("%r is %r." % (left, right))
 
1502
 
 
1503
    def assertTransportMode(self, transport, path, mode):
 
1504
        """Fail if a path does not have mode "mode".
 
1505
 
 
1506
        If modes are not supported on this transport, the assertion is ignored.
 
1507
        """
 
1508
        if not transport._can_roundtrip_unix_modebits():
 
1509
            return
 
1510
        path_stat = transport.stat(path)
 
1511
        actual_mode = stat.S_IMODE(path_stat.st_mode)
 
1512
        self.assertEqual(mode, actual_mode,
 
1513
                         'mode of %r incorrect (%s != %s)'
 
1514
                         % (path, oct(mode), oct(actual_mode)))
 
1515
 
 
1516
    def assertIsSameRealPath(self, path1, path2):
 
1517
        """Fail if path1 and path2 points to different files"""
 
1518
        self.assertEqual(osutils.realpath(path1),
 
1519
                         osutils.realpath(path2),
 
1520
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
 
1521
 
 
1522
    def assertIsInstance(self, obj, kls, msg=None):
 
1523
        """Fail if obj is not an instance of kls
 
1524
        
 
1525
        :param msg: Supplementary message to show if the assertion fails.
 
1526
        """
 
1527
        if not isinstance(obj, kls):
 
1528
            m = "%r is an instance of %s rather than %s" % (
 
1529
                obj, obj.__class__, kls)
 
1530
            if msg:
 
1531
                m += ": " + msg
 
1532
            self.fail(m)
 
1533
 
 
1534
    def assertFileEqual(self, content, path):
 
1535
        """Fail if path does not contain 'content'."""
 
1536
        self.assertPathExists(path)
 
1537
        f = file(path, 'rb')
 
1538
        try:
 
1539
            s = f.read()
 
1540
        finally:
 
1541
            f.close()
 
1542
        self.assertEqualDiff(content, s)
 
1543
 
 
1544
    def assertDocstring(self, expected_docstring, obj):
 
1545
        """Fail if obj does not have expected_docstring"""
 
1546
        if __doc__ is None:
 
1547
            # With -OO the docstring should be None instead
 
1548
            self.assertIs(obj.__doc__, None)
 
1549
        else:
 
1550
            self.assertEqual(expected_docstring, obj.__doc__)
 
1551
 
 
1552
    def assertPathExists(self, path):
 
1553
        """Fail unless path or paths, which may be abs or relative, exist."""
 
1554
        if not isinstance(path, basestring):
 
1555
            for p in path:
 
1556
                self.assertPathExists(p)
 
1557
        else:
 
1558
            self.assertTrue(osutils.lexists(path),
 
1559
                path + " does not exist")
 
1560
 
 
1561
    def assertPathDoesNotExist(self, path):
 
1562
        """Fail if path or paths, which may be abs or relative, exist."""
 
1563
        if not isinstance(path, basestring):
 
1564
            for p in path:
 
1565
                self.assertPathDoesNotExist(p)
 
1566
        else:
 
1567
            self.assertFalse(osutils.lexists(path),
 
1568
                path + " exists")
 
1569
 
 
1570
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
 
1571
        """A helper for callDeprecated and applyDeprecated.
 
1572
 
 
1573
        :param a_callable: A callable to call.
 
1574
        :param args: The positional arguments for the callable
 
1575
        :param kwargs: The keyword arguments for the callable
 
1576
        :return: A tuple (warnings, result). result is the result of calling
 
1577
            a_callable(``*args``, ``**kwargs``).
 
1578
        """
 
1579
        local_warnings = []
 
1580
        def capture_warnings(msg, cls=None, stacklevel=None):
 
1581
            # we've hooked into a deprecation specific callpath,
 
1582
            # only deprecations should getting sent via it.
 
1583
            self.assertEqual(cls, DeprecationWarning)
 
1584
            local_warnings.append(msg)
 
1585
        original_warning_method = symbol_versioning.warn
 
1586
        symbol_versioning.set_warning_method(capture_warnings)
 
1587
        try:
 
1588
            result = a_callable(*args, **kwargs)
 
1589
        finally:
 
1590
            symbol_versioning.set_warning_method(original_warning_method)
 
1591
        return (local_warnings, result)
 
1592
 
 
1593
    def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
 
1594
        """Call a deprecated callable without warning the user.
 
1595
 
 
1596
        Note that this only captures warnings raised by symbol_versioning.warn,
 
1597
        not other callers that go direct to the warning module.
 
1598
 
 
1599
        To test that a deprecated method raises an error, do something like
 
1600
        this (remember that both assertRaises and applyDeprecated delays *args
 
1601
        and **kwargs passing)::
 
1602
 
 
1603
            self.assertRaises(errors.ReservedId,
 
1604
                self.applyDeprecated,
 
1605
                deprecated_in((1, 5, 0)),
 
1606
                br.append_revision,
 
1607
                'current:')
 
1608
 
 
1609
        :param deprecation_format: The deprecation format that the callable
 
1610
            should have been deprecated with. This is the same type as the
 
1611
            parameter to deprecated_method/deprecated_function. If the
 
1612
            callable is not deprecated with this format, an assertion error
 
1613
            will be raised.
 
1614
        :param a_callable: A callable to call. This may be a bound method or
 
1615
            a regular function. It will be called with ``*args`` and
 
1616
            ``**kwargs``.
 
1617
        :param args: The positional arguments for the callable
 
1618
        :param kwargs: The keyword arguments for the callable
 
1619
        :return: The result of a_callable(``*args``, ``**kwargs``)
 
1620
        """
 
1621
        call_warnings, result = self._capture_deprecation_warnings(a_callable,
 
1622
            *args, **kwargs)
 
1623
        expected_first_warning = symbol_versioning.deprecation_string(
 
1624
            a_callable, deprecation_format)
 
1625
        if len(call_warnings) == 0:
 
1626
            self.fail("No deprecation warning generated by call to %s" %
 
1627
                a_callable)
 
1628
        self.assertEqual(expected_first_warning, call_warnings[0])
 
1629
        return result
 
1630
 
 
1631
    def callCatchWarnings(self, fn, *args, **kw):
 
1632
        """Call a callable that raises python warnings.
 
1633
 
 
1634
        The caller's responsible for examining the returned warnings.
 
1635
 
 
1636
        If the callable raises an exception, the exception is not
 
1637
        caught and propagates up to the caller.  In that case, the list
 
1638
        of warnings is not available.
 
1639
 
 
1640
        :returns: ([warning_object, ...], fn_result)
 
1641
        """
 
1642
        # XXX: This is not perfect, because it completely overrides the
 
1643
        # warnings filters, and some code may depend on suppressing particular
 
1644
        # warnings.  It's the easiest way to insulate ourselves from -Werror,
 
1645
        # though.  -- Andrew, 20071062
 
1646
        wlist = []
 
1647
        def _catcher(message, category, filename, lineno, file=None, line=None):
 
1648
            # despite the name, 'message' is normally(?) a Warning subclass
 
1649
            # instance
 
1650
            wlist.append(message)
 
1651
        saved_showwarning = warnings.showwarning
 
1652
        saved_filters = warnings.filters
 
1653
        try:
 
1654
            warnings.showwarning = _catcher
 
1655
            warnings.filters = []
 
1656
            result = fn(*args, **kw)
 
1657
        finally:
 
1658
            warnings.showwarning = saved_showwarning
 
1659
            warnings.filters = saved_filters
 
1660
        return wlist, result
 
1661
 
 
1662
    def callDeprecated(self, expected, callable, *args, **kwargs):
 
1663
        """Assert that a callable is deprecated in a particular way.
 
1664
 
 
1665
        This is a very precise test for unusual requirements. The
 
1666
        applyDeprecated helper function is probably more suited for most tests
 
1667
        as it allows you to simply specify the deprecation format being used
 
1668
        and will ensure that that is issued for the function being called.
 
1669
 
 
1670
        Note that this only captures warnings raised by symbol_versioning.warn,
 
1671
        not other callers that go direct to the warning module.  To catch
 
1672
        general warnings, use callCatchWarnings.
 
1673
 
 
1674
        :param expected: a list of the deprecation warnings expected, in order
 
1675
        :param callable: The callable to call
 
1676
        :param args: The positional arguments for the callable
 
1677
        :param kwargs: The keyword arguments for the callable
 
1678
        """
 
1679
        call_warnings, result = self._capture_deprecation_warnings(callable,
 
1680
            *args, **kwargs)
 
1681
        self.assertEqual(expected, call_warnings)
 
1682
        return result
 
1683
 
 
1684
    def _startLogFile(self):
 
1685
        """Setup a in-memory target for bzr and testcase log messages"""
 
1686
        pseudo_log_file = BytesIO()
 
1687
        def _get_log_contents_for_weird_testtools_api():
 
1688
            return [pseudo_log_file.getvalue().decode(
 
1689
                "utf-8", "replace").encode("utf-8")]
 
1690
        self.addDetail("log", content.Content(content.ContentType("text",
 
1691
            "plain", {"charset": "utf8"}),
 
1692
            _get_log_contents_for_weird_testtools_api))
 
1693
        self._log_file = pseudo_log_file
 
1694
        self._log_memento = trace.push_log_file(self._log_file)
 
1695
        self.addCleanup(self._finishLogFile)
 
1696
 
 
1697
    def _finishLogFile(self):
 
1698
        """Flush and dereference the in-memory log for this testcase"""
 
1699
        if trace._trace_file:
 
1700
            # flush the log file, to get all content
 
1701
            trace._trace_file.flush()
 
1702
        trace.pop_log_file(self._log_memento)
 
1703
        # The logging module now tracks references for cleanup so discard ours
 
1704
        del self._log_memento
 
1705
 
 
1706
    def thisFailsStrictLockCheck(self):
 
1707
        """It is known that this test would fail with -Dstrict_locks.
 
1708
 
 
1709
        By default, all tests are run with strict lock checking unless
 
1710
        -Edisable_lock_checks is supplied. However there are some tests which
 
1711
        we know fail strict locks at this point that have not been fixed.
 
1712
        They should call this function to disable the strict checking.
 
1713
 
 
1714
        This should be used sparingly, it is much better to fix the locking
 
1715
        issues rather than papering over the problem by calling this function.
 
1716
        """
 
1717
        debug.debug_flags.discard('strict_locks')
 
1718
 
 
1719
    def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
 
1720
        """Overrides an object attribute restoring it after the test.
 
1721
 
 
1722
        :note: This should be used with discretion; you should think about
 
1723
        whether it's better to make the code testable without monkey-patching.
 
1724
 
 
1725
        :param obj: The object that will be mutated.
 
1726
 
 
1727
        :param attr_name: The attribute name we want to preserve/override in
 
1728
            the object.
 
1729
 
 
1730
        :param new: The optional value we want to set the attribute to.
 
1731
 
 
1732
        :returns: The actual attr value.
 
1733
        """
 
1734
        # The actual value is captured by the call below
 
1735
        value = getattr(obj, attr_name, _unitialized_attr)
 
1736
        if value is _unitialized_attr:
 
1737
            # When the test completes, the attribute should not exist, but if
 
1738
            # we aren't setting a value, we don't need to do anything.
 
1739
            if new is not _unitialized_attr:
 
1740
                self.addCleanup(delattr, obj, attr_name)
 
1741
        else:
 
1742
            self.addCleanup(setattr, obj, attr_name, value)
 
1743
        if new is not _unitialized_attr:
 
1744
            setattr(obj, attr_name, new)
 
1745
        return value
 
1746
 
 
1747
    def overrideEnv(self, name, new):
 
1748
        """Set an environment variable, and reset it after the test.
 
1749
 
 
1750
        :param name: The environment variable name.
 
1751
 
 
1752
        :param new: The value to set the variable to. If None, the 
 
1753
            variable is deleted from the environment.
 
1754
 
 
1755
        :returns: The actual variable value.
 
1756
        """
 
1757
        value = osutils.set_or_unset_env(name, new)
 
1758
        self.addCleanup(osutils.set_or_unset_env, name, value)
 
1759
        return value
 
1760
 
 
1761
    def recordCalls(self, obj, attr_name):
 
1762
        """Monkeypatch in a wrapper that will record calls.
 
1763
 
 
1764
        The monkeypatch is automatically removed when the test concludes.
 
1765
 
 
1766
        :param obj: The namespace holding the reference to be replaced;
 
1767
            typically a module, class, or object.
 
1768
        :param attr_name: A string for the name of the attribute to 
 
1769
            patch.
 
1770
        :returns: A list that will be extended with one item every time the
 
1771
            function is called, with a tuple of (args, kwargs).
 
1772
        """
 
1773
        calls = []
 
1774
 
 
1775
        def decorator(*args, **kwargs):
 
1776
            calls.append((args, kwargs))
 
1777
            return orig(*args, **kwargs)
 
1778
        orig = self.overrideAttr(obj, attr_name, decorator)
 
1779
        return calls
 
1780
 
 
1781
    def _cleanEnvironment(self):
 
1782
        for name, value in isolated_environ.items():
 
1783
            self.overrideEnv(name, value)
 
1784
 
 
1785
    def _restoreHooks(self):
 
1786
        for klass, (name, hooks) in self._preserved_hooks.items():
 
1787
            setattr(klass, name, hooks)
 
1788
        self._preserved_hooks.clear()
 
1789
        breezy.hooks._lazy_hooks = self._preserved_lazy_hooks
 
1790
        self._preserved_lazy_hooks.clear()
 
1791
 
 
1792
    def knownFailure(self, reason):
 
1793
        """Declare that this test fails for a known reason
 
1794
 
 
1795
        Tests that are known to fail should generally be using expectedFailure
 
1796
        with an appropriate reverse assertion if a change could cause the test
 
1797
        to start passing. Conversely if the test has no immediate prospect of
 
1798
        succeeding then using skip is more suitable.
 
1799
 
 
1800
        When this method is called while an exception is being handled, that
 
1801
        traceback will be used, otherwise a new exception will be thrown to
 
1802
        provide one but won't be reported.
 
1803
        """
 
1804
        self._add_reason(reason)
 
1805
        try:
 
1806
            exc_info = sys.exc_info()
 
1807
            if exc_info != (None, None, None):
 
1808
                self._report_traceback(exc_info)
 
1809
            else:
 
1810
                try:
 
1811
                    raise self.failureException(reason)
 
1812
                except self.failureException:
 
1813
                    exc_info = sys.exc_info()
 
1814
            # GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
 
1815
            raise testtools.testcase._ExpectedFailure(exc_info)
 
1816
        finally:
 
1817
            del exc_info
 
1818
 
 
1819
    def _suppress_log(self):
 
1820
        """Remove the log info from details."""
 
1821
        self.discardDetail('log')
 
1822
 
 
1823
    def _do_skip(self, result, reason):
 
1824
        self._suppress_log()
 
1825
        addSkip = getattr(result, 'addSkip', None)
 
1826
        if not callable(addSkip):
 
1827
            result.addSuccess(result)
 
1828
        else:
 
1829
            addSkip(self, reason)
 
1830
 
 
1831
    @staticmethod
 
1832
    def _do_known_failure(self, result, e):
 
1833
        self._suppress_log()
 
1834
        err = sys.exc_info()
 
1835
        addExpectedFailure = getattr(result, 'addExpectedFailure', None)
 
1836
        if addExpectedFailure is not None:
 
1837
            addExpectedFailure(self, err)
 
1838
        else:
 
1839
            result.addSuccess(self)
 
1840
 
 
1841
    @staticmethod
 
1842
    def _do_not_applicable(self, result, e):
 
1843
        if not e.args:
 
1844
            reason = 'No reason given'
 
1845
        else:
 
1846
            reason = e.args[0]
 
1847
        self._suppress_log ()
 
1848
        addNotApplicable = getattr(result, 'addNotApplicable', None)
 
1849
        if addNotApplicable is not None:
 
1850
            result.addNotApplicable(self, reason)
 
1851
        else:
 
1852
            self._do_skip(result, reason)
 
1853
 
 
1854
    @staticmethod
 
1855
    def _report_skip(self, result, err):
 
1856
        """Override the default _report_skip.
 
1857
 
 
1858
        We want to strip the 'log' detail. If we waint until _do_skip, it has
 
1859
        already been formatted into the 'reason' string, and we can't pull it
 
1860
        out again.
 
1861
        """
 
1862
        self._suppress_log()
 
1863
        super(TestCase, self)._report_skip(self, result, err)
 
1864
 
 
1865
    @staticmethod
 
1866
    def _report_expected_failure(self, result, err):
 
1867
        """Strip the log.
 
1868
 
 
1869
        See _report_skip for motivation.
 
1870
        """
 
1871
        self._suppress_log()
 
1872
        super(TestCase, self)._report_expected_failure(self, result, err)
 
1873
 
 
1874
    @staticmethod
 
1875
    def _do_unsupported_or_skip(self, result, e):
 
1876
        reason = e.args[0]
 
1877
        self._suppress_log()
 
1878
        addNotSupported = getattr(result, 'addNotSupported', None)
 
1879
        if addNotSupported is not None:
 
1880
            result.addNotSupported(self, reason)
 
1881
        else:
 
1882
            self._do_skip(result, reason)
 
1883
 
 
1884
    def time(self, callable, *args, **kwargs):
 
1885
        """Run callable and accrue the time it takes to the benchmark time.
 
1886
 
 
1887
        If lsprofiling is enabled (i.e. by --lsprof-time to brz selftest) then
 
1888
        this will cause lsprofile statistics to be gathered and stored in
 
1889
        self._benchcalls.
 
1890
        """
 
1891
        if self._benchtime is None:
 
1892
            self.addDetail('benchtime', content.Content(content.ContentType(
 
1893
                "text", "plain"), lambda:[str(self._benchtime)]))
 
1894
            self._benchtime = 0
 
1895
        start = time.time()
 
1896
        try:
 
1897
            if not self._gather_lsprof_in_benchmarks:
 
1898
                return callable(*args, **kwargs)
 
1899
            else:
 
1900
                # record this benchmark
 
1901
                ret, stats = breezy.lsprof.profile(callable, *args, **kwargs)
 
1902
                stats.sort()
 
1903
                self._benchcalls.append(((callable, args, kwargs), stats))
 
1904
                return ret
 
1905
        finally:
 
1906
            self._benchtime += time.time() - start
 
1907
 
 
1908
    def log(self, *args):
 
1909
        trace.mutter(*args)
 
1910
 
 
1911
    def get_log(self):
 
1912
        """Get a unicode string containing the log from breezy.trace.
 
1913
 
 
1914
        Undecodable characters are replaced.
 
1915
        """
 
1916
        return u"".join(self.getDetails()['log'].iter_text())
 
1917
 
 
1918
    def requireFeature(self, feature):
 
1919
        """This test requires a specific feature is available.
 
1920
 
 
1921
        :raises UnavailableFeature: When feature is not available.
 
1922
        """
 
1923
        if not feature.available():
 
1924
            raise UnavailableFeature(feature)
 
1925
 
 
1926
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
 
1927
            working_dir):
 
1928
        """Run bazaar command line, splitting up a string command line."""
 
1929
        if isinstance(args, string_types):
 
1930
            args = shlex.split(args)
 
1931
        return self._run_bzr_core(args, retcode=retcode,
 
1932
                encoding=encoding, stdin=stdin, working_dir=working_dir,
 
1933
                )
 
1934
 
 
1935
    def _run_bzr_core(self, args, retcode, encoding, stdin,
 
1936
            working_dir):
 
1937
        # Clear chk_map page cache, because the contents are likely to mask
 
1938
        # locking errors.
 
1939
        chk_map.clear_cache()
 
1940
        if encoding is None:
 
1941
            encoding = osutils.get_user_encoding()
 
1942
 
 
1943
        self.log('run brz: %r', args)
 
1944
 
 
1945
        stdout = ui_testing.BytesIOWithEncoding()
 
1946
        stderr = ui_testing.BytesIOWithEncoding()
 
1947
        stdout.encoding = stderr.encoding = encoding
 
1948
 
 
1949
        # FIXME: don't call into logging here
 
1950
        handler = trace.EncodedStreamHandler(
 
1951
            stderr, errors="replace", level=logging.INFO)
 
1952
        logger = logging.getLogger('')
 
1953
        logger.addHandler(handler)
 
1954
 
 
1955
        self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
 
1956
        self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
 
1957
 
 
1958
        old_ui_factory = ui.ui_factory
 
1959
        ui.ui_factory = ui_testing.TestUIFactory(
 
1960
            stdin=stdin,
 
1961
            stdout=self._last_cmd_stdout,
 
1962
            stderr=self._last_cmd_stderr)
 
1963
 
 
1964
        cwd = None
 
1965
        if working_dir is not None:
 
1966
            cwd = osutils.getcwd()
 
1967
            os.chdir(working_dir)
 
1968
 
 
1969
        try:
 
1970
            result = self.apply_redirected(
 
1971
                ui.ui_factory.stdin,
 
1972
                stdout, stderr,
 
1973
                _mod_commands.run_bzr_catch_user_errors,
 
1974
                args)
 
1975
        finally:
 
1976
            logger.removeHandler(handler)
 
1977
            ui.ui_factory = old_ui_factory
 
1978
            if cwd is not None:
 
1979
                os.chdir(cwd)
 
1980
 
 
1981
        out = stdout.getvalue()
 
1982
        err = stderr.getvalue()
 
1983
        if out:
 
1984
            self.log('output:\n%r', out)
 
1985
        if err:
 
1986
            self.log('errors:\n%r', err)
 
1987
        if retcode is not None:
 
1988
            self.assertEqual(retcode, result,
 
1989
                              message='Unexpected return code')
 
1990
        return result, out, err
 
1991
 
 
1992
    def run_bzr(self, args, retcode=0, stdin=None, encoding=None,
 
1993
                working_dir=None, error_regexes=[]):
 
1994
        """Invoke brz, as if it were run from the command line.
 
1995
 
 
1996
        The argument list should not include the brz program name - the
 
1997
        first argument is normally the brz command.  Arguments may be
 
1998
        passed in three ways:
 
1999
 
 
2000
        1- A list of strings, eg ["commit", "a"].  This is recommended
 
2001
        when the command contains whitespace or metacharacters, or
 
2002
        is built up at run time.
 
2003
 
 
2004
        2- A single string, eg "add a".  This is the most convenient
 
2005
        for hardcoded commands.
 
2006
 
 
2007
        This runs brz through the interface that catches and reports
 
2008
        errors, and with logging set to something approximating the
 
2009
        default, so that error reporting can be checked.
 
2010
 
 
2011
        This should be the main method for tests that want to exercise the
 
2012
        overall behavior of the brz application (rather than a unit test
 
2013
        or a functional test of the library.)
 
2014
 
 
2015
        This sends the stdout/stderr results into the test's log,
 
2016
        where it may be useful for debugging.  See also run_captured.
 
2017
 
 
2018
        :keyword stdin: A string to be used as stdin for the command.
 
2019
        :keyword retcode: The status code the command should return;
 
2020
            default 0.
 
2021
        :keyword working_dir: The directory to run the command in
 
2022
        :keyword error_regexes: A list of expected error messages.  If
 
2023
            specified they must be seen in the error output of the command.
 
2024
        """
 
2025
        retcode, out, err = self._run_bzr_autosplit(
 
2026
            args=args,
 
2027
            retcode=retcode,
 
2028
            encoding=encoding,
 
2029
            stdin=stdin,
 
2030
            working_dir=working_dir,
 
2031
            )
 
2032
        self.assertIsInstance(error_regexes, (list, tuple))
 
2033
        for regex in error_regexes:
 
2034
            self.assertContainsRe(err, regex)
 
2035
        return out, err
 
2036
 
 
2037
    def run_bzr_error(self, error_regexes, *args, **kwargs):
 
2038
        """Run brz, and check that stderr contains the supplied regexes
 
2039
 
 
2040
        :param error_regexes: Sequence of regular expressions which
 
2041
            must each be found in the error output. The relative ordering
 
2042
            is not enforced.
 
2043
        :param args: command-line arguments for brz
 
2044
        :param kwargs: Keyword arguments which are interpreted by run_brz
 
2045
            This function changes the default value of retcode to be 3,
 
2046
            since in most cases this is run when you expect brz to fail.
 
2047
 
 
2048
        :return: (out, err) The actual output of running the command (in case
 
2049
            you want to do more inspection)
 
2050
 
 
2051
        Examples of use::
 
2052
 
 
2053
            # Make sure that commit is failing because there is nothing to do
 
2054
            self.run_bzr_error(['no changes to commit'],
 
2055
                               ['commit', '-m', 'my commit comment'])
 
2056
            # Make sure --strict is handling an unknown file, rather than
 
2057
            # giving us the 'nothing to do' error
 
2058
            self.build_tree(['unknown'])
 
2059
            self.run_bzr_error(['Commit refused because there are unknown files'],
 
2060
                               ['commit', --strict', '-m', 'my commit comment'])
 
2061
        """
 
2062
        kwargs.setdefault('retcode', 3)
 
2063
        kwargs['error_regexes'] = error_regexes
 
2064
        out, err = self.run_bzr(*args, **kwargs)
 
2065
        return out, err
 
2066
 
 
2067
    def run_bzr_subprocess(self, *args, **kwargs):
 
2068
        """Run brz in a subprocess for testing.
 
2069
 
 
2070
        This starts a new Python interpreter and runs brz in there.
 
2071
        This should only be used for tests that have a justifiable need for
 
2072
        this isolation: e.g. they are testing startup time, or signal
 
2073
        handling, or early startup code, etc.  Subprocess code can't be
 
2074
        profiled or debugged so easily.
 
2075
 
 
2076
        :keyword retcode: The status code that is expected.  Defaults to 0.  If
 
2077
            None is supplied, the status code is not checked.
 
2078
        :keyword env_changes: A dictionary which lists changes to environment
 
2079
            variables. A value of None will unset the env variable.
 
2080
            The values must be strings. The change will only occur in the
 
2081
            child, so you don't need to fix the environment after running.
 
2082
        :keyword universal_newlines: Convert CRLF => LF
 
2083
        :keyword allow_plugins: By default the subprocess is run with
 
2084
            --no-plugins to ensure test reproducibility. Also, it is possible
 
2085
            for system-wide plugins to create unexpected output on stderr,
 
2086
            which can cause unnecessary test failures.
 
2087
        """
 
2088
        env_changes = kwargs.get('env_changes', {})
 
2089
        working_dir = kwargs.get('working_dir', None)
 
2090
        allow_plugins = kwargs.get('allow_plugins', False)
 
2091
        if len(args) == 1:
 
2092
            if isinstance(args[0], list):
 
2093
                args = args[0]
 
2094
            elif isinstance(args[0], basestring):
 
2095
                args = list(shlex.split(args[0]))
 
2096
        else:
 
2097
            raise ValueError("passing varargs to run_bzr_subprocess")
 
2098
        process = self.start_bzr_subprocess(args, env_changes=env_changes,
 
2099
                                            working_dir=working_dir,
 
2100
                                            allow_plugins=allow_plugins)
 
2101
        # We distinguish between retcode=None and retcode not passed.
 
2102
        supplied_retcode = kwargs.get('retcode', 0)
 
2103
        return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
 
2104
            universal_newlines=kwargs.get('universal_newlines', False),
 
2105
            process_args=args)
 
2106
 
 
2107
    def start_bzr_subprocess(self, process_args, env_changes=None,
 
2108
                             skip_if_plan_to_signal=False,
 
2109
                             working_dir=None,
 
2110
                             allow_plugins=False, stderr=subprocess.PIPE):
 
2111
        """Start brz in a subprocess for testing.
 
2112
 
 
2113
        This starts a new Python interpreter and runs brz in there.
 
2114
        This should only be used for tests that have a justifiable need for
 
2115
        this isolation: e.g. they are testing startup time, or signal
 
2116
        handling, or early startup code, etc.  Subprocess code can't be
 
2117
        profiled or debugged so easily.
 
2118
 
 
2119
        :param process_args: a list of arguments to pass to the brz executable,
 
2120
            for example ``['--version']``.
 
2121
        :param env_changes: A dictionary which lists changes to environment
 
2122
            variables. A value of None will unset the env variable.
 
2123
            The values must be strings. The change will only occur in the
 
2124
            child, so you don't need to fix the environment after running.
 
2125
        :param skip_if_plan_to_signal: raise TestSkipped when true and system
 
2126
            doesn't support signalling subprocesses.
 
2127
        :param allow_plugins: If False (default) pass --no-plugins to brz.
 
2128
        :param stderr: file to use for the subprocess's stderr.  Valid values
 
2129
            are those valid for the stderr argument of `subprocess.Popen`.
 
2130
            Default value is ``subprocess.PIPE``.
 
2131
 
 
2132
        :returns: Popen object for the started process.
 
2133
        """
 
2134
        if skip_if_plan_to_signal:
 
2135
            if os.name != "posix":
 
2136
                raise TestSkipped("Sending signals not supported")
 
2137
 
 
2138
        if env_changes is None:
 
2139
            env_changes = {}
 
2140
        # Because $HOME is set to a tempdir for the context of a test, modules
 
2141
        # installed in the user dir will not be found unless $PYTHONUSERBASE
 
2142
        # gets set to the computed directory of this parent process.
 
2143
        if site.USER_BASE is not None:
 
2144
            env_changes["PYTHONUSERBASE"] = site.USER_BASE
 
2145
        old_env = {}
 
2146
 
 
2147
        def cleanup_environment():
 
2148
            for env_var, value in env_changes.items():
 
2149
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
 
2150
 
 
2151
        def restore_environment():
 
2152
            for env_var, value in old_env.items():
 
2153
                osutils.set_or_unset_env(env_var, value)
 
2154
 
 
2155
        bzr_path = self.get_brz_path()
 
2156
 
 
2157
        cwd = None
 
2158
        if working_dir is not None:
 
2159
            cwd = osutils.getcwd()
 
2160
            os.chdir(working_dir)
 
2161
 
 
2162
        try:
 
2163
            # win32 subprocess doesn't support preexec_fn
 
2164
            # so we will avoid using it on all platforms, just to
 
2165
            # make sure the code path is used, and we don't break on win32
 
2166
            cleanup_environment()
 
2167
            # Include the subprocess's log file in the test details, in case
 
2168
            # the test fails due to an error in the subprocess.
 
2169
            self._add_subprocess_log(trace._get_brz_log_filename())
 
2170
            command = [sys.executable]
 
2171
            # frozen executables don't need the path to bzr
 
2172
            if getattr(sys, "frozen", None) is None:
 
2173
                command.append(bzr_path)
 
2174
            if not allow_plugins:
 
2175
                command.append('--no-plugins')
 
2176
            command.extend(process_args)
 
2177
            process = self._popen(command, stdin=subprocess.PIPE,
 
2178
                                  stdout=subprocess.PIPE,
 
2179
                                  stderr=stderr)
 
2180
        finally:
 
2181
            restore_environment()
 
2182
            if cwd is not None:
 
2183
                os.chdir(cwd)
 
2184
 
 
2185
        return process
 
2186
 
 
2187
    def _add_subprocess_log(self, log_file_path):
 
2188
        if len(self._log_files) == 0:
 
2189
            # Register an addCleanup func.  We do this on the first call to
 
2190
            # _add_subprocess_log rather than in TestCase.setUp so that this
 
2191
            # addCleanup is registered after any cleanups for tempdirs that
 
2192
            # subclasses might create, which will probably remove the log file
 
2193
            # we want to read.
 
2194
            self.addCleanup(self._subprocess_log_cleanup)
 
2195
        # self._log_files is a set, so if a log file is reused we won't grab it
 
2196
        # twice.
 
2197
        self._log_files.add(log_file_path)
 
2198
 
 
2199
    def _subprocess_log_cleanup(self):
 
2200
        for count, log_file_path in enumerate(self._log_files):
 
2201
            # We use buffer_now=True to avoid holding the file open beyond
 
2202
            # the life of this function, which might interfere with e.g.
 
2203
            # cleaning tempdirs on Windows.
 
2204
            # XXX: Testtools 0.9.5 doesn't have the content_from_file helper
 
2205
            #detail_content = content.content_from_file(
 
2206
            #    log_file_path, buffer_now=True)
 
2207
            with open(log_file_path, 'rb') as log_file:
 
2208
                log_file_bytes = log_file.read()
 
2209
            detail_content = content.Content(content.ContentType("text",
 
2210
                "plain", {"charset": "utf8"}), lambda: [log_file_bytes])
 
2211
            self.addDetail("start_bzr_subprocess-log-%d" % (count,),
 
2212
                detail_content)
 
2213
 
 
2214
    def _popen(self, *args, **kwargs):
 
2215
        """Place a call to Popen.
 
2216
 
 
2217
        Allows tests to override this method to intercept the calls made to
 
2218
        Popen for introspection.
 
2219
        """
 
2220
        return subprocess.Popen(*args, **kwargs)
 
2221
 
 
2222
    def get_source_path(self):
 
2223
        """Return the path of the directory containing breezy."""
 
2224
        return os.path.dirname(os.path.dirname(breezy.__file__))
 
2225
 
 
2226
    def get_brz_path(self):
 
2227
        """Return the path of the 'brz' executable for this test suite."""
 
2228
        brz_path = os.path.join(self.get_source_path(), "brz")
 
2229
        if not os.path.isfile(brz_path):
 
2230
            # We are probably installed. Assume sys.argv is the right file
 
2231
            brz_path = sys.argv[0]
 
2232
        return brz_path
 
2233
 
 
2234
    def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
 
2235
                              universal_newlines=False, process_args=None):
 
2236
        """Finish the execution of process.
 
2237
 
 
2238
        :param process: the Popen object returned from start_bzr_subprocess.
 
2239
        :param retcode: The status code that is expected.  Defaults to 0.  If
 
2240
            None is supplied, the status code is not checked.
 
2241
        :param send_signal: an optional signal to send to the process.
 
2242
        :param universal_newlines: Convert CRLF => LF
 
2243
        :returns: (stdout, stderr)
 
2244
        """
 
2245
        if send_signal is not None:
 
2246
            os.kill(process.pid, send_signal)
 
2247
        out, err = process.communicate()
 
2248
 
 
2249
        if universal_newlines:
 
2250
            out = out.replace('\r\n', '\n')
 
2251
            err = err.replace('\r\n', '\n')
 
2252
 
 
2253
        if retcode is not None and retcode != process.returncode:
 
2254
            if process_args is None:
 
2255
                process_args = "(unknown args)"
 
2256
            trace.mutter('Output of brz %s:\n%s', process_args, out)
 
2257
            trace.mutter('Error for brz %s:\n%s', process_args, err)
 
2258
            self.fail('Command brz %s failed with retcode %s != %s'
 
2259
                      % (process_args, retcode, process.returncode))
 
2260
        return [out, err]
 
2261
 
 
2262
    def check_tree_shape(self, tree, shape):
 
2263
        """Compare a tree to a list of expected names.
 
2264
 
 
2265
        Fail if they are not precisely equal.
 
2266
        """
 
2267
        extras = []
 
2268
        shape = list(shape)             # copy
 
2269
        for path, ie in tree.iter_entries_by_dir():
 
2270
            name = path.replace('\\', '/')
 
2271
            if ie.kind == 'directory':
 
2272
                name = name + '/'
 
2273
            if name == "/":
 
2274
                pass # ignore root entry
 
2275
            elif name in shape:
 
2276
                shape.remove(name)
 
2277
            else:
 
2278
                extras.append(name)
 
2279
        if shape:
 
2280
            self.fail("expected paths not found in inventory: %r" % shape)
 
2281
        if extras:
 
2282
            self.fail("unexpected paths found in inventory: %r" % extras)
 
2283
 
 
2284
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
2285
                         a_callable=None, *args, **kwargs):
 
2286
        """Call callable with redirected std io pipes.
 
2287
 
 
2288
        Returns the return code."""
 
2289
        if not callable(a_callable):
 
2290
            raise ValueError("a_callable must be callable.")
 
2291
        if stdin is None:
 
2292
            stdin = BytesIO("")
 
2293
        if stdout is None:
 
2294
            if getattr(self, "_log_file", None) is not None:
 
2295
                stdout = self._log_file
 
2296
            else:
 
2297
                stdout = BytesIO()
 
2298
        if stderr is None:
 
2299
            if getattr(self, "_log_file", None is not None):
 
2300
                stderr = self._log_file
 
2301
            else:
 
2302
                stderr = BytesIO()
 
2303
        real_stdin = sys.stdin
 
2304
        real_stdout = sys.stdout
 
2305
        real_stderr = sys.stderr
 
2306
        try:
 
2307
            sys.stdout = stdout
 
2308
            sys.stderr = stderr
 
2309
            sys.stdin = stdin
 
2310
            return a_callable(*args, **kwargs)
 
2311
        finally:
 
2312
            sys.stdout = real_stdout
 
2313
            sys.stderr = real_stderr
 
2314
            sys.stdin = real_stdin
 
2315
 
 
2316
    def reduceLockdirTimeout(self):
 
2317
        """Reduce the default lock timeout for the duration of the test, so that
 
2318
        if LockContention occurs during a test, it does so quickly.
 
2319
 
 
2320
        Tests that expect to provoke LockContention errors should call this.
 
2321
        """
 
2322
        self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
 
2323
 
 
2324
    def make_utf8_encoded_stringio(self, encoding_type=None):
 
2325
        """Return a wrapped BytesIO, that will encode text input to UTF-8."""
 
2326
        if encoding_type is None:
 
2327
            encoding_type = 'strict'
 
2328
        bio = BytesIO()
 
2329
        output_encoding = 'utf-8'
 
2330
        sio = codecs.getwriter(output_encoding)(bio, errors=encoding_type)
 
2331
        sio.encoding = output_encoding
 
2332
        return sio
 
2333
 
 
2334
    def disable_verb(self, verb):
 
2335
        """Disable a smart server verb for one test."""
 
2336
        from breezy.smart import request
 
2337
        request_handlers = request.request_handlers
 
2338
        orig_method = request_handlers.get(verb)
 
2339
        orig_info = request_handlers.get_info(verb)
 
2340
        request_handlers.remove(verb)
 
2341
        self.addCleanup(request_handlers.register, verb, orig_method,
 
2342
            info=orig_info)
 
2343
 
 
2344
    def __hash__(self):
 
2345
        return id(self)
 
2346
 
 
2347
 
 
2348
class CapturedCall(object):
 
2349
    """A helper for capturing smart server calls for easy debug analysis."""
 
2350
 
 
2351
    def __init__(self, params, prefix_length):
 
2352
        """Capture the call with params and skip prefix_length stack frames."""
 
2353
        self.call = params
 
2354
        import traceback
 
2355
        # The last 5 frames are the __init__, the hook frame, and 3 smart
 
2356
        # client frames. Beyond this we could get more clever, but this is good
 
2357
        # enough for now.
 
2358
        stack = traceback.extract_stack()[prefix_length:-5]
 
2359
        self.stack = ''.join(traceback.format_list(stack))
 
2360
 
 
2361
    def __str__(self):
 
2362
        return self.call.method
 
2363
 
 
2364
    def __repr__(self):
 
2365
        return self.call.method
 
2366
 
 
2367
    def stack(self):
 
2368
        return self.stack
 
2369
 
 
2370
 
 
2371
class TestCaseWithMemoryTransport(TestCase):
 
2372
    """Common test class for tests that do not need disk resources.
 
2373
 
 
2374
    Tests that need disk resources should derive from TestCaseInTempDir
 
2375
    orTestCaseWithTransport.
 
2376
 
 
2377
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all brz tests.
 
2378
 
 
2379
    For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
 
2380
    a directory which does not exist. This serves to help ensure test isolation
 
2381
    is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
 
2382
    must exist. However, TestCaseWithMemoryTransport does not offer local file
 
2383
    defaults for the transport in tests, nor does it obey the command line
 
2384
    override, so tests that accidentally write to the common directory should
 
2385
    be rare.
 
2386
 
 
2387
    :cvar TEST_ROOT: Directory containing all temporary directories, plus a
 
2388
        ``.bzr`` directory that stops us ascending higher into the filesystem.
 
2389
    """
 
2390
 
 
2391
    TEST_ROOT = None
 
2392
    _TEST_NAME = 'test'
 
2393
 
 
2394
    def __init__(self, methodName='runTest'):
 
2395
        # allow test parameterization after test construction and before test
 
2396
        # execution. Variables that the parameterizer sets need to be
 
2397
        # ones that are not set by setUp, or setUp will trash them.
 
2398
        super(TestCaseWithMemoryTransport, self).__init__(methodName)
 
2399
        self.vfs_transport_factory = default_transport
 
2400
        self.transport_server = None
 
2401
        self.transport_readonly_server = None
 
2402
        self.__vfs_server = None
 
2403
 
 
2404
    def setUp(self):
 
2405
        super(TestCaseWithMemoryTransport, self).setUp()
 
2406
 
 
2407
        def _add_disconnect_cleanup(transport):
 
2408
            """Schedule disconnection of given transport at test cleanup
 
2409
 
 
2410
            This needs to happen for all connected transports or leaks occur.
 
2411
 
 
2412
            Note reconnections may mean we call disconnect multiple times per
 
2413
            transport which is suboptimal but seems harmless.
 
2414
            """
 
2415
            self.addCleanup(transport.disconnect)
 
2416
 
 
2417
        _mod_transport.Transport.hooks.install_named_hook('post_connect',
 
2418
            _add_disconnect_cleanup, None)
 
2419
 
 
2420
        self._make_test_root()
 
2421
        self.addCleanup(os.chdir, osutils.getcwd())
 
2422
        self.makeAndChdirToTestDir()
 
2423
        self.overrideEnvironmentForTesting()
 
2424
        self.__readonly_server = None
 
2425
        self.__server = None
 
2426
        self.reduceLockdirTimeout()
 
2427
        # Each test may use its own config files even if the local config files
 
2428
        # don't actually exist. They'll rightly fail if they try to create them
 
2429
        # though.
 
2430
        self.overrideAttr(config, '_shared_stores', {})
 
2431
 
 
2432
    def get_transport(self, relpath=None):
 
2433
        """Return a writeable transport.
 
2434
 
 
2435
        This transport is for the test scratch space relative to
 
2436
        "self._test_root"
 
2437
 
 
2438
        :param relpath: a path relative to the base url.
 
2439
        """
 
2440
        t = _mod_transport.get_transport_from_url(self.get_url(relpath))
 
2441
        self.assertFalse(t.is_readonly())
 
2442
        return t
 
2443
 
 
2444
    def get_readonly_transport(self, relpath=None):
 
2445
        """Return a readonly transport for the test scratch space
 
2446
 
 
2447
        This can be used to test that operations which should only need
 
2448
        readonly access in fact do not try to write.
 
2449
 
 
2450
        :param relpath: a path relative to the base url.
 
2451
        """
 
2452
        t = _mod_transport.get_transport_from_url(
 
2453
            self.get_readonly_url(relpath))
 
2454
        self.assertTrue(t.is_readonly())
 
2455
        return t
 
2456
 
 
2457
    def create_transport_readonly_server(self):
 
2458
        """Create a transport server from class defined at init.
 
2459
 
 
2460
        This is mostly a hook for daughter classes.
 
2461
        """
 
2462
        return self.transport_readonly_server()
 
2463
 
 
2464
    def get_readonly_server(self):
 
2465
        """Get the server instance for the readonly transport
 
2466
 
 
2467
        This is useful for some tests with specific servers to do diagnostics.
 
2468
        """
 
2469
        if self.__readonly_server is None:
 
2470
            if self.transport_readonly_server is None:
 
2471
                # readonly decorator requested
 
2472
                self.__readonly_server = test_server.ReadonlyServer()
 
2473
            else:
 
2474
                # explicit readonly transport.
 
2475
                self.__readonly_server = self.create_transport_readonly_server()
 
2476
            self.start_server(self.__readonly_server,
 
2477
                self.get_vfs_only_server())
 
2478
        return self.__readonly_server
 
2479
 
 
2480
    def get_readonly_url(self, relpath=None):
 
2481
        """Get a URL for the readonly transport.
 
2482
 
 
2483
        This will either be backed by '.' or a decorator to the transport
 
2484
        used by self.get_url()
 
2485
        relpath provides for clients to get a path relative to the base url.
 
2486
        These should only be downwards relative, not upwards.
 
2487
        """
 
2488
        base = self.get_readonly_server().get_url()
 
2489
        return self._adjust_url(base, relpath)
 
2490
 
 
2491
    def get_vfs_only_server(self):
 
2492
        """Get the vfs only read/write server instance.
 
2493
 
 
2494
        This is useful for some tests with specific servers that need
 
2495
        diagnostics.
 
2496
 
 
2497
        For TestCaseWithMemoryTransport this is always a MemoryServer, and there
 
2498
        is no means to override it.
 
2499
        """
 
2500
        if self.__vfs_server is None:
 
2501
            self.__vfs_server = memory.MemoryServer()
 
2502
            self.start_server(self.__vfs_server)
 
2503
        return self.__vfs_server
 
2504
 
 
2505
    def get_server(self):
 
2506
        """Get the read/write server instance.
 
2507
 
 
2508
        This is useful for some tests with specific servers that need
 
2509
        diagnostics.
 
2510
 
 
2511
        This is built from the self.transport_server factory. If that is None,
 
2512
        then the self.get_vfs_server is returned.
 
2513
        """
 
2514
        if self.__server is None:
 
2515
            if (self.transport_server is None or self.transport_server is
 
2516
                self.vfs_transport_factory):
 
2517
                self.__server = self.get_vfs_only_server()
 
2518
            else:
 
2519
                # bring up a decorated means of access to the vfs only server.
 
2520
                self.__server = self.transport_server()
 
2521
                self.start_server(self.__server, self.get_vfs_only_server())
 
2522
        return self.__server
 
2523
 
 
2524
    def _adjust_url(self, base, relpath):
 
2525
        """Get a URL (or maybe a path) for the readwrite transport.
 
2526
 
 
2527
        This will either be backed by '.' or to an equivalent non-file based
 
2528
        facility.
 
2529
        relpath provides for clients to get a path relative to the base url.
 
2530
        These should only be downwards relative, not upwards.
 
2531
        """
 
2532
        if relpath is not None and relpath != '.':
 
2533
            if not base.endswith('/'):
 
2534
                base = base + '/'
 
2535
            # XXX: Really base should be a url; we did after all call
 
2536
            # get_url()!  But sometimes it's just a path (from
 
2537
            # LocalAbspathServer), and it'd be wrong to append urlescaped data
 
2538
            # to a non-escaped local path.
 
2539
            if base.startswith('./') or base.startswith('/'):
 
2540
                base += relpath
 
2541
            else:
 
2542
                base += urlutils.escape(relpath)
 
2543
        return base
 
2544
 
 
2545
    def get_url(self, relpath=None):
 
2546
        """Get a URL (or maybe a path) for the readwrite transport.
 
2547
 
 
2548
        This will either be backed by '.' or to an equivalent non-file based
 
2549
        facility.
 
2550
        relpath provides for clients to get a path relative to the base url.
 
2551
        These should only be downwards relative, not upwards.
 
2552
        """
 
2553
        base = self.get_server().get_url()
 
2554
        return self._adjust_url(base, relpath)
 
2555
 
 
2556
    def get_vfs_only_url(self, relpath=None):
 
2557
        """Get a URL (or maybe a path for the plain old vfs transport.
 
2558
 
 
2559
        This will never be a smart protocol.  It always has all the
 
2560
        capabilities of the local filesystem, but it might actually be a
 
2561
        MemoryTransport or some other similar virtual filesystem.
 
2562
 
 
2563
        This is the backing transport (if any) of the server returned by
 
2564
        get_url and get_readonly_url.
 
2565
 
 
2566
        :param relpath: provides for clients to get a path relative to the base
 
2567
            url.  These should only be downwards relative, not upwards.
 
2568
        :return: A URL
 
2569
        """
 
2570
        base = self.get_vfs_only_server().get_url()
 
2571
        return self._adjust_url(base, relpath)
 
2572
 
 
2573
    def _create_safety_net(self):
 
2574
        """Make a fake bzr directory.
 
2575
 
 
2576
        This prevents any tests propagating up onto the TEST_ROOT directory's
 
2577
        real branch.
 
2578
        """
 
2579
        root = TestCaseWithMemoryTransport.TEST_ROOT
 
2580
        try:
 
2581
            # Make sure we get a readable and accessible home for .brz.log
 
2582
            # and/or config files, and not fallback to weird defaults (see
 
2583
            # http://pad.lv/825027).
 
2584
            self.assertIs(None, os.environ.get('BRZ_HOME', None))
 
2585
            os.environ['BRZ_HOME'] = root
 
2586
            wt = controldir.ControlDir.create_standalone_workingtree(root)
 
2587
            del os.environ['BRZ_HOME']
 
2588
        except Exception as e:
 
2589
            self.fail("Fail to initialize the safety net: %r\n" % (e,))
 
2590
        # Hack for speed: remember the raw bytes of the dirstate file so that
 
2591
        # we don't need to re-open the wt to check it hasn't changed.
 
2592
        TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
 
2593
            wt.control_transport.get_bytes('dirstate'))
 
2594
 
 
2595
    def _check_safety_net(self):
 
2596
        """Check that the safety .bzr directory have not been touched.
 
2597
 
 
2598
        _make_test_root have created a .bzr directory to prevent tests from
 
2599
        propagating. This method ensures than a test did not leaked.
 
2600
        """
 
2601
        root = TestCaseWithMemoryTransport.TEST_ROOT
 
2602
        t = _mod_transport.get_transport_from_path(root)
 
2603
        self.permit_url(t.base)
 
2604
        if (t.get_bytes('.bzr/checkout/dirstate') != 
 
2605
                TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
 
2606
            # The current test have modified the /bzr directory, we need to
 
2607
            # recreate a new one or all the followng tests will fail.
 
2608
            # If you need to inspect its content uncomment the following line
 
2609
            # import pdb; pdb.set_trace()
 
2610
            _rmtree_temp_dir(root + '/.bzr', test_id=self.id())
 
2611
            self._create_safety_net()
 
2612
            raise AssertionError('%s/.bzr should not be modified' % root)
 
2613
 
 
2614
    def _make_test_root(self):
 
2615
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
 
2616
            # Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
 
2617
            root = osutils.realpath(osutils.mkdtemp(prefix='testbzr-',
 
2618
                                                    suffix='.tmp'))
 
2619
            TestCaseWithMemoryTransport.TEST_ROOT = root
 
2620
 
 
2621
            self._create_safety_net()
 
2622
 
 
2623
            # The same directory is used by all tests, and we're not
 
2624
            # specifically told when all tests are finished.  This will do.
 
2625
            atexit.register(_rmtree_temp_dir, root)
 
2626
 
 
2627
        self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
 
2628
        self.addCleanup(self._check_safety_net)
 
2629
 
 
2630
    def makeAndChdirToTestDir(self):
 
2631
        """Create a temporary directories for this one test.
 
2632
 
 
2633
        This must set self.test_home_dir and self.test_dir and chdir to
 
2634
        self.test_dir.
 
2635
 
 
2636
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
 
2637
        """
 
2638
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
 
2639
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
 
2640
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
 
2641
        self.permit_dir(self.test_dir)
 
2642
 
 
2643
    def make_branch(self, relpath, format=None, name=None):
 
2644
        """Create a branch on the transport at relpath."""
 
2645
        repo = self.make_repository(relpath, format=format)
 
2646
        return repo.bzrdir.create_branch(append_revisions_only=False,
 
2647
                                         name=name)
 
2648
 
 
2649
    def get_default_format(self):
 
2650
        return 'default'
 
2651
 
 
2652
    def resolve_format(self, format):
 
2653
        """Resolve an object to a ControlDir format object.
 
2654
 
 
2655
        The initial format object can either already be
 
2656
        a ControlDirFormat, None (for the default format),
 
2657
        or a string with the name of the control dir format.
 
2658
 
 
2659
        :param format: Object to resolve
 
2660
        :return A ControlDirFormat instance
 
2661
        """
 
2662
        if format is None:
 
2663
            format = self.get_default_format()
 
2664
        if isinstance(format, basestring):
 
2665
            format = controldir.format_registry.make_bzrdir(format)
 
2666
        return format
 
2667
 
 
2668
    def make_bzrdir(self, relpath, format=None):
 
2669
        try:
 
2670
            # might be a relative or absolute path
 
2671
            maybe_a_url = self.get_url(relpath)
 
2672
            segments = maybe_a_url.rsplit('/', 1)
 
2673
            t = _mod_transport.get_transport(maybe_a_url)
 
2674
            if len(segments) > 1 and segments[-1] not in ('', '.'):
 
2675
                t.ensure_base()
 
2676
            format = self.resolve_format(format)
 
2677
            return format.initialize_on_transport(t)
 
2678
        except errors.UninitializableFormat:
 
2679
            raise TestSkipped("Format %s is not initializable." % format)
 
2680
 
 
2681
    def make_repository(self, relpath, shared=None, format=None):
 
2682
        """Create a repository on our default transport at relpath.
 
2683
 
 
2684
        Note that relpath must be a relative path, not a full url.
 
2685
        """
 
2686
        # FIXME: If you create a remoterepository this returns the underlying
 
2687
        # real format, which is incorrect.  Actually we should make sure that
 
2688
        # RemoteBzrDir returns a RemoteRepository.
 
2689
        # maybe  mbp 20070410
 
2690
        made_control = self.make_bzrdir(relpath, format=format)
 
2691
        return made_control.create_repository(shared=shared)
 
2692
 
 
2693
    def make_smart_server(self, path, backing_server=None):
 
2694
        if backing_server is None:
 
2695
            backing_server = self.get_server()
 
2696
        smart_server = test_server.SmartTCPServer_for_testing()
 
2697
        self.start_server(smart_server, backing_server)
 
2698
        remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
 
2699
                                                   ).clone(path)
 
2700
        return remote_transport
 
2701
 
 
2702
    def make_branch_and_memory_tree(self, relpath, format=None):
 
2703
        """Create a branch on the default transport and a MemoryTree for it."""
 
2704
        b = self.make_branch(relpath, format=format)
 
2705
        return memorytree.MemoryTree.create_on_branch(b)
 
2706
 
 
2707
    def make_branch_builder(self, relpath, format=None):
 
2708
        branch = self.make_branch(relpath, format=format)
 
2709
        return branchbuilder.BranchBuilder(branch=branch)
 
2710
 
 
2711
    def overrideEnvironmentForTesting(self):
 
2712
        test_home_dir = self.test_home_dir
 
2713
        if isinstance(test_home_dir, text_type):
 
2714
            test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
 
2715
        self.overrideEnv('HOME', test_home_dir)
 
2716
        self.overrideEnv('BRZ_HOME', test_home_dir)
 
2717
 
 
2718
    def setup_smart_server_with_call_log(self):
 
2719
        """Sets up a smart server as the transport server with a call log."""
 
2720
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2721
        self.hpss_connections = []
 
2722
        self.hpss_calls = []
 
2723
        import traceback
 
2724
        # Skip the current stack down to the caller of
 
2725
        # setup_smart_server_with_call_log
 
2726
        prefix_length = len(traceback.extract_stack()) - 2
 
2727
        def capture_hpss_call(params):
 
2728
            self.hpss_calls.append(
 
2729
                CapturedCall(params, prefix_length))
 
2730
        def capture_connect(transport):
 
2731
            self.hpss_connections.append(transport)
 
2732
        client._SmartClient.hooks.install_named_hook(
 
2733
            'call', capture_hpss_call, None)
 
2734
        _mod_transport.Transport.hooks.install_named_hook(
 
2735
            'post_connect', capture_connect, None)
 
2736
 
 
2737
    def reset_smart_call_log(self):
 
2738
        self.hpss_calls = []
 
2739
        self.hpss_connections = []
 
2740
 
 
2741
 
 
2742
class TestCaseInTempDir(TestCaseWithMemoryTransport):
 
2743
    """Derived class that runs a test within a temporary directory.
 
2744
 
 
2745
    This is useful for tests that need to create a branch, etc.
 
2746
 
 
2747
    The directory is created in a slightly complex way: for each
 
2748
    Python invocation, a new temporary top-level directory is created.
 
2749
    All test cases create their own directory within that.  If the
 
2750
    tests complete successfully, the directory is removed.
 
2751
 
 
2752
    :ivar test_base_dir: The path of the top-level directory for this
 
2753
    test, which contains a home directory and a work directory.
 
2754
 
 
2755
    :ivar test_home_dir: An initially empty directory under test_base_dir
 
2756
    which is used as $HOME for this test.
 
2757
 
 
2758
    :ivar test_dir: A directory under test_base_dir used as the current
 
2759
    directory when the test proper is run.
 
2760
    """
 
2761
 
 
2762
    OVERRIDE_PYTHON = 'python'
 
2763
 
 
2764
    def setUp(self):
 
2765
        super(TestCaseInTempDir, self).setUp()
 
2766
        # Remove the protection set in isolated_environ, we have a proper
 
2767
        # access to disk resources now.
 
2768
        self.overrideEnv('BRZ_LOG', None)
 
2769
 
 
2770
    def check_file_contents(self, filename, expect):
 
2771
        self.log("check contents of file %s" % filename)
 
2772
        f = file(filename)
 
2773
        try:
 
2774
            contents = f.read()
 
2775
        finally:
 
2776
            f.close()
 
2777
        if contents != expect:
 
2778
            self.log("expected: %r" % expect)
 
2779
            self.log("actually: %r" % contents)
 
2780
            self.fail("contents of %s not as expected" % filename)
 
2781
 
 
2782
    def _getTestDirPrefix(self):
 
2783
        # create a directory within the top level test directory
 
2784
        if sys.platform in ('win32', 'cygwin'):
 
2785
            name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
 
2786
            # windows is likely to have path-length limits so use a short name
 
2787
            name_prefix = name_prefix[-30:]
 
2788
        else:
 
2789
            name_prefix = re.sub('[/]', '_', self.id())
 
2790
        return name_prefix
 
2791
 
 
2792
    def makeAndChdirToTestDir(self):
 
2793
        """See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
 
2794
 
 
2795
        For TestCaseInTempDir we create a temporary directory based on the test
 
2796
        name and then create two subdirs - test and home under it.
 
2797
        """
 
2798
        name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
 
2799
            self._getTestDirPrefix())
 
2800
        name = name_prefix
 
2801
        for i in range(100):
 
2802
            if os.path.exists(name):
 
2803
                name = name_prefix + '_' + str(i)
 
2804
            else:
 
2805
                # now create test and home directories within this dir
 
2806
                self.test_base_dir = name
 
2807
                self.addCleanup(self.deleteTestDir)
 
2808
                os.mkdir(self.test_base_dir)
 
2809
                break
 
2810
        self.permit_dir(self.test_base_dir)
 
2811
        # 'sprouting' and 'init' of a branch both walk up the tree to find
 
2812
        # stacking policy to honour; create a bzr dir with an unshared
 
2813
        # repository (but not a branch - our code would be trying to escape
 
2814
        # then!) to stop them, and permit it to be read.
 
2815
        # control = controldir.ControlDir.create(self.test_base_dir)
 
2816
        # control.create_repository()
 
2817
        self.test_home_dir = self.test_base_dir + '/home'
 
2818
        os.mkdir(self.test_home_dir)
 
2819
        self.test_dir = self.test_base_dir + '/work'
 
2820
        os.mkdir(self.test_dir)
 
2821
        os.chdir(self.test_dir)
 
2822
        # put name of test inside
 
2823
        f = file(self.test_base_dir + '/name', 'w')
 
2824
        try:
 
2825
            f.write(self.id())
 
2826
        finally:
 
2827
            f.close()
 
2828
 
 
2829
    def deleteTestDir(self):
 
2830
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
 
2831
        _rmtree_temp_dir(self.test_base_dir, test_id=self.id())
 
2832
 
 
2833
    def build_tree(self, shape, line_endings='binary', transport=None):
 
2834
        """Build a test tree according to a pattern.
 
2835
 
 
2836
        shape is a sequence of file specifications.  If the final
 
2837
        character is '/', a directory is created.
 
2838
 
 
2839
        This assumes that all the elements in the tree being built are new.
 
2840
 
 
2841
        This doesn't add anything to a branch.
 
2842
 
 
2843
        :type shape:    list or tuple.
 
2844
        :param line_endings: Either 'binary' or 'native'
 
2845
            in binary mode, exact contents are written in native mode, the
 
2846
            line endings match the default platform endings.
 
2847
        :param transport: A transport to write to, for building trees on VFS's.
 
2848
            If the transport is readonly or None, "." is opened automatically.
 
2849
        :return: None
 
2850
        """
 
2851
        if type(shape) not in (list, tuple):
 
2852
            raise AssertionError("Parameter 'shape' should be "
 
2853
                "a list or a tuple. Got %r instead" % (shape,))
 
2854
        # It's OK to just create them using forward slashes on windows.
 
2855
        if transport is None or transport.is_readonly():
 
2856
            transport = _mod_transport.get_transport_from_path(".")
 
2857
        for name in shape:
 
2858
            self.assertIsInstance(name, basestring)
 
2859
            if name[-1] == '/':
 
2860
                transport.mkdir(urlutils.escape(name[:-1]))
 
2861
            else:
 
2862
                if line_endings == 'binary':
 
2863
                    end = '\n'
 
2864
                elif line_endings == 'native':
 
2865
                    end = os.linesep
 
2866
                else:
 
2867
                    raise errors.BzrError(
 
2868
                        'Invalid line ending request %r' % line_endings)
 
2869
                content = "contents of %s%s" % (name.encode('utf-8'), end)
 
2870
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
 
2871
 
 
2872
    build_tree_contents = staticmethod(treeshape.build_tree_contents)
 
2873
 
 
2874
    def assertInWorkingTree(self, path, root_path='.', tree=None):
 
2875
        """Assert whether path or paths are in the WorkingTree"""
 
2876
        if tree is None:
 
2877
            tree = workingtree.WorkingTree.open(root_path)
 
2878
        if not isinstance(path, basestring):
 
2879
            for p in path:
 
2880
                self.assertInWorkingTree(p, tree=tree)
 
2881
        else:
 
2882
            self.assertIsNot(tree.path2id(path), None,
 
2883
                path+' not in working tree.')
 
2884
 
 
2885
    def assertNotInWorkingTree(self, path, root_path='.', tree=None):
 
2886
        """Assert whether path or paths are not in the WorkingTree"""
 
2887
        if tree is None:
 
2888
            tree = workingtree.WorkingTree.open(root_path)
 
2889
        if not isinstance(path, basestring):
 
2890
            for p in path:
 
2891
                self.assertNotInWorkingTree(p,tree=tree)
 
2892
        else:
 
2893
            self.assertIs(tree.path2id(path), None, path+' in working tree.')
 
2894
 
 
2895
 
 
2896
class TestCaseWithTransport(TestCaseInTempDir):
 
2897
    """A test case that provides get_url and get_readonly_url facilities.
 
2898
 
 
2899
    These back onto two transport servers, one for readonly access and one for
 
2900
    read write access.
 
2901
 
 
2902
    If no explicit class is provided for readonly access, a
 
2903
    ReadonlyTransportDecorator is used instead which allows the use of non disk
 
2904
    based read write transports.
 
2905
 
 
2906
    If an explicit class is provided for readonly access, that server and the
 
2907
    readwrite one must both define get_url() as resolving to os.getcwd().
 
2908
    """
 
2909
 
 
2910
    def setUp(self):
 
2911
        super(TestCaseWithTransport, self).setUp()
 
2912
        self.__vfs_server = None
 
2913
 
 
2914
    def get_vfs_only_server(self):
 
2915
        """See TestCaseWithMemoryTransport.
 
2916
 
 
2917
        This is useful for some tests with specific servers that need
 
2918
        diagnostics.
 
2919
        """
 
2920
        if self.__vfs_server is None:
 
2921
            self.__vfs_server = self.vfs_transport_factory()
 
2922
            self.start_server(self.__vfs_server)
 
2923
        return self.__vfs_server
 
2924
 
 
2925
    def make_branch_and_tree(self, relpath, format=None):
 
2926
        """Create a branch on the transport and a tree locally.
 
2927
 
 
2928
        If the transport is not a LocalTransport, the Tree can't be created on
 
2929
        the transport.  In that case if the vfs_transport_factory is
 
2930
        LocalURLServer the working tree is created in the local
 
2931
        directory backing the transport, and the returned tree's branch and
 
2932
        repository will also be accessed locally. Otherwise a lightweight
 
2933
        checkout is created and returned.
 
2934
 
 
2935
        We do this because we can't physically create a tree in the local
 
2936
        path, with a branch reference to the transport_factory url, and
 
2937
        a branch + repository in the vfs_transport, unless the vfs_transport
 
2938
        namespace is distinct from the local disk - the two branch objects
 
2939
        would collide. While we could construct a tree with its branch object
 
2940
        pointing at the transport_factory transport in memory, reopening it
 
2941
        would behaving unexpectedly, and has in the past caused testing bugs
 
2942
        when we tried to do it that way.
 
2943
 
 
2944
        :param format: The BzrDirFormat.
 
2945
        :returns: the WorkingTree.
 
2946
        """
 
2947
        # TODO: always use the local disk path for the working tree,
 
2948
        # this obviously requires a format that supports branch references
 
2949
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
 
2950
        # RBC 20060208
 
2951
        format = self.resolve_format(format=format)
 
2952
        if not format.supports_workingtrees:
 
2953
            b = self.make_branch(relpath+'.branch', format=format)
 
2954
            return b.create_checkout(relpath, lightweight=True)
 
2955
        b = self.make_branch(relpath, format=format)
 
2956
        try:
 
2957
            return b.bzrdir.create_workingtree()
 
2958
        except errors.NotLocalUrl:
 
2959
            # We can only make working trees locally at the moment.  If the
 
2960
            # transport can't support them, then we keep the non-disk-backed
 
2961
            # branch and create a local checkout.
 
2962
            if self.vfs_transport_factory is test_server.LocalURLServer:
 
2963
                # the branch is colocated on disk, we cannot create a checkout.
 
2964
                # hopefully callers will expect this.
 
2965
                local_controldir = controldir.ControlDir.open(
 
2966
                    self.get_vfs_only_url(relpath))
 
2967
                wt = local_controldir.create_workingtree()
 
2968
                if wt.branch._format != b._format:
 
2969
                    wt._branch = b
 
2970
                    # Make sure that assigning to wt._branch fixes wt.branch,
 
2971
                    # in case the implementation details of workingtree objects
 
2972
                    # change.
 
2973
                    self.assertIs(b, wt.branch)
 
2974
                return wt
 
2975
            else:
 
2976
                return b.create_checkout(relpath, lightweight=True)
 
2977
 
 
2978
    def assertIsDirectory(self, relpath, transport):
 
2979
        """Assert that relpath within transport is a directory.
 
2980
 
 
2981
        This may not be possible on all transports; in that case it propagates
 
2982
        a TransportNotPossible.
 
2983
        """
 
2984
        try:
 
2985
            mode = transport.stat(relpath).st_mode
 
2986
        except errors.NoSuchFile:
 
2987
            self.fail("path %s is not a directory; no such file"
 
2988
                      % (relpath))
 
2989
        if not stat.S_ISDIR(mode):
 
2990
            self.fail("path %s is not a directory; has mode %#o"
 
2991
                      % (relpath, mode))
 
2992
 
 
2993
    def assertTreesEqual(self, left, right):
 
2994
        """Check that left and right have the same content and properties."""
 
2995
        # we use a tree delta to check for equality of the content, and we
 
2996
        # manually check for equality of other things such as the parents list.
 
2997
        self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
 
2998
        differences = left.changes_from(right)
 
2999
        self.assertFalse(differences.has_changed(),
 
3000
            "Trees %r and %r are different: %r" % (left, right, differences))
 
3001
 
 
3002
    def disable_missing_extensions_warning(self):
 
3003
        """Some tests expect a precise stderr content.
 
3004
 
 
3005
        There is no point in forcing them to duplicate the extension related
 
3006
        warning.
 
3007
        """
 
3008
        config.GlobalStack().set('ignore_missing_extensions', True)
 
3009
 
 
3010
 
 
3011
class ChrootedTestCase(TestCaseWithTransport):
 
3012
    """A support class that provides readonly urls outside the local namespace.
 
3013
 
 
3014
    This is done by checking if self.transport_server is a MemoryServer. if it
 
3015
    is then we are chrooted already, if it is not then an HttpServer is used
 
3016
    for readonly urls.
 
3017
 
 
3018
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
 
3019
                       be used without needed to redo it when a different
 
3020
                       subclass is in use ?
 
3021
    """
 
3022
 
 
3023
    def setUp(self):
 
3024
        from breezy.tests import http_server
 
3025
        super(ChrootedTestCase, self).setUp()
 
3026
        if not self.vfs_transport_factory == memory.MemoryServer:
 
3027
            self.transport_readonly_server = http_server.HttpServer
 
3028
 
 
3029
 
 
3030
def condition_id_re(pattern):
 
3031
    """Create a condition filter which performs a re check on a test's id.
 
3032
 
 
3033
    :param pattern: A regular expression string.
 
3034
    :return: A callable that returns True if the re matches.
 
3035
    """
 
3036
    filter_re = re.compile(pattern, 0)
 
3037
    def condition(test):
 
3038
        test_id = test.id()
 
3039
        return filter_re.search(test_id)
 
3040
    return condition
 
3041
 
 
3042
 
 
3043
def condition_isinstance(klass_or_klass_list):
 
3044
    """Create a condition filter which returns isinstance(param, klass).
 
3045
 
 
3046
    :return: A callable which when called with one parameter obj return the
 
3047
        result of isinstance(obj, klass_or_klass_list).
 
3048
    """
 
3049
    def condition(obj):
 
3050
        return isinstance(obj, klass_or_klass_list)
 
3051
    return condition
 
3052
 
 
3053
 
 
3054
def condition_id_in_list(id_list):
 
3055
    """Create a condition filter which verify that test's id in a list.
 
3056
 
 
3057
    :param id_list: A TestIdList object.
 
3058
    :return: A callable that returns True if the test's id appears in the list.
 
3059
    """
 
3060
    def condition(test):
 
3061
        return id_list.includes(test.id())
 
3062
    return condition
 
3063
 
 
3064
 
 
3065
def condition_id_startswith(starts):
 
3066
    """Create a condition filter verifying that test's id starts with a string.
 
3067
 
 
3068
    :param starts: A list of string.
 
3069
    :return: A callable that returns True if the test's id starts with one of
 
3070
        the given strings.
 
3071
    """
 
3072
    def condition(test):
 
3073
        for start in starts:
 
3074
            if test.id().startswith(start):
 
3075
                return True
 
3076
        return False
 
3077
    return condition
 
3078
 
 
3079
 
 
3080
def exclude_tests_by_condition(suite, condition):
 
3081
    """Create a test suite which excludes some tests from suite.
 
3082
 
 
3083
    :param suite: The suite to get tests from.
 
3084
    :param condition: A callable whose result evaluates True when called with a
 
3085
        test case which should be excluded from the result.
 
3086
    :return: A suite which contains the tests found in suite that fail
 
3087
        condition.
 
3088
    """
 
3089
    result = []
 
3090
    for test in iter_suite_tests(suite):
 
3091
        if not condition(test):
 
3092
            result.append(test)
 
3093
    return TestUtil.TestSuite(result)
 
3094
 
 
3095
 
 
3096
def filter_suite_by_condition(suite, condition):
 
3097
    """Create a test suite by filtering another one.
 
3098
 
 
3099
    :param suite: The source suite.
 
3100
    :param condition: A callable whose result evaluates True when called with a
 
3101
        test case which should be included in the result.
 
3102
    :return: A suite which contains the tests found in suite that pass
 
3103
        condition.
 
3104
    """
 
3105
    result = []
 
3106
    for test in iter_suite_tests(suite):
 
3107
        if condition(test):
 
3108
            result.append(test)
 
3109
    return TestUtil.TestSuite(result)
 
3110
 
 
3111
 
 
3112
def filter_suite_by_re(suite, pattern):
 
3113
    """Create a test suite by filtering another one.
 
3114
 
 
3115
    :param suite:           the source suite
 
3116
    :param pattern:         pattern that names must match
 
3117
    :returns: the newly created suite
 
3118
    """
 
3119
    condition = condition_id_re(pattern)
 
3120
    result_suite = filter_suite_by_condition(suite, condition)
 
3121
    return result_suite
 
3122
 
 
3123
 
 
3124
def filter_suite_by_id_list(suite, test_id_list):
 
3125
    """Create a test suite by filtering another one.
 
3126
 
 
3127
    :param suite: The source suite.
 
3128
    :param test_id_list: A list of the test ids to keep as strings.
 
3129
    :returns: the newly created suite
 
3130
    """
 
3131
    condition = condition_id_in_list(test_id_list)
 
3132
    result_suite = filter_suite_by_condition(suite, condition)
 
3133
    return result_suite
 
3134
 
 
3135
 
 
3136
def filter_suite_by_id_startswith(suite, start):
 
3137
    """Create a test suite by filtering another one.
 
3138
 
 
3139
    :param suite: The source suite.
 
3140
    :param start: A list of string the test id must start with one of.
 
3141
    :returns: the newly created suite
 
3142
    """
 
3143
    condition = condition_id_startswith(start)
 
3144
    result_suite = filter_suite_by_condition(suite, condition)
 
3145
    return result_suite
 
3146
 
 
3147
 
 
3148
def exclude_tests_by_re(suite, pattern):
 
3149
    """Create a test suite which excludes some tests from suite.
 
3150
 
 
3151
    :param suite: The suite to get tests from.
 
3152
    :param pattern: A regular expression string. Test ids that match this
 
3153
        pattern will be excluded from the result.
 
3154
    :return: A TestSuite that contains all the tests from suite without the
 
3155
        tests that matched pattern. The order of tests is the same as it was in
 
3156
        suite.
 
3157
    """
 
3158
    return exclude_tests_by_condition(suite, condition_id_re(pattern))
 
3159
 
 
3160
 
 
3161
def preserve_input(something):
 
3162
    """A helper for performing test suite transformation chains.
 
3163
 
 
3164
    :param something: Anything you want to preserve.
 
3165
    :return: Something.
 
3166
    """
 
3167
    return something
 
3168
 
 
3169
 
 
3170
def randomize_suite(suite):
 
3171
    """Return a new TestSuite with suite's tests in random order.
 
3172
 
 
3173
    The tests in the input suite are flattened into a single suite in order to
 
3174
    accomplish this. Any nested TestSuites are removed to provide global
 
3175
    randomness.
 
3176
    """
 
3177
    tests = list(iter_suite_tests(suite))
 
3178
    random.shuffle(tests)
 
3179
    return TestUtil.TestSuite(tests)
 
3180
 
 
3181
 
 
3182
def split_suite_by_condition(suite, condition):
 
3183
    """Split a test suite into two by a condition.
 
3184
 
 
3185
    :param suite: The suite to split.
 
3186
    :param condition: The condition to match on. Tests that match this
 
3187
        condition are returned in the first test suite, ones that do not match
 
3188
        are in the second suite.
 
3189
    :return: A tuple of two test suites, where the first contains tests from
 
3190
        suite matching the condition, and the second contains the remainder
 
3191
        from suite. The order within each output suite is the same as it was in
 
3192
        suite.
 
3193
    """
 
3194
    matched = []
 
3195
    did_not_match = []
 
3196
    for test in iter_suite_tests(suite):
 
3197
        if condition(test):
 
3198
            matched.append(test)
 
3199
        else:
 
3200
            did_not_match.append(test)
 
3201
    return TestUtil.TestSuite(matched), TestUtil.TestSuite(did_not_match)
 
3202
 
 
3203
 
 
3204
def split_suite_by_re(suite, pattern):
 
3205
    """Split a test suite into two by a regular expression.
 
3206
 
 
3207
    :param suite: The suite to split.
 
3208
    :param pattern: A regular expression string. Test ids that match this
 
3209
        pattern will be in the first test suite returned, and the others in the
 
3210
        second test suite returned.
 
3211
    :return: A tuple of two test suites, where the first contains tests from
 
3212
        suite matching pattern, and the second contains the remainder from
 
3213
        suite. The order within each output suite is the same as it was in
 
3214
        suite.
 
3215
    """
 
3216
    return split_suite_by_condition(suite, condition_id_re(pattern))
 
3217
 
 
3218
 
 
3219
def run_suite(suite, name='test', verbose=False, pattern=".*",
 
3220
              stop_on_failure=False,
 
3221
              transport=None, lsprof_timed=None, bench_history=None,
 
3222
              matching_tests_first=None,
 
3223
              list_only=False,
 
3224
              random_seed=None,
 
3225
              exclude_pattern=None,
 
3226
              strict=False,
 
3227
              runner_class=None,
 
3228
              suite_decorators=None,
 
3229
              stream=None,
 
3230
              result_decorators=None,
 
3231
              ):
 
3232
    """Run a test suite for brz selftest.
 
3233
 
 
3234
    :param runner_class: The class of runner to use. Must support the
 
3235
        constructor arguments passed by run_suite which are more than standard
 
3236
        python uses.
 
3237
    :return: A boolean indicating success.
 
3238
    """
 
3239
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
 
3240
    if verbose:
 
3241
        verbosity = 2
 
3242
    else:
 
3243
        verbosity = 1
 
3244
    if runner_class is None:
 
3245
        runner_class = TextTestRunner
 
3246
    if stream is None:
 
3247
        stream = sys.stdout
 
3248
    runner = runner_class(stream=stream,
 
3249
                            descriptions=0,
 
3250
                            verbosity=verbosity,
 
3251
                            bench_history=bench_history,
 
3252
                            strict=strict,
 
3253
                            result_decorators=result_decorators,
 
3254
                            )
 
3255
    runner.stop_on_failure=stop_on_failure
 
3256
    if isinstance(suite, unittest.TestSuite):
 
3257
        # Empty out _tests list of passed suite and populate new TestSuite
 
3258
        suite._tests[:], suite = [], TestSuite(suite)
 
3259
    # built in decorator factories:
 
3260
    decorators = [
 
3261
        random_order(random_seed, runner),
 
3262
        exclude_tests(exclude_pattern),
 
3263
        ]
 
3264
    if matching_tests_first:
 
3265
        decorators.append(tests_first(pattern))
 
3266
    else:
 
3267
        decorators.append(filter_tests(pattern))
 
3268
    if suite_decorators:
 
3269
        decorators.extend(suite_decorators)
 
3270
    # tell the result object how many tests will be running: (except if
 
3271
    # --parallel=fork is being used. Robert said he will provide a better
 
3272
    # progress design later -- vila 20090817)
 
3273
    if fork_decorator not in decorators:
 
3274
        decorators.append(CountingDecorator)
 
3275
    for decorator in decorators:
 
3276
        suite = decorator(suite)
 
3277
    if list_only:
 
3278
        # Done after test suite decoration to allow randomisation etc
 
3279
        # to take effect, though that is of marginal benefit.
 
3280
        if verbosity >= 2:
 
3281
            stream.write("Listing tests only ...\n")
 
3282
        for t in iter_suite_tests(suite):
 
3283
            stream.write("%s\n" % (t.id()))
 
3284
        return True
 
3285
    result = runner.run(suite)
 
3286
    if strict:
 
3287
        return result.wasStrictlySuccessful()
 
3288
    else:
 
3289
        return result.wasSuccessful()
 
3290
 
 
3291
 
 
3292
# A registry where get() returns a suite decorator.
 
3293
parallel_registry = registry.Registry()
 
3294
 
 
3295
 
 
3296
def fork_decorator(suite):
 
3297
    if getattr(os, "fork", None) is None:
 
3298
        raise errors.BzrCommandError("platform does not support fork,"
 
3299
            " try --parallel=subprocess instead.")
 
3300
    concurrency = osutils.local_concurrency()
 
3301
    if concurrency == 1:
 
3302
        return suite
 
3303
    from testtools import ConcurrentTestSuite
 
3304
    return ConcurrentTestSuite(suite, fork_for_tests)
 
3305
parallel_registry.register('fork', fork_decorator)
 
3306
 
 
3307
 
 
3308
def subprocess_decorator(suite):
 
3309
    concurrency = osutils.local_concurrency()
 
3310
    if concurrency == 1:
 
3311
        return suite
 
3312
    from testtools import ConcurrentTestSuite
 
3313
    return ConcurrentTestSuite(suite, reinvoke_for_tests)
 
3314
parallel_registry.register('subprocess', subprocess_decorator)
 
3315
 
 
3316
 
 
3317
def exclude_tests(exclude_pattern):
 
3318
    """Return a test suite decorator that excludes tests."""
 
3319
    if exclude_pattern is None:
 
3320
        return identity_decorator
 
3321
    def decorator(suite):
 
3322
        return ExcludeDecorator(suite, exclude_pattern)
 
3323
    return decorator
 
3324
 
 
3325
 
 
3326
def filter_tests(pattern):
 
3327
    if pattern == '.*':
 
3328
        return identity_decorator
 
3329
    def decorator(suite):
 
3330
        return FilterTestsDecorator(suite, pattern)
 
3331
    return decorator
 
3332
 
 
3333
 
 
3334
def random_order(random_seed, runner):
 
3335
    """Return a test suite decorator factory for randomising tests order.
 
3336
 
 
3337
    :param random_seed: now, a string which casts to an integer, or an integer.
 
3338
    :param runner: A test runner with a stream attribute to report on.
 
3339
    """
 
3340
    if random_seed is None:
 
3341
        return identity_decorator
 
3342
    def decorator(suite):
 
3343
        return RandomDecorator(suite, random_seed, runner.stream)
 
3344
    return decorator
 
3345
 
 
3346
 
 
3347
def tests_first(pattern):
 
3348
    if pattern == '.*':
 
3349
        return identity_decorator
 
3350
    def decorator(suite):
 
3351
        return TestFirstDecorator(suite, pattern)
 
3352
    return decorator
 
3353
 
 
3354
 
 
3355
def identity_decorator(suite):
 
3356
    """Return suite."""
 
3357
    return suite
 
3358
 
 
3359
 
 
3360
class TestDecorator(TestUtil.TestSuite):
 
3361
    """A decorator for TestCase/TestSuite objects.
 
3362
 
 
3363
    Contains rather than flattening suite passed on construction
 
3364
    """
 
3365
 
 
3366
    def __init__(self, suite=None):
 
3367
        super(TestDecorator, self).__init__()
 
3368
        if suite is not None:
 
3369
            self.addTest(suite)
 
3370
 
 
3371
    # Don't need subclass run method with suite emptying
 
3372
    run = unittest.TestSuite.run
 
3373
 
 
3374
 
 
3375
class CountingDecorator(TestDecorator):
 
3376
    """A decorator which calls result.progress(self.countTestCases)."""
 
3377
 
 
3378
    def run(self, result):
 
3379
        progress_method = getattr(result, 'progress', None)
 
3380
        if callable(progress_method):
 
3381
            progress_method(self.countTestCases(), SUBUNIT_SEEK_SET)
 
3382
        return super(CountingDecorator, self).run(result)
 
3383
 
 
3384
 
 
3385
class ExcludeDecorator(TestDecorator):
 
3386
    """A decorator which excludes test matching an exclude pattern."""
 
3387
 
 
3388
    def __init__(self, suite, exclude_pattern):
 
3389
        super(ExcludeDecorator, self).__init__(
 
3390
            exclude_tests_by_re(suite, exclude_pattern))
 
3391
 
 
3392
 
 
3393
class FilterTestsDecorator(TestDecorator):
 
3394
    """A decorator which filters tests to those matching a pattern."""
 
3395
 
 
3396
    def __init__(self, suite, pattern):
 
3397
        super(FilterTestsDecorator, self).__init__(
 
3398
            filter_suite_by_re(suite, pattern))
 
3399
 
 
3400
 
 
3401
class RandomDecorator(TestDecorator):
 
3402
    """A decorator which randomises the order of its tests."""
 
3403
 
 
3404
    def __init__(self, suite, random_seed, stream):
 
3405
        random_seed = self.actual_seed(random_seed)
 
3406
        stream.write("Randomizing test order using seed %s\n\n" %
 
3407
            (random_seed,))
 
3408
        # Initialise the random number generator.
 
3409
        random.seed(random_seed)
 
3410
        super(RandomDecorator, self).__init__(randomize_suite(suite))
 
3411
 
 
3412
    @staticmethod
 
3413
    def actual_seed(seed):
 
3414
        if seed == "now":
 
3415
            # We convert the seed to an integer to make it reuseable across
 
3416
            # invocations (because the user can reenter it).
 
3417
            return int(time.time())
 
3418
        else:
 
3419
            # Convert the seed to an integer if we can
 
3420
            try:
 
3421
                return int(seed)
 
3422
            except (TypeError, ValueError):
 
3423
                pass
 
3424
        return seed
 
3425
 
 
3426
 
 
3427
class TestFirstDecorator(TestDecorator):
 
3428
    """A decorator which moves named tests to the front."""
 
3429
 
 
3430
    def __init__(self, suite, pattern):
 
3431
        super(TestFirstDecorator, self).__init__()
 
3432
        self.addTests(split_suite_by_re(suite, pattern))
 
3433
 
 
3434
 
 
3435
def partition_tests(suite, count):
 
3436
    """Partition suite into count lists of tests."""
 
3437
    # This just assigns tests in a round-robin fashion.  On one hand this
 
3438
    # splits up blocks of related tests that might run faster if they shared
 
3439
    # resources, but on the other it avoids assigning blocks of slow tests to
 
3440
    # just one partition.  So the slowest partition shouldn't be much slower
 
3441
    # than the fastest.
 
3442
    partitions = [list() for i in range(count)]
 
3443
    tests = iter_suite_tests(suite)
 
3444
    for partition, test in zip(itertools.cycle(partitions), tests):
 
3445
        partition.append(test)
 
3446
    return partitions
 
3447
 
 
3448
 
 
3449
def workaround_zealous_crypto_random():
 
3450
    """Crypto.Random want to help us being secure, but we don't care here.
 
3451
 
 
3452
    This workaround some test failure related to the sftp server. Once paramiko
 
3453
    stop using the controversial API in Crypto.Random, we may get rid of it.
 
3454
    """
 
3455
    try:
 
3456
        from Crypto.Random import atfork
 
3457
        atfork()
 
3458
    except ImportError:
 
3459
        pass
 
3460
 
 
3461
 
 
3462
def fork_for_tests(suite):
 
3463
    """Take suite and start up one runner per CPU by forking()
 
3464
 
 
3465
    :return: An iterable of TestCase-like objects which can each have
 
3466
        run(result) called on them to feed tests to result.
 
3467
    """
 
3468
    concurrency = osutils.local_concurrency()
 
3469
    result = []
 
3470
    from subunit import ProtocolTestCase
 
3471
    from subunit.test_results import AutoTimingTestResultDecorator
 
3472
    class TestInOtherProcess(ProtocolTestCase):
 
3473
        # Should be in subunit, I think. RBC.
 
3474
        def __init__(self, stream, pid):
 
3475
            ProtocolTestCase.__init__(self, stream)
 
3476
            self.pid = pid
 
3477
 
 
3478
        def run(self, result):
 
3479
            try:
 
3480
                ProtocolTestCase.run(self, result)
 
3481
            finally:
 
3482
                pid, status = os.waitpid(self.pid, 0)
 
3483
            # GZ 2011-10-18: If status is nonzero, should report to the result
 
3484
            #                that something went wrong.
 
3485
 
 
3486
    test_blocks = partition_tests(suite, concurrency)
 
3487
    # Clear the tests from the original suite so it doesn't keep them alive
 
3488
    suite._tests[:] = []
 
3489
    for process_tests in test_blocks:
 
3490
        process_suite = TestUtil.TestSuite(process_tests)
 
3491
        # Also clear each split list so new suite has only reference
 
3492
        process_tests[:] = []
 
3493
        c2pread, c2pwrite = os.pipe()
 
3494
        pid = os.fork()
 
3495
        if pid == 0:
 
3496
            try:
 
3497
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3498
                workaround_zealous_crypto_random()
 
3499
                os.close(c2pread)
 
3500
                # Leave stderr and stdout open so we can see test noise
 
3501
                # Close stdin so that the child goes away if it decides to
 
3502
                # read from stdin (otherwise its a roulette to see what
 
3503
                # child actually gets keystrokes for pdb etc).
 
3504
                sys.stdin.close()
 
3505
                subunit_result = AutoTimingTestResultDecorator(
 
3506
                    SubUnitBzrProtocolClient(stream))
 
3507
                process_suite.run(subunit_result)
 
3508
            except:
 
3509
                # Try and report traceback on stream, but exit with error even
 
3510
                # if stream couldn't be created or something else goes wrong.
 
3511
                # The traceback is formatted to a string and written in one go
 
3512
                # to avoid interleaving lines from multiple failing children.
 
3513
                try:
 
3514
                    stream.write(traceback.format_exc())
 
3515
                finally:
 
3516
                    os._exit(1)
 
3517
            os._exit(0)
 
3518
        else:
 
3519
            os.close(c2pwrite)
 
3520
            stream = os.fdopen(c2pread, 'rb', 1)
 
3521
            test = TestInOtherProcess(stream, pid)
 
3522
            result.append(test)
 
3523
    return result
 
3524
 
 
3525
 
 
3526
def reinvoke_for_tests(suite):
 
3527
    """Take suite and start up one runner per CPU using subprocess().
 
3528
 
 
3529
    :return: An iterable of TestCase-like objects which can each have
 
3530
        run(result) called on them to feed tests to result.
 
3531
    """
 
3532
    concurrency = osutils.local_concurrency()
 
3533
    result = []
 
3534
    from subunit import ProtocolTestCase
 
3535
    class TestInSubprocess(ProtocolTestCase):
 
3536
        def __init__(self, process, name):
 
3537
            ProtocolTestCase.__init__(self, process.stdout)
 
3538
            self.process = process
 
3539
            self.process.stdin.close()
 
3540
            self.name = name
 
3541
 
 
3542
        def run(self, result):
 
3543
            try:
 
3544
                ProtocolTestCase.run(self, result)
 
3545
            finally:
 
3546
                self.process.wait()
 
3547
                os.unlink(self.name)
 
3548
            # print "pid %d finished" % finished_process
 
3549
    test_blocks = partition_tests(suite, concurrency)
 
3550
    for process_tests in test_blocks:
 
3551
        # ugly; currently reimplement rather than reuses TestCase methods.
 
3552
        bzr_path = os.path.dirname(os.path.dirname(breezy.__file__))+'/bzr'
 
3553
        if not os.path.isfile(bzr_path):
 
3554
            # We are probably installed. Assume sys.argv is the right file
 
3555
            bzr_path = sys.argv[0]
 
3556
        bzr_path = [bzr_path]
 
3557
        if sys.platform == "win32":
 
3558
            # if we're on windows, we can't execute the bzr script directly
 
3559
            bzr_path = [sys.executable] + bzr_path
 
3560
        fd, test_list_file_name = tempfile.mkstemp()
 
3561
        test_list_file = os.fdopen(fd, 'wb', 1)
 
3562
        for test in process_tests:
 
3563
            test_list_file.write(test.id() + '\n')
 
3564
        test_list_file.close()
 
3565
        try:
 
3566
            argv = bzr_path + ['selftest', '--load-list', test_list_file_name,
 
3567
                '--subunit']
 
3568
            if '--no-plugins' in sys.argv:
 
3569
                argv.append('--no-plugins')
 
3570
            # stderr=subprocess.STDOUT would be ideal, but until we prevent
 
3571
            # noise on stderr it can interrupt the subunit protocol.
 
3572
            process = subprocess.Popen(argv, stdin=subprocess.PIPE,
 
3573
                                      stdout=subprocess.PIPE,
 
3574
                                      stderr=subprocess.PIPE,
 
3575
                                      bufsize=1)
 
3576
            test = TestInSubprocess(process, test_list_file_name)
 
3577
            result.append(test)
 
3578
        except:
 
3579
            os.unlink(test_list_file_name)
 
3580
            raise
 
3581
    return result
 
3582
 
 
3583
 
 
3584
class ProfileResult(testtools.ExtendedToOriginalDecorator):
 
3585
    """Generate profiling data for all activity between start and success.
 
3586
    
 
3587
    The profile data is appended to the test's _benchcalls attribute and can
 
3588
    be accessed by the forwarded-to TestResult.
 
3589
 
 
3590
    While it might be cleaner do accumulate this in stopTest, addSuccess is
 
3591
    where our existing output support for lsprof is, and this class aims to
 
3592
    fit in with that: while it could be moved it's not necessary to accomplish
 
3593
    test profiling, nor would it be dramatically cleaner.
 
3594
    """
 
3595
 
 
3596
    def startTest(self, test):
 
3597
        self.profiler = breezy.lsprof.BzrProfiler()
 
3598
        # Prevent deadlocks in tests that use lsprof: those tests will
 
3599
        # unavoidably fail.
 
3600
        breezy.lsprof.BzrProfiler.profiler_block = 0
 
3601
        self.profiler.start()
 
3602
        testtools.ExtendedToOriginalDecorator.startTest(self, test)
 
3603
 
 
3604
    def addSuccess(self, test):
 
3605
        stats = self.profiler.stop()
 
3606
        try:
 
3607
            calls = test._benchcalls
 
3608
        except AttributeError:
 
3609
            test._benchcalls = []
 
3610
            calls = test._benchcalls
 
3611
        calls.append(((test.id(), "", ""), stats))
 
3612
        testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
 
3613
 
 
3614
    def stopTest(self, test):
 
3615
        testtools.ExtendedToOriginalDecorator.stopTest(self, test)
 
3616
        self.profiler = None
 
3617
 
 
3618
 
 
3619
# Controlled by "brz selftest -E=..." option
 
3620
# Currently supported:
 
3621
#   -Eallow_debug           Will no longer clear debug.debug_flags() so it
 
3622
#                           preserves any flags supplied at the command line.
 
3623
#   -Edisable_lock_checks   Turns errors in mismatched locks into simple prints
 
3624
#                           rather than failing tests. And no longer raise
 
3625
#                           LockContention when fctnl locks are not being used
 
3626
#                           with proper exclusion rules.
 
3627
#   -Ethreads               Will display thread ident at creation/join time to
 
3628
#                           help track thread leaks
 
3629
#   -Euncollected_cases     Display the identity of any test cases that weren't
 
3630
#                           deallocated after being completed.
 
3631
#   -Econfig_stats          Will collect statistics using addDetail
 
3632
selftest_debug_flags = set()
 
3633
 
 
3634
 
 
3635
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
 
3636
             transport=None,
 
3637
             test_suite_factory=None,
 
3638
             lsprof_timed=None,
 
3639
             bench_history=None,
 
3640
             matching_tests_first=None,
 
3641
             list_only=False,
 
3642
             random_seed=None,
 
3643
             exclude_pattern=None,
 
3644
             strict=False,
 
3645
             load_list=None,
 
3646
             debug_flags=None,
 
3647
             starting_with=None,
 
3648
             runner_class=None,
 
3649
             suite_decorators=None,
 
3650
             stream=None,
 
3651
             lsprof_tests=False,
 
3652
             ):
 
3653
    """Run the whole test suite under the enhanced runner"""
 
3654
    # XXX: Very ugly way to do this...
 
3655
    # Disable warning about old formats because we don't want it to disturb
 
3656
    # any blackbox tests.
 
3657
    from breezy import repository
 
3658
    repository._deprecation_warning_done = True
 
3659
 
 
3660
    global default_transport
 
3661
    if transport is None:
 
3662
        transport = default_transport
 
3663
    old_transport = default_transport
 
3664
    default_transport = transport
 
3665
    global selftest_debug_flags
 
3666
    old_debug_flags = selftest_debug_flags
 
3667
    if debug_flags is not None:
 
3668
        selftest_debug_flags = set(debug_flags)
 
3669
    try:
 
3670
        if load_list is None:
 
3671
            keep_only = None
 
3672
        else:
 
3673
            keep_only = load_test_id_list(load_list)
 
3674
        if starting_with:
 
3675
            starting_with = [test_prefix_alias_registry.resolve_alias(start)
 
3676
                             for start in starting_with]
 
3677
        if test_suite_factory is None:
 
3678
            # Reduce loading time by loading modules based on the starting_with
 
3679
            # patterns.
 
3680
            suite = test_suite(keep_only, starting_with)
 
3681
        else:
 
3682
            suite = test_suite_factory()
 
3683
        if starting_with:
 
3684
            # But always filter as requested.
 
3685
            suite = filter_suite_by_id_startswith(suite, starting_with)
 
3686
        result_decorators = []
 
3687
        if lsprof_tests:
 
3688
            result_decorators.append(ProfileResult)
 
3689
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
 
3690
                     stop_on_failure=stop_on_failure,
 
3691
                     transport=transport,
 
3692
                     lsprof_timed=lsprof_timed,
 
3693
                     bench_history=bench_history,
 
3694
                     matching_tests_first=matching_tests_first,
 
3695
                     list_only=list_only,
 
3696
                     random_seed=random_seed,
 
3697
                     exclude_pattern=exclude_pattern,
 
3698
                     strict=strict,
 
3699
                     runner_class=runner_class,
 
3700
                     suite_decorators=suite_decorators,
 
3701
                     stream=stream,
 
3702
                     result_decorators=result_decorators,
 
3703
                     )
 
3704
    finally:
 
3705
        default_transport = old_transport
 
3706
        selftest_debug_flags = old_debug_flags
 
3707
 
 
3708
 
 
3709
def load_test_id_list(file_name):
 
3710
    """Load a test id list from a text file.
 
3711
 
 
3712
    The format is one test id by line.  No special care is taken to impose
 
3713
    strict rules, these test ids are used to filter the test suite so a test id
 
3714
    that do not match an existing test will do no harm. This allows user to add
 
3715
    comments, leave blank lines, etc.
 
3716
    """
 
3717
    test_list = []
 
3718
    try:
 
3719
        ftest = open(file_name, 'rt')
 
3720
    except IOError as e:
 
3721
        if e.errno != errno.ENOENT:
 
3722
            raise
 
3723
        else:
 
3724
            raise errors.NoSuchFile(file_name)
 
3725
 
 
3726
    for test_name in ftest.readlines():
 
3727
        test_list.append(test_name.strip())
 
3728
    ftest.close()
 
3729
    return test_list
 
3730
 
 
3731
 
 
3732
def suite_matches_id_list(test_suite, id_list):
 
3733
    """Warns about tests not appearing or appearing more than once.
 
3734
 
 
3735
    :param test_suite: A TestSuite object.
 
3736
    :param test_id_list: The list of test ids that should be found in
 
3737
         test_suite.
 
3738
 
 
3739
    :return: (absents, duplicates) absents is a list containing the test found
 
3740
        in id_list but not in test_suite, duplicates is a list containing the
 
3741
        tests found multiple times in test_suite.
 
3742
 
 
3743
    When using a prefined test id list, it may occurs that some tests do not
 
3744
    exist anymore or that some tests use the same id. This function warns the
 
3745
    tester about potential problems in his workflow (test lists are volatile)
 
3746
    or in the test suite itself (using the same id for several tests does not
 
3747
    help to localize defects).
 
3748
    """
 
3749
    # Build a dict counting id occurrences
 
3750
    tests = dict()
 
3751
    for test in iter_suite_tests(test_suite):
 
3752
        id = test.id()
 
3753
        tests[id] = tests.get(id, 0) + 1
 
3754
 
 
3755
    not_found = []
 
3756
    duplicates = []
 
3757
    for id in id_list:
 
3758
        occurs = tests.get(id, 0)
 
3759
        if not occurs:
 
3760
            not_found.append(id)
 
3761
        elif occurs > 1:
 
3762
            duplicates.append(id)
 
3763
 
 
3764
    return not_found, duplicates
 
3765
 
 
3766
 
 
3767
class TestIdList(object):
 
3768
    """Test id list to filter a test suite.
 
3769
 
 
3770
    Relying on the assumption that test ids are built as:
 
3771
    <module>[.<class>.<method>][(<param>+)], <module> being in python dotted
 
3772
    notation, this class offers methods to :
 
3773
    - avoid building a test suite for modules not refered to in the test list,
 
3774
    - keep only the tests listed from the module test suite.
 
3775
    """
 
3776
 
 
3777
    def __init__(self, test_id_list):
 
3778
        # When a test suite needs to be filtered against us we compare test ids
 
3779
        # for equality, so a simple dict offers a quick and simple solution.
 
3780
        self.tests = dict().fromkeys(test_id_list, True)
 
3781
 
 
3782
        # While unittest.TestCase have ids like:
 
3783
        # <module>.<class>.<method>[(<param+)],
 
3784
        # doctest.DocTestCase can have ids like:
 
3785
        # <module>
 
3786
        # <module>.<class>
 
3787
        # <module>.<function>
 
3788
        # <module>.<class>.<method>
 
3789
 
 
3790
        # Since we can't predict a test class from its name only, we settle on
 
3791
        # a simple constraint: a test id always begins with its module name.
 
3792
 
 
3793
        modules = {}
 
3794
        for test_id in test_id_list:
 
3795
            parts = test_id.split('.')
 
3796
            mod_name = parts.pop(0)
 
3797
            modules[mod_name] = True
 
3798
            for part in parts:
 
3799
                mod_name += '.' + part
 
3800
                modules[mod_name] = True
 
3801
        self.modules = modules
 
3802
 
 
3803
    def refers_to(self, module_name):
 
3804
        """Is there tests for the module or one of its sub modules."""
 
3805
        return module_name in self.modules
 
3806
 
 
3807
    def includes(self, test_id):
 
3808
        return test_id in self.tests
 
3809
 
 
3810
 
 
3811
class TestPrefixAliasRegistry(registry.Registry):
 
3812
    """A registry for test prefix aliases.
 
3813
 
 
3814
    This helps implement shorcuts for the --starting-with selftest
 
3815
    option. Overriding existing prefixes is not allowed but not fatal (a
 
3816
    warning will be emitted).
 
3817
    """
 
3818
 
 
3819
    def register(self, key, obj, help=None, info=None,
 
3820
                 override_existing=False):
 
3821
        """See Registry.register.
 
3822
 
 
3823
        Trying to override an existing alias causes a warning to be emitted,
 
3824
        not a fatal execption.
 
3825
        """
 
3826
        try:
 
3827
            super(TestPrefixAliasRegistry, self).register(
 
3828
                key, obj, help=help, info=info, override_existing=False)
 
3829
        except KeyError:
 
3830
            actual = self.get(key)
 
3831
            trace.note(
 
3832
                'Test prefix alias %s is already used for %s, ignoring %s'
 
3833
                % (key, actual, obj))
 
3834
 
 
3835
    def resolve_alias(self, id_start):
 
3836
        """Replace the alias by the prefix in the given string.
 
3837
 
 
3838
        Using an unknown prefix is an error to help catching typos.
 
3839
        """
 
3840
        parts = id_start.split('.')
 
3841
        try:
 
3842
            parts[0] = self.get(parts[0])
 
3843
        except KeyError:
 
3844
            raise errors.BzrCommandError(
 
3845
                '%s is not a known test prefix alias' % parts[0])
 
3846
        return '.'.join(parts)
 
3847
 
 
3848
 
 
3849
test_prefix_alias_registry = TestPrefixAliasRegistry()
 
3850
"""Registry of test prefix aliases."""
 
3851
 
 
3852
 
 
3853
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
 
3854
# appear prefixed ('breezy.' is "replaced" by 'breezy.').
 
3855
test_prefix_alias_registry.register('breezy', 'breezy')
 
3856
 
 
3857
# Obvious highest levels prefixes, feel free to add your own via a plugin
 
3858
test_prefix_alias_registry.register('bd', 'breezy.doc')
 
3859
test_prefix_alias_registry.register('bu', 'breezy.utils')
 
3860
test_prefix_alias_registry.register('bt', 'breezy.tests')
 
3861
test_prefix_alias_registry.register('bb', 'breezy.tests.blackbox')
 
3862
test_prefix_alias_registry.register('bp', 'breezy.plugins')
 
3863
 
 
3864
 
 
3865
def _test_suite_testmod_names():
 
3866
    """Return the standard list of test module names to test."""
 
3867
    return [
 
3868
        'breezy.doc',
 
3869
        'breezy.tests.blackbox',
 
3870
        'breezy.tests.commands',
 
3871
        'breezy.tests.per_branch',
 
3872
        'breezy.tests.per_bzrdir',
 
3873
        'breezy.tests.per_controldir',
 
3874
        'breezy.tests.per_controldir_colo',
 
3875
        'breezy.tests.per_foreign_vcs',
 
3876
        'breezy.tests.per_interrepository',
 
3877
        'breezy.tests.per_intertree',
 
3878
        'breezy.tests.per_inventory',
 
3879
        'breezy.tests.per_interbranch',
 
3880
        'breezy.tests.per_lock',
 
3881
        'breezy.tests.per_merger',
 
3882
        'breezy.tests.per_transport',
 
3883
        'breezy.tests.per_tree',
 
3884
        'breezy.tests.per_pack_repository',
 
3885
        'breezy.tests.per_repository',
 
3886
        'breezy.tests.per_repository_chk',
 
3887
        'breezy.tests.per_repository_reference',
 
3888
        'breezy.tests.per_repository_vf',
 
3889
        'breezy.tests.per_uifactory',
 
3890
        'breezy.tests.per_versionedfile',
 
3891
        'breezy.tests.per_workingtree',
 
3892
        'breezy.tests.test__annotator',
 
3893
        'breezy.tests.test__bencode',
 
3894
        'breezy.tests.test__btree_serializer',
 
3895
        'breezy.tests.test__chk_map',
 
3896
        'breezy.tests.test__dirstate_helpers',
 
3897
        'breezy.tests.test__groupcompress',
 
3898
        'breezy.tests.test__known_graph',
 
3899
        'breezy.tests.test__rio',
 
3900
        'breezy.tests.test__simple_set',
 
3901
        'breezy.tests.test__static_tuple',
 
3902
        'breezy.tests.test__walkdirs_win32',
 
3903
        'breezy.tests.test_ancestry',
 
3904
        'breezy.tests.test_annotate',
 
3905
        'breezy.tests.test_api',
 
3906
        'breezy.tests.test_atomicfile',
 
3907
        'breezy.tests.test_bad_files',
 
3908
        'breezy.tests.test_bisect_multi',
 
3909
        'breezy.tests.test_branch',
 
3910
        'breezy.tests.test_branchbuilder',
 
3911
        'breezy.tests.test_btree_index',
 
3912
        'breezy.tests.test_bugtracker',
 
3913
        'breezy.tests.test_bundle',
 
3914
        'breezy.tests.test_bzrdir',
 
3915
        'breezy.tests.test__chunks_to_lines',
 
3916
        'breezy.tests.test_cache_utf8',
 
3917
        'breezy.tests.test_chk_map',
 
3918
        'breezy.tests.test_chk_serializer',
 
3919
        'breezy.tests.test_chunk_writer',
 
3920
        'breezy.tests.test_clean_tree',
 
3921
        'breezy.tests.test_cleanup',
 
3922
        'breezy.tests.test_cmdline',
 
3923
        'breezy.tests.test_commands',
 
3924
        'breezy.tests.test_commit',
 
3925
        'breezy.tests.test_commit_merge',
 
3926
        'breezy.tests.test_config',
 
3927
        'breezy.tests.test_conflicts',
 
3928
        'breezy.tests.test_controldir',
 
3929
        'breezy.tests.test_counted_lock',
 
3930
        'breezy.tests.test_crash',
 
3931
        'breezy.tests.test_decorators',
 
3932
        'breezy.tests.test_delta',
 
3933
        'breezy.tests.test_debug',
 
3934
        'breezy.tests.test_diff',
 
3935
        'breezy.tests.test_directory_service',
 
3936
        'breezy.tests.test_dirstate',
 
3937
        'breezy.tests.test_email_message',
 
3938
        'breezy.tests.test_eol_filters',
 
3939
        'breezy.tests.test_errors',
 
3940
        'breezy.tests.test_estimate_compressed_size',
 
3941
        'breezy.tests.test_export',
 
3942
        'breezy.tests.test_export_pot',
 
3943
        'breezy.tests.test_extract',
 
3944
        'breezy.tests.test_features',
 
3945
        'breezy.tests.test_fetch',
 
3946
        'breezy.tests.test_fetch_ghosts',
 
3947
        'breezy.tests.test_fixtures',
 
3948
        'breezy.tests.test_fifo_cache',
 
3949
        'breezy.tests.test_filters',
 
3950
        'breezy.tests.test_filter_tree',
 
3951
        'breezy.tests.test_ftp_transport',
 
3952
        'breezy.tests.test_foreign',
 
3953
        'breezy.tests.test_generate_docs',
 
3954
        'breezy.tests.test_generate_ids',
 
3955
        'breezy.tests.test_globbing',
 
3956
        'breezy.tests.test_gpg',
 
3957
        'breezy.tests.test_graph',
 
3958
        'breezy.tests.test_groupcompress',
 
3959
        'breezy.tests.test_hashcache',
 
3960
        'breezy.tests.test_help',
 
3961
        'breezy.tests.test_hooks',
 
3962
        'breezy.tests.test_http',
 
3963
        'breezy.tests.test_http_response',
 
3964
        'breezy.tests.test_https_ca_bundle',
 
3965
        'breezy.tests.test_https_urllib',
 
3966
        'breezy.tests.test_i18n',
 
3967
        'breezy.tests.test_identitymap',
 
3968
        'breezy.tests.test_ignores',
 
3969
        'breezy.tests.test_index',
 
3970
        'breezy.tests.test_import_tariff',
 
3971
        'breezy.tests.test_info',
 
3972
        'breezy.tests.test_inv',
 
3973
        'breezy.tests.test_inventory_delta',
 
3974
        'breezy.tests.test_knit',
 
3975
        'breezy.tests.test_lazy_import',
 
3976
        'breezy.tests.test_lazy_regex',
 
3977
        'breezy.tests.test_library_state',
 
3978
        'breezy.tests.test_lock',
 
3979
        'breezy.tests.test_lockable_files',
 
3980
        'breezy.tests.test_lockdir',
 
3981
        'breezy.tests.test_log',
 
3982
        'breezy.tests.test_lru_cache',
 
3983
        'breezy.tests.test_lsprof',
 
3984
        'breezy.tests.test_mail_client',
 
3985
        'breezy.tests.test_matchers',
 
3986
        'breezy.tests.test_memorytree',
 
3987
        'breezy.tests.test_merge',
 
3988
        'breezy.tests.test_merge3',
 
3989
        'breezy.tests.test_merge_core',
 
3990
        'breezy.tests.test_merge_directive',
 
3991
        'breezy.tests.test_mergetools',
 
3992
        'breezy.tests.test_missing',
 
3993
        'breezy.tests.test_msgeditor',
 
3994
        'breezy.tests.test_multiparent',
 
3995
        'breezy.tests.test_mutabletree',
 
3996
        'breezy.tests.test_nonascii',
 
3997
        'breezy.tests.test_options',
 
3998
        'breezy.tests.test_osutils',
 
3999
        'breezy.tests.test_osutils_encodings',
 
4000
        'breezy.tests.test_pack',
 
4001
        'breezy.tests.test_patch',
 
4002
        'breezy.tests.test_patches',
 
4003
        'breezy.tests.test_permissions',
 
4004
        'breezy.tests.test_plugins',
 
4005
        'breezy.tests.test_progress',
 
4006
        'breezy.tests.test_pyutils',
 
4007
        'breezy.tests.test_read_bundle',
 
4008
        'breezy.tests.test_reconcile',
 
4009
        'breezy.tests.test_reconfigure',
 
4010
        'breezy.tests.test_registry',
 
4011
        'breezy.tests.test_remote',
 
4012
        'breezy.tests.test_rename_map',
 
4013
        'breezy.tests.test_repository',
 
4014
        'breezy.tests.test_revert',
 
4015
        'breezy.tests.test_revision',
 
4016
        'breezy.tests.test_revisionspec',
 
4017
        'breezy.tests.test_revisiontree',
 
4018
        'breezy.tests.test_rio',
 
4019
        'breezy.tests.test_rules',
 
4020
        'breezy.tests.test_url_policy_open',
 
4021
        'breezy.tests.test_sampler',
 
4022
        'breezy.tests.test_scenarios',
 
4023
        'breezy.tests.test_script',
 
4024
        'breezy.tests.test_selftest',
 
4025
        'breezy.tests.test_serializer',
 
4026
        'breezy.tests.test_setup',
 
4027
        'breezy.tests.test_sftp_transport',
 
4028
        'breezy.tests.test_shelf',
 
4029
        'breezy.tests.test_shelf_ui',
 
4030
        'breezy.tests.test_smart',
 
4031
        'breezy.tests.test_smart_add',
 
4032
        'breezy.tests.test_smart_request',
 
4033
        'breezy.tests.test_smart_signals',
 
4034
        'breezy.tests.test_smart_transport',
 
4035
        'breezy.tests.test_smtp_connection',
 
4036
        'breezy.tests.test_source',
 
4037
        'breezy.tests.test_ssh_transport',
 
4038
        'breezy.tests.test_status',
 
4039
        'breezy.tests.test_store',
 
4040
        'breezy.tests.test_strace',
 
4041
        'breezy.tests.test_subsume',
 
4042
        'breezy.tests.test_switch',
 
4043
        'breezy.tests.test_symbol_versioning',
 
4044
        'breezy.tests.test_tag',
 
4045
        'breezy.tests.test_test_server',
 
4046
        'breezy.tests.test_testament',
 
4047
        'breezy.tests.test_textfile',
 
4048
        'breezy.tests.test_textmerge',
 
4049
        'breezy.tests.test_cethread',
 
4050
        'breezy.tests.test_timestamp',
 
4051
        'breezy.tests.test_trace',
 
4052
        'breezy.tests.test_transactions',
 
4053
        'breezy.tests.test_transform',
 
4054
        'breezy.tests.test_transport',
 
4055
        'breezy.tests.test_transport_log',
 
4056
        'breezy.tests.test_tree',
 
4057
        'breezy.tests.test_treebuilder',
 
4058
        'breezy.tests.test_treeshape',
 
4059
        'breezy.tests.test_tsort',
 
4060
        'breezy.tests.test_tuned_gzip',
 
4061
        'breezy.tests.test_ui',
 
4062
        'breezy.tests.test_uncommit',
 
4063
        'breezy.tests.test_upgrade',
 
4064
        'breezy.tests.test_upgrade_stacked',
 
4065
        'breezy.tests.test_upstream_import',
 
4066
        'breezy.tests.test_urlutils',
 
4067
        'breezy.tests.test_utextwrap',
 
4068
        'breezy.tests.test_version',
 
4069
        'breezy.tests.test_version_info',
 
4070
        'breezy.tests.test_versionedfile',
 
4071
        'breezy.tests.test_vf_search',
 
4072
        'breezy.tests.test_weave',
 
4073
        'breezy.tests.test_whitebox',
 
4074
        'breezy.tests.test_win32utils',
 
4075
        'breezy.tests.test_workingtree',
 
4076
        'breezy.tests.test_workingtree_4',
 
4077
        'breezy.tests.test_wsgi',
 
4078
        'breezy.tests.test_xml',
 
4079
        ]
 
4080
 
 
4081
 
 
4082
def _test_suite_modules_to_doctest():
 
4083
    """Return the list of modules to doctest."""
 
4084
    if __doc__ is None:
 
4085
        # GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
 
4086
        return []
 
4087
    return [
 
4088
        'breezy',
 
4089
        'breezy.branchbuilder',
 
4090
        'breezy.decorators',
 
4091
        'breezy.inventory',
 
4092
        'breezy.iterablefile',
 
4093
        'breezy.lockdir',
 
4094
        'breezy.merge3',
 
4095
        'breezy.option',
 
4096
        'breezy.pyutils',
 
4097
        'breezy.symbol_versioning',
 
4098
        'breezy.tests',
 
4099
        'breezy.tests.fixtures',
 
4100
        'breezy.timestamp',
 
4101
        'breezy.transport.http',
 
4102
        'breezy.version_info_formats.format_custom',
 
4103
        ]
 
4104
 
 
4105
 
 
4106
def test_suite(keep_only=None, starting_with=None):
 
4107
    """Build and return TestSuite for the whole of breezy.
 
4108
 
 
4109
    :param keep_only: A list of test ids limiting the suite returned.
 
4110
 
 
4111
    :param starting_with: An id limiting the suite returned to the tests
 
4112
         starting with it.
 
4113
 
 
4114
    This function can be replaced if you need to change the default test
 
4115
    suite on a global basis, but it is not encouraged.
 
4116
    """
 
4117
 
 
4118
    loader = TestUtil.TestLoader()
 
4119
 
 
4120
    if keep_only is not None:
 
4121
        id_filter = TestIdList(keep_only)
 
4122
    if starting_with:
 
4123
        # We take precedence over keep_only because *at loading time* using
 
4124
        # both options means we will load less tests for the same final result.
 
4125
        def interesting_module(name):
 
4126
            for start in starting_with:
 
4127
                if (
 
4128
                    # Either the module name starts with the specified string
 
4129
                    name.startswith(start)
 
4130
                    # or it may contain tests starting with the specified string
 
4131
                    or start.startswith(name)
 
4132
                    ):
 
4133
                    return True
 
4134
            return False
 
4135
        loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
 
4136
 
 
4137
    elif keep_only is not None:
 
4138
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
 
4139
        def interesting_module(name):
 
4140
            return id_filter.refers_to(name)
 
4141
 
 
4142
    else:
 
4143
        loader = TestUtil.TestLoader()
 
4144
        def interesting_module(name):
 
4145
            # No filtering, all modules are interesting
 
4146
            return True
 
4147
 
 
4148
    suite = loader.suiteClass()
 
4149
 
 
4150
    # modules building their suite with loadTestsFromModuleNames
 
4151
    suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
 
4152
 
 
4153
    for mod in _test_suite_modules_to_doctest():
 
4154
        if not interesting_module(mod):
 
4155
            # No tests to keep here, move along
 
4156
            continue
 
4157
        try:
 
4158
            # note that this really does mean "report only" -- doctest
 
4159
            # still runs the rest of the examples
 
4160
            doc_suite = IsolatedDocTestSuite(
 
4161
                mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
4162
        except ValueError as e:
 
4163
            print('**failed to get doctest for: %s\n%s' % (mod, e))
 
4164
            raise
 
4165
        if len(doc_suite._tests) == 0:
 
4166
            raise errors.BzrError("no doctests found in %s" % (mod,))
 
4167
        suite.addTest(doc_suite)
 
4168
 
 
4169
    default_encoding = sys.getdefaultencoding()
 
4170
    for name, plugin in _mod_plugin.plugins().items():
 
4171
        if not interesting_module(plugin.module.__name__):
 
4172
            continue
 
4173
        plugin_suite = plugin.test_suite()
 
4174
        # We used to catch ImportError here and turn it into just a warning,
 
4175
        # but really if you don't have --no-plugins this should be a failure.
 
4176
        # mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
 
4177
        if plugin_suite is None:
 
4178
            plugin_suite = plugin.load_plugin_tests(loader)
 
4179
        if plugin_suite is not None:
 
4180
            suite.addTest(plugin_suite)
 
4181
        if default_encoding != sys.getdefaultencoding():
 
4182
            trace.warning(
 
4183
                'Plugin "%s" tried to reset default encoding to: %s', name,
 
4184
                sys.getdefaultencoding())
 
4185
            reload(sys)
 
4186
            sys.setdefaultencoding(default_encoding)
 
4187
 
 
4188
    if keep_only is not None:
 
4189
        # Now that the referred modules have loaded their tests, keep only the
 
4190
        # requested ones.
 
4191
        suite = filter_suite_by_id_list(suite, id_filter)
 
4192
        # Do some sanity checks on the id_list filtering
 
4193
        not_found, duplicates = suite_matches_id_list(suite, keep_only)
 
4194
        if starting_with:
 
4195
            # The tester has used both keep_only and starting_with, so he is
 
4196
            # already aware that some tests are excluded from the list, there
 
4197
            # is no need to tell him which.
 
4198
            pass
 
4199
        else:
 
4200
            # Some tests mentioned in the list are not in the test suite. The
 
4201
            # list may be out of date, report to the tester.
 
4202
            for id in not_found:
 
4203
                trace.warning('"%s" not found in the test suite', id)
 
4204
        for id in duplicates:
 
4205
            trace.warning('"%s" is used as an id by several tests', id)
 
4206
 
 
4207
    return suite
 
4208
 
 
4209
 
 
4210
def multiply_scenarios(*scenarios):
 
4211
    """Multiply two or more iterables of scenarios.
 
4212
 
 
4213
    It is safe to pass scenario generators or iterators.
 
4214
 
 
4215
    :returns: A list of compound scenarios: the cross-product of all
 
4216
        scenarios, with the names concatenated and the parameters
 
4217
        merged together.
 
4218
    """
 
4219
    return functools.reduce(_multiply_two_scenarios, map(list, scenarios))
 
4220
 
 
4221
 
 
4222
def _multiply_two_scenarios(scenarios_left, scenarios_right):
 
4223
    """Multiply two sets of scenarios.
 
4224
 
 
4225
    :returns: the cartesian product of the two sets of scenarios, that is
 
4226
        a scenario for every possible combination of a left scenario and a
 
4227
        right scenario.
 
4228
    """
 
4229
    return [
 
4230
        ('%s,%s' % (left_name, right_name),
 
4231
         dict(left_dict, **right_dict))
 
4232
        for left_name, left_dict in scenarios_left
 
4233
        for right_name, right_dict in scenarios_right]
 
4234
 
 
4235
 
 
4236
def multiply_tests(tests, scenarios, result):
 
4237
    """Multiply tests_list by scenarios into result.
 
4238
 
 
4239
    This is the core workhorse for test parameterisation.
 
4240
 
 
4241
    Typically the load_tests() method for a per-implementation test suite will
 
4242
    call multiply_tests and return the result.
 
4243
 
 
4244
    :param tests: The tests to parameterise.
 
4245
    :param scenarios: The scenarios to apply: pairs of (scenario_name,
 
4246
        scenario_param_dict).
 
4247
    :param result: A TestSuite to add created tests to.
 
4248
 
 
4249
    This returns the passed in result TestSuite with the cross product of all
 
4250
    the tests repeated once for each scenario.  Each test is adapted by adding
 
4251
    the scenario name at the end of its id(), and updating the test object's
 
4252
    __dict__ with the scenario_param_dict.
 
4253
 
 
4254
    >>> import breezy.tests.test_sampler
 
4255
    >>> r = multiply_tests(
 
4256
    ...     breezy.tests.test_sampler.DemoTest('test_nothing'),
 
4257
    ...     [('one', dict(param=1)),
 
4258
    ...      ('two', dict(param=2))],
 
4259
    ...     TestUtil.TestSuite())
 
4260
    >>> tests = list(iter_suite_tests(r))
 
4261
    >>> len(tests)
 
4262
    2
 
4263
    >>> tests[0].id()
 
4264
    'breezy.tests.test_sampler.DemoTest.test_nothing(one)'
 
4265
    >>> tests[0].param
 
4266
    1
 
4267
    >>> tests[1].param
 
4268
    2
 
4269
    """
 
4270
    for test in iter_suite_tests(tests):
 
4271
        apply_scenarios(test, scenarios, result)
 
4272
    return result
 
4273
 
 
4274
 
 
4275
def apply_scenarios(test, scenarios, result):
 
4276
    """Apply the scenarios in scenarios to test and add to result.
 
4277
 
 
4278
    :param test: The test to apply scenarios to.
 
4279
    :param scenarios: An iterable of scenarios to apply to test.
 
4280
    :return: result
 
4281
    :seealso: apply_scenario
 
4282
    """
 
4283
    for scenario in scenarios:
 
4284
        result.addTest(apply_scenario(test, scenario))
 
4285
    return result
 
4286
 
 
4287
 
 
4288
def apply_scenario(test, scenario):
 
4289
    """Copy test and apply scenario to it.
 
4290
 
 
4291
    :param test: A test to adapt.
 
4292
    :param scenario: A tuple describing the scenario.
 
4293
        The first element of the tuple is the new test id.
 
4294
        The second element is a dict containing attributes to set on the
 
4295
        test.
 
4296
    :return: The adapted test.
 
4297
    """
 
4298
    new_id = "%s(%s)" % (test.id(), scenario[0])
 
4299
    new_test = clone_test(test, new_id)
 
4300
    for name, value in scenario[1].items():
 
4301
        setattr(new_test, name, value)
 
4302
    return new_test
 
4303
 
 
4304
 
 
4305
def clone_test(test, new_id):
 
4306
    """Clone a test giving it a new id.
 
4307
 
 
4308
    :param test: The test to clone.
 
4309
    :param new_id: The id to assign to it.
 
4310
    :return: The new test.
 
4311
    """
 
4312
    new_test = copy.copy(test)
 
4313
    new_test.id = lambda: new_id
 
4314
    # XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
 
4315
    # causes cloned tests to share the 'details' dict.  This makes it hard to
 
4316
    # read the test output for parameterized tests, because tracebacks will be
 
4317
    # associated with irrelevant tests.
 
4318
    try:
 
4319
        details = new_test._TestCase__details
 
4320
    except AttributeError:
 
4321
        # must be a different version of testtools than expected.  Do nothing.
 
4322
        pass
 
4323
    else:
 
4324
        # Reset the '__details' dict.
 
4325
        new_test._TestCase__details = {}
 
4326
    return new_test
 
4327
 
 
4328
 
 
4329
def permute_tests_for_extension(standard_tests, loader, py_module_name,
 
4330
                                ext_module_name):
 
4331
    """Helper for permutating tests against an extension module.
 
4332
 
 
4333
    This is meant to be used inside a modules 'load_tests()' function. It will
 
4334
    create 2 scenarios, and cause all tests in the 'standard_tests' to be run
 
4335
    against both implementations. Setting 'test.module' to the appropriate
 
4336
    module. See breezy.tests.test__chk_map.load_tests as an example.
 
4337
 
 
4338
    :param standard_tests: A test suite to permute
 
4339
    :param loader: A TestLoader
 
4340
    :param py_module_name: The python path to a python module that can always
 
4341
        be loaded, and will be considered the 'python' implementation. (eg
 
4342
        'breezy._chk_map_py')
 
4343
    :param ext_module_name: The python path to an extension module. If the
 
4344
        module cannot be loaded, a single test will be added, which notes that
 
4345
        the module is not available. If it can be loaded, all standard_tests
 
4346
        will be run against that module.
 
4347
    :return: (suite, feature) suite is a test-suite that has all the permuted
 
4348
        tests. feature is the Feature object that can be used to determine if
 
4349
        the module is available.
 
4350
    """
 
4351
 
 
4352
    from .features import ModuleAvailableFeature
 
4353
    py_module = pyutils.get_named_object(py_module_name)
 
4354
    scenarios = [
 
4355
        ('python', {'module': py_module}),
 
4356
    ]
 
4357
    suite = loader.suiteClass()
 
4358
    feature = ModuleAvailableFeature(ext_module_name)
 
4359
    if feature.available():
 
4360
        scenarios.append(('C', {'module': feature.module}))
 
4361
    else:
 
4362
        # the compiled module isn't available, so we add a failing test
 
4363
        class FailWithoutFeature(TestCase):
 
4364
            def test_fail(self):
 
4365
                self.requireFeature(feature)
 
4366
        suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
 
4367
    result = multiply_tests(standard_tests, scenarios, suite)
 
4368
    return result, feature
 
4369
 
 
4370
 
 
4371
def _rmtree_temp_dir(dirname, test_id=None):
 
4372
    # If LANG=C we probably have created some bogus paths
 
4373
    # which rmtree(unicode) will fail to delete
 
4374
    # so make sure we are using rmtree(str) to delete everything
 
4375
    # except on win32, where rmtree(str) will fail
 
4376
    # since it doesn't have the property of byte-stream paths
 
4377
    # (they are either ascii or mbcs)
 
4378
    if sys.platform == 'win32':
 
4379
        # make sure we are using the unicode win32 api
 
4380
        dirname = text_type(dirname)
 
4381
    else:
 
4382
        dirname = dirname.encode(sys.getfilesystemencoding())
 
4383
    try:
 
4384
        osutils.rmtree(dirname)
 
4385
    except OSError as e:
 
4386
        # We don't want to fail here because some useful display will be lost
 
4387
        # otherwise. Polluting the tmp dir is bad, but not giving all the
 
4388
        # possible info to the test runner is even worse.
 
4389
        if test_id != None:
 
4390
            ui.ui_factory.clear_term()
 
4391
            sys.stderr.write('\nWhile running: %s\n' % (test_id,))
 
4392
        # Ugly, but the last thing we want here is fail, so bear with it.
 
4393
        printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
 
4394
                                    ).encode('ascii', 'replace')
 
4395
        sys.stderr.write('Unable to remove testing dir %s\n%s'
 
4396
                         % (os.path.basename(dirname), printable_e))
 
4397
 
 
4398
 
 
4399
def probe_unicode_in_user_encoding():
 
4400
    """Try to encode several unicode strings to use in unicode-aware tests.
 
4401
    Return first successfull match.
 
4402
 
 
4403
    :return:  (unicode value, encoded plain string value) or (None, None)
 
4404
    """
 
4405
    possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
 
4406
    for uni_val in possible_vals:
 
4407
        try:
 
4408
            str_val = uni_val.encode(osutils.get_user_encoding())
 
4409
        except UnicodeEncodeError:
 
4410
            # Try a different character
 
4411
            pass
 
4412
        else:
 
4413
            return uni_val, str_val
 
4414
    return None, None
 
4415
 
 
4416
 
 
4417
def probe_bad_non_ascii(encoding):
 
4418
    """Try to find [bad] character with code [128..255]
 
4419
    that cannot be decoded to unicode in some encoding.
 
4420
    Return None if all non-ascii characters is valid
 
4421
    for given encoding.
 
4422
    """
 
4423
    for i in range(128, 256):
 
4424
        char = chr(i)
 
4425
        try:
 
4426
            char.decode(encoding)
 
4427
        except UnicodeDecodeError:
 
4428
            return char
 
4429
    return None
 
4430
 
 
4431
 
 
4432
# Only define SubUnitBzrRunner if subunit is available.
 
4433
try:
 
4434
    from subunit import TestProtocolClient
 
4435
    from subunit.test_results import AutoTimingTestResultDecorator
 
4436
    class SubUnitBzrProtocolClient(TestProtocolClient):
 
4437
 
 
4438
        def stopTest(self, test):
 
4439
            super(SubUnitBzrProtocolClient, self).stopTest(test)
 
4440
            _clear__type_equality_funcs(test)
 
4441
 
 
4442
        def addSuccess(self, test, details=None):
 
4443
            # The subunit client always includes the details in the subunit
 
4444
            # stream, but we don't want to include it in ours.
 
4445
            if details is not None and 'log' in details:
 
4446
                del details['log']
 
4447
            return super(SubUnitBzrProtocolClient, self).addSuccess(
 
4448
                test, details)
 
4449
 
 
4450
    class SubUnitBzrRunner(TextTestRunner):
 
4451
        def run(self, test):
 
4452
            result = AutoTimingTestResultDecorator(
 
4453
                SubUnitBzrProtocolClient(self.stream))
 
4454
            test.run(result)
 
4455
            return result
 
4456
except ImportError:
 
4457
    pass