/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-07-30 18:38:48 UTC
  • mfrom: (6740.1.1 breezy-conf-1)
  • Revision ID: jelmer@jelmer.uk-20170730183848-195b9ch7sclkxmqs
Merge lp:~jelmer/brz/breezy-conf

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