~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Martin Pool
  • Date: 2009-07-19 01:05:42 UTC
  • mto: This revision was merged to the branch mainline in revision 4558.
  • Revision ID: mbp@sourcefrog.net-20090719010542-34bzx1i5ynfvs6zd
TextUIFactory should cope with EOF when in get_boolean

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 by Canonical Ltd
2
 
 
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
 
 
7
#
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
 
 
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
 
18
 
from testsweet import TestBase, run_suite, InTempDir
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
# TODO: Perhaps there should be an API to find out if bzr running under the
 
19
# test suite -- some plugins might want to avoid making intrusive changes if
 
20
# this is the case.  However, we want behaviour under to test to diverge as
 
21
# little as possible, so this should be used rarely if it's added at all.
 
22
# (Suggestion from j-a-meinel, 2005-11-24)
 
23
 
 
24
# NOTE: Some classes in here use camelCaseNaming() rather than
 
25
# underscore_naming().  That's for consistency with unittest; it's not the
 
26
# general style of bzrlib.  Please continue that consistency when adding e.g.
 
27
# new assertFoo() methods.
 
28
 
 
29
import atexit
 
30
import codecs
 
31
from cStringIO import StringIO
 
32
import difflib
 
33
import doctest
 
34
import errno
 
35
import logging
 
36
import math
 
37
import os
 
38
from pprint import pformat
 
39
import random
 
40
import re
 
41
import shlex
 
42
import stat
 
43
from subprocess import Popen, PIPE, STDOUT
 
44
import sys
 
45
import tempfile
 
46
import threading
 
47
import time
 
48
import unittest
 
49
import warnings
 
50
 
 
51
 
 
52
from bzrlib import (
 
53
    branchbuilder,
 
54
    bzrdir,
 
55
    debug,
 
56
    errors,
 
57
    hooks,
 
58
    lock as _mod_lock,
 
59
    memorytree,
 
60
    osutils,
 
61
    progress,
 
62
    ui,
 
63
    urlutils,
 
64
    registry,
 
65
    workingtree,
 
66
    )
 
67
import bzrlib.branch
19
68
import bzrlib.commands
20
 
 
21
 
MODULES_TO_TEST = []
22
 
MODULES_TO_DOCTEST = []
23
 
 
24
 
 
25
 
class BzrTestBase(InTempDir):
26
 
    """bzr-specific test base class"""
27
 
    def run_bzr(self, *args, **kwargs):
28
 
        retcode = kwargs.get('retcode', 0)
29
 
        self.assertEquals(bzrlib.commands.run_bzr(args), retcode)
 
69
import bzrlib.timestamp
 
70
import bzrlib.export
 
71
import bzrlib.inventory
 
72
import bzrlib.iterablefile
 
73
import bzrlib.lockdir
 
74
try:
 
75
    import bzrlib.lsprof
 
76
except ImportError:
 
77
    # lsprof not available
 
78
    pass
 
79
from bzrlib.merge import merge_inner
 
80
import bzrlib.merge3
 
81
import bzrlib.plugin
 
82
from bzrlib.smart import client, request, server
 
83
import bzrlib.store
 
84
from bzrlib import symbol_versioning
 
85
from bzrlib.symbol_versioning import (
 
86
    DEPRECATED_PARAMETER,
 
87
    deprecated_function,
 
88
    deprecated_method,
 
89
    deprecated_passed,
 
90
    )
 
91
import bzrlib.trace
 
92
from bzrlib.transport import get_transport
 
93
import bzrlib.transport
 
94
from bzrlib.transport.local import LocalURLServer
 
95
from bzrlib.transport.memory import MemoryServer
 
96
from bzrlib.transport.readonly import ReadonlyServer
 
97
from bzrlib.trace import mutter, note
 
98
from bzrlib.tests import TestUtil
 
99
from bzrlib.tests.http_server import HttpServer
 
100
from bzrlib.tests.TestUtil import (
 
101
                          TestSuite,
 
102
                          TestLoader,
 
103
                          )
 
104
from bzrlib.tests.treeshape import build_tree_contents
 
105
from bzrlib.ui.text import TextUIFactory
 
106
import bzrlib.version_info_formats.format_custom
 
107
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
 
108
 
 
109
# Mark this python module as being part of the implementation
 
110
# of unittest: this gives us better tracebacks where the last
 
111
# shown frame is the test code, not our assertXYZ.
 
112
__unittest = 1
 
113
 
 
114
default_transport = LocalURLServer
 
115
 
 
116
 
 
117
class ExtendedTestResult(unittest._TextTestResult):
 
118
    """Accepts, reports and accumulates the results of running tests.
 
119
 
 
120
    Compared to the unittest version this class adds support for
 
121
    profiling, benchmarking, stopping as soon as a test fails,  and
 
122
    skipping tests.  There are further-specialized subclasses for
 
123
    different types of display.
 
124
 
 
125
    When a test finishes, in whatever way, it calls one of the addSuccess,
 
126
    addFailure or addError classes.  These in turn may redirect to a more
 
127
    specific case for the special test results supported by our extended
 
128
    tests.
 
129
 
 
130
    Note that just one of these objects is fed the results from many tests.
 
131
    """
 
132
 
 
133
    stop_early = False
 
134
 
 
135
    def __init__(self, stream, descriptions, verbosity,
 
136
                 bench_history=None,
 
137
                 num_tests=None,
 
138
                 strict=False,
 
139
                 ):
 
140
        """Construct new TestResult.
 
141
 
 
142
        :param bench_history: Optionally, a writable file object to accumulate
 
143
            benchmark results.
 
144
        """
 
145
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
146
        if bench_history is not None:
 
147
            from bzrlib.version import _get_bzr_source_tree
 
148
            src_tree = _get_bzr_source_tree()
 
149
            if src_tree:
 
150
                try:
 
151
                    revision_id = src_tree.get_parent_ids()[0]
 
152
                except IndexError:
 
153
                    # XXX: if this is a brand new tree, do the same as if there
 
154
                    # is no branch.
 
155
                    revision_id = ''
 
156
            else:
 
157
                # XXX: If there's no branch, what should we do?
 
158
                revision_id = ''
 
159
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
 
160
        self._bench_history = bench_history
 
161
        self.ui = ui.ui_factory
 
162
        self.num_tests = num_tests
 
163
        self.error_count = 0
 
164
        self.failure_count = 0
 
165
        self.known_failure_count = 0
 
166
        self.skip_count = 0
 
167
        self.not_applicable_count = 0
 
168
        self.unsupported = {}
 
169
        self.count = 0
 
170
        self._overall_start_time = time.time()
 
171
        self._strict = strict
 
172
 
 
173
    def done(self):
 
174
        if self._strict:
 
175
            ok = self.wasStrictlySuccessful()
 
176
        else:
 
177
            ok = self.wasSuccessful()
 
178
        if ok:
 
179
            self.stream.write('tests passed\n')
 
180
        else:
 
181
            self.stream.write('tests failed\n')
 
182
        if TestCase._first_thread_leaker_id:
 
183
            self.stream.write(
 
184
                '%s is leaking threads among %d leaking tests.\n' % (
 
185
                TestCase._first_thread_leaker_id,
 
186
                TestCase._leaking_threads_tests))
 
187
 
 
188
    def _extractBenchmarkTime(self, testCase):
 
189
        """Add a benchmark time for the current test case."""
 
190
        return getattr(testCase, "_benchtime", None)
 
191
 
 
192
    def _elapsedTestTimeString(self):
 
193
        """Return a time string for the overall time the current test has taken."""
 
194
        return self._formatTime(time.time() - self._start_time)
 
195
 
 
196
    def _testTimeString(self, testCase):
 
197
        benchmark_time = self._extractBenchmarkTime(testCase)
 
198
        if benchmark_time is not None:
 
199
            return "%s/%s" % (
 
200
                self._formatTime(benchmark_time),
 
201
                self._elapsedTestTimeString())
 
202
        else:
 
203
            return "           %s" % self._elapsedTestTimeString()
 
204
 
 
205
    def _formatTime(self, seconds):
 
206
        """Format seconds as milliseconds with leading spaces."""
 
207
        # some benchmarks can take thousands of seconds to run, so we need 8
 
208
        # places
 
209
        return "%8dms" % (1000 * seconds)
 
210
 
 
211
    def _shortened_test_description(self, test):
 
212
        what = test.id()
 
213
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
214
        return what
 
215
 
 
216
    def startTest(self, test):
 
217
        unittest.TestResult.startTest(self, test)
 
218
        if self.count == 0:
 
219
            self.startTests()
 
220
        self.report_test_start(test)
 
221
        test.number = self.count
 
222
        self._recordTestStartTime()
 
223
 
 
224
    def startTests(self):
 
225
        self.stream.write(
 
226
            'testing: %s\n' % (osutils.realpath(sys.argv[0]),))
 
227
        self.stream.write(
 
228
            '   %s (%s python%s)\n' % (
 
229
                    bzrlib.__path__[0],
 
230
                    bzrlib.version_string,
 
231
                    bzrlib._format_version_tuple(sys.version_info),
 
232
                    ))
 
233
        self.stream.write('\n')
 
234
 
 
235
    def _recordTestStartTime(self):
 
236
        """Record that a test has started."""
 
237
        self._start_time = time.time()
 
238
 
 
239
    def _cleanupLogFile(self, test):
 
240
        # We can only do this if we have one of our TestCases, not if
 
241
        # we have a doctest.
 
242
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
 
243
        if setKeepLogfile is not None:
 
244
            setKeepLogfile()
 
245
 
 
246
    def addError(self, test, err):
 
247
        """Tell result that test finished with an error.
 
248
 
 
249
        Called from the TestCase run() method when the test
 
250
        fails with an unexpected error.
 
251
        """
 
252
        self._testConcluded(test)
 
253
        if isinstance(err[1], TestNotApplicable):
 
254
            return self._addNotApplicable(test, err)
 
255
        elif isinstance(err[1], UnavailableFeature):
 
256
            return self.addNotSupported(test, err[1].args[0])
 
257
        else:
 
258
            unittest.TestResult.addError(self, test, err)
 
259
            self.error_count += 1
 
260
            self.report_error(test, err)
 
261
            if self.stop_early:
 
262
                self.stop()
 
263
            self._cleanupLogFile(test)
 
264
 
 
265
    def addFailure(self, test, err):
 
266
        """Tell result that test failed.
 
267
 
 
268
        Called from the TestCase run() method when the test
 
269
        fails because e.g. an assert() method failed.
 
270
        """
 
271
        self._testConcluded(test)
 
272
        if isinstance(err[1], KnownFailure):
 
273
            return self._addKnownFailure(test, err)
 
274
        else:
 
275
            unittest.TestResult.addFailure(self, test, err)
 
276
            self.failure_count += 1
 
277
            self.report_failure(test, err)
 
278
            if self.stop_early:
 
279
                self.stop()
 
280
            self._cleanupLogFile(test)
 
281
 
 
282
    def addSuccess(self, test):
 
283
        """Tell result that test completed successfully.
 
284
 
 
285
        Called from the TestCase run()
 
286
        """
 
287
        self._testConcluded(test)
 
288
        if self._bench_history is not None:
 
289
            benchmark_time = self._extractBenchmarkTime(test)
 
290
            if benchmark_time is not None:
 
291
                self._bench_history.write("%s %s\n" % (
 
292
                    self._formatTime(benchmark_time),
 
293
                    test.id()))
 
294
        self.report_success(test)
 
295
        self._cleanupLogFile(test)
 
296
        unittest.TestResult.addSuccess(self, test)
 
297
        test._log_contents = ''
 
298
 
 
299
    def _testConcluded(self, test):
 
300
        """Common code when a test has finished.
 
301
 
 
302
        Called regardless of whether it succeded, failed, etc.
 
303
        """
 
304
        pass
 
305
 
 
306
    def _addKnownFailure(self, test, err):
 
307
        self.known_failure_count += 1
 
308
        self.report_known_failure(test, err)
 
309
 
 
310
    def addNotSupported(self, test, feature):
 
311
        """The test will not be run because of a missing feature.
 
312
        """
 
313
        # this can be called in two different ways: it may be that the
 
314
        # test started running, and then raised (through addError)
 
315
        # UnavailableFeature.  Alternatively this method can be called
 
316
        # while probing for features before running the tests; in that
 
317
        # case we will see startTest and stopTest, but the test will never
 
318
        # actually run.
 
319
        self.unsupported.setdefault(str(feature), 0)
 
320
        self.unsupported[str(feature)] += 1
 
321
        self.report_unsupported(test, feature)
 
322
 
 
323
    def addSkip(self, test, reason):
 
324
        """A test has not run for 'reason'."""
 
325
        self.skip_count += 1
 
326
        self.report_skip(test, reason)
 
327
 
 
328
    def _addNotApplicable(self, test, skip_excinfo):
 
329
        if isinstance(skip_excinfo[1], TestNotApplicable):
 
330
            self.not_applicable_count += 1
 
331
            self.report_not_applicable(test, skip_excinfo)
 
332
        try:
 
333
            test.tearDown()
 
334
        except KeyboardInterrupt:
 
335
            raise
 
336
        except:
 
337
            self.addError(test, test.exc_info())
 
338
        else:
 
339
            # seems best to treat this as success from point-of-view of unittest
 
340
            # -- it actually does nothing so it barely matters :)
 
341
            unittest.TestResult.addSuccess(self, test)
 
342
            test._log_contents = ''
 
343
 
 
344
    def printErrorList(self, flavour, errors):
 
345
        for test, err in errors:
 
346
            self.stream.writeln(self.separator1)
 
347
            self.stream.write("%s: " % flavour)
 
348
            self.stream.writeln(self.getDescription(test))
 
349
            if getattr(test, '_get_log', None) is not None:
 
350
                self.stream.write('\n')
 
351
                self.stream.write(
 
352
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
 
353
                self.stream.write('\n')
 
354
                self.stream.write(test._get_log())
 
355
                self.stream.write('\n')
 
356
                self.stream.write(
 
357
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
 
358
                self.stream.write('\n')
 
359
            self.stream.writeln(self.separator2)
 
360
            self.stream.writeln("%s" % err)
 
361
 
 
362
    def finished(self):
 
363
        pass
 
364
 
 
365
    def report_cleaning_up(self):
 
366
        pass
 
367
 
 
368
    def report_success(self, test):
 
369
        pass
 
370
 
 
371
    def wasStrictlySuccessful(self):
 
372
        if self.unsupported or self.known_failure_count:
 
373
            return False
 
374
        return self.wasSuccessful()
 
375
 
 
376
 
 
377
class TextTestResult(ExtendedTestResult):
 
378
    """Displays progress and results of tests in text form"""
 
379
 
 
380
    def __init__(self, stream, descriptions, verbosity,
 
381
                 bench_history=None,
 
382
                 num_tests=None,
 
383
                 pb=None,
 
384
                 strict=None,
 
385
                 ):
 
386
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
 
387
            bench_history, num_tests, strict)
 
388
        if pb is None:
 
389
            self.pb = self.ui.nested_progress_bar()
 
390
            self._supplied_pb = False
 
391
        else:
 
392
            self.pb = pb
 
393
            self._supplied_pb = True
 
394
        self.pb.show_pct = False
 
395
        self.pb.show_spinner = False
 
396
        self.pb.show_eta = False,
 
397
        self.pb.show_count = False
 
398
        self.pb.show_bar = False
 
399
 
 
400
    def report_starting(self):
 
401
        self.pb.update('[test 0/%d] Starting' % (self.num_tests))
 
402
 
 
403
    def _progress_prefix_text(self):
 
404
        # the longer this text, the less space we have to show the test
 
405
        # name...
 
406
        a = '[%d' % self.count              # total that have been run
 
407
        # tests skipped as known not to be relevant are not important enough
 
408
        # to show here
 
409
        ## if self.skip_count:
 
410
        ##     a += ', %d skip' % self.skip_count
 
411
        ## if self.known_failure_count:
 
412
        ##     a += '+%dX' % self.known_failure_count
 
413
        if self.num_tests is not None:
 
414
            a +='/%d' % self.num_tests
 
415
        a += ' in '
 
416
        runtime = time.time() - self._overall_start_time
 
417
        if runtime >= 60:
 
418
            a += '%dm%ds' % (runtime / 60, runtime % 60)
 
419
        else:
 
420
            a += '%ds' % runtime
 
421
        if self.error_count:
 
422
            a += ', %d err' % self.error_count
 
423
        if self.failure_count:
 
424
            a += ', %d fail' % self.failure_count
 
425
        if self.unsupported:
 
426
            a += ', %d missing' % len(self.unsupported)
 
427
        a += ']'
 
428
        return a
 
429
 
 
430
    def report_test_start(self, test):
 
431
        self.count += 1
 
432
        self.pb.update(
 
433
                self._progress_prefix_text()
 
434
                + ' '
 
435
                + self._shortened_test_description(test))
 
436
 
 
437
    def _test_description(self, test):
 
438
        return self._shortened_test_description(test)
 
439
 
 
440
    def report_error(self, test, err):
 
441
        self.pb.note('ERROR: %s\n    %s\n',
 
442
            self._test_description(test),
 
443
            err[1],
 
444
            )
 
445
 
 
446
    def report_failure(self, test, err):
 
447
        self.pb.note('FAIL: %s\n    %s\n',
 
448
            self._test_description(test),
 
449
            err[1],
 
450
            )
 
451
 
 
452
    def report_known_failure(self, test, err):
 
453
        self.pb.note('XFAIL: %s\n%s\n',
 
454
            self._test_description(test), err[1])
 
455
 
 
456
    def report_skip(self, test, reason):
 
457
        pass
 
458
 
 
459
    def report_not_applicable(self, test, skip_excinfo):
 
460
        pass
 
461
 
 
462
    def report_unsupported(self, test, feature):
 
463
        """test cannot be run because feature is missing."""
 
464
 
 
465
    def report_cleaning_up(self):
 
466
        self.pb.update('Cleaning up')
 
467
 
 
468
    def finished(self):
 
469
        if not self._supplied_pb:
 
470
            self.pb.finished()
 
471
 
 
472
 
 
473
class VerboseTestResult(ExtendedTestResult):
 
474
    """Produce long output, with one line per test run plus times"""
 
475
 
 
476
    def _ellipsize_to_right(self, a_string, final_width):
 
477
        """Truncate and pad a string, keeping the right hand side"""
 
478
        if len(a_string) > final_width:
 
479
            result = '...' + a_string[3-final_width:]
 
480
        else:
 
481
            result = a_string
 
482
        return result.ljust(final_width)
 
483
 
 
484
    def report_starting(self):
 
485
        self.stream.write('running %d tests...\n' % self.num_tests)
 
486
 
 
487
    def report_test_start(self, test):
 
488
        self.count += 1
 
489
        name = self._shortened_test_description(test)
 
490
        # width needs space for 6 char status, plus 1 for slash, plus 2 10-char
 
491
        # numbers, plus a trailing blank
 
492
        # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
 
493
        self.stream.write(self._ellipsize_to_right(name,
 
494
                          osutils.terminal_width()-30))
 
495
        self.stream.flush()
 
496
 
 
497
    def _error_summary(self, err):
 
498
        indent = ' ' * 4
 
499
        return '%s%s' % (indent, err[1])
 
500
 
 
501
    def report_error(self, test, err):
 
502
        self.stream.writeln('ERROR %s\n%s'
 
503
                % (self._testTimeString(test),
 
504
                   self._error_summary(err)))
 
505
 
 
506
    def report_failure(self, test, err):
 
507
        self.stream.writeln(' FAIL %s\n%s'
 
508
                % (self._testTimeString(test),
 
509
                   self._error_summary(err)))
 
510
 
 
511
    def report_known_failure(self, test, err):
 
512
        self.stream.writeln('XFAIL %s\n%s'
 
513
                % (self._testTimeString(test),
 
514
                   self._error_summary(err)))
 
515
 
 
516
    def report_success(self, test):
 
517
        self.stream.writeln('   OK %s' % self._testTimeString(test))
 
518
        for bench_called, stats in getattr(test, '_benchcalls', []):
 
519
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
520
            stats.pprint(file=self.stream)
 
521
        # flush the stream so that we get smooth output. This verbose mode is
 
522
        # used to show the output in PQM.
 
523
        self.stream.flush()
 
524
 
 
525
    def report_skip(self, test, reason):
 
526
        self.stream.writeln(' SKIP %s\n%s'
 
527
                % (self._testTimeString(test), reason))
 
528
 
 
529
    def report_not_applicable(self, test, skip_excinfo):
 
530
        self.stream.writeln('  N/A %s\n%s'
 
531
                % (self._testTimeString(test),
 
532
                   self._error_summary(skip_excinfo)))
 
533
 
 
534
    def report_unsupported(self, test, feature):
 
535
        """test cannot be run because feature is missing."""
 
536
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
 
537
                %(self._testTimeString(test), feature))
 
538
 
 
539
 
 
540
class TextTestRunner(object):
 
541
    stop_on_failure = False
 
542
 
 
543
    def __init__(self,
 
544
                 stream=sys.stderr,
 
545
                 descriptions=0,
 
546
                 verbosity=1,
 
547
                 bench_history=None,
 
548
                 list_only=False,
 
549
                 strict=False,
 
550
                 ):
 
551
        self.stream = unittest._WritelnDecorator(stream)
 
552
        self.descriptions = descriptions
 
553
        self.verbosity = verbosity
 
554
        self._bench_history = bench_history
 
555
        self.list_only = list_only
 
556
        self._strict = strict
 
557
 
 
558
    def run(self, test):
 
559
        "Run the given test case or test suite."
 
560
        startTime = time.time()
 
561
        if self.verbosity == 1:
 
562
            result_class = TextTestResult
 
563
        elif self.verbosity >= 2:
 
564
            result_class = VerboseTestResult
 
565
        result = result_class(self.stream,
 
566
                              self.descriptions,
 
567
                              self.verbosity,
 
568
                              bench_history=self._bench_history,
 
569
                              num_tests=test.countTestCases(),
 
570
                              strict=self._strict,
 
571
                              )
 
572
        result.stop_early = self.stop_on_failure
 
573
        result.report_starting()
 
574
        if self.list_only:
 
575
            if self.verbosity >= 2:
 
576
                self.stream.writeln("Listing tests only ...\n")
 
577
            run = 0
 
578
            for t in iter_suite_tests(test):
 
579
                self.stream.writeln("%s" % (t.id()))
 
580
                run += 1
 
581
            return None
 
582
        else:
 
583
            try:
 
584
                import testtools
 
585
            except ImportError:
 
586
                test.run(result)
 
587
            else:
 
588
                if isinstance(test, testtools.ConcurrentTestSuite):
 
589
                    # We need to catch bzr specific behaviors
 
590
                    test.run(BZRTransformingResult(result))
 
591
                else:
 
592
                    test.run(result)
 
593
            run = result.testsRun
 
594
            actionTaken = "Ran"
 
595
        stopTime = time.time()
 
596
        timeTaken = stopTime - startTime
 
597
        result.printErrors()
 
598
        self.stream.writeln(result.separator2)
 
599
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
600
                            run, run != 1 and "s" or "", timeTaken))
 
601
        self.stream.writeln()
 
602
        if not result.wasSuccessful():
 
603
            self.stream.write("FAILED (")
 
604
            failed, errored = map(len, (result.failures, result.errors))
 
605
            if failed:
 
606
                self.stream.write("failures=%d" % failed)
 
607
            if errored:
 
608
                if failed: self.stream.write(", ")
 
609
                self.stream.write("errors=%d" % errored)
 
610
            if result.known_failure_count:
 
611
                if failed or errored: self.stream.write(", ")
 
612
                self.stream.write("known_failure_count=%d" %
 
613
                    result.known_failure_count)
 
614
            self.stream.writeln(")")
 
615
        else:
 
616
            if result.known_failure_count:
 
617
                self.stream.writeln("OK (known_failures=%d)" %
 
618
                    result.known_failure_count)
 
619
            else:
 
620
                self.stream.writeln("OK")
 
621
        if result.skip_count > 0:
 
622
            skipped = result.skip_count
 
623
            self.stream.writeln('%d test%s skipped' %
 
624
                                (skipped, skipped != 1 and "s" or ""))
 
625
        if result.unsupported:
 
626
            for feature, count in sorted(result.unsupported.items()):
 
627
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
628
                    (feature, count))
 
629
        result.finished()
 
630
        return result
 
631
 
 
632
 
 
633
def iter_suite_tests(suite):
 
634
    """Return all tests in a suite, recursing through nested suites"""
 
635
    if isinstance(suite, unittest.TestCase):
 
636
        yield suite
 
637
    elif isinstance(suite, unittest.TestSuite):
 
638
        for item in suite:
 
639
            for r in iter_suite_tests(item):
 
640
                yield r
 
641
    else:
 
642
        raise Exception('unknown type %r for object %r'
 
643
                        % (type(suite), suite))
 
644
 
 
645
 
 
646
class TestSkipped(Exception):
 
647
    """Indicates that a test was intentionally skipped, rather than failing."""
 
648
 
 
649
 
 
650
class TestNotApplicable(TestSkipped):
 
651
    """A test is not applicable to the situation where it was run.
 
652
 
 
653
    This is only normally raised by parameterized tests, if they find that
 
654
    the instance they're constructed upon does not support one aspect
 
655
    of its interface.
 
656
    """
 
657
 
 
658
 
 
659
class KnownFailure(AssertionError):
 
660
    """Indicates that a test failed in a precisely expected manner.
 
661
 
 
662
    Such failures dont block the whole test suite from passing because they are
 
663
    indicators of partially completed code or of future work. We have an
 
664
    explicit error for them so that we can ensure that they are always visible:
 
665
    KnownFailures are always shown in the output of bzr selftest.
 
666
    """
 
667
 
 
668
 
 
669
class UnavailableFeature(Exception):
 
670
    """A feature required for this test was not available.
 
671
 
 
672
    The feature should be used to construct the exception.
 
673
    """
 
674
 
 
675
 
 
676
class CommandFailed(Exception):
 
677
    pass
 
678
 
 
679
 
 
680
class StringIOWrapper(object):
 
681
    """A wrapper around cStringIO which just adds an encoding attribute.
 
682
 
 
683
    Internally we can check sys.stdout to see what the output encoding
 
684
    should be. However, cStringIO has no encoding attribute that we can
 
685
    set. So we wrap it instead.
 
686
    """
 
687
    encoding='ascii'
 
688
    _cstring = None
 
689
 
 
690
    def __init__(self, s=None):
 
691
        if s is not None:
 
692
            self.__dict__['_cstring'] = StringIO(s)
 
693
        else:
 
694
            self.__dict__['_cstring'] = StringIO()
 
695
 
 
696
    def __getattr__(self, name, getattr=getattr):
 
697
        return getattr(self.__dict__['_cstring'], name)
 
698
 
 
699
    def __setattr__(self, name, val):
 
700
        if name == 'encoding':
 
701
            self.__dict__['encoding'] = val
 
702
        else:
 
703
            return setattr(self._cstring, name, val)
 
704
 
 
705
 
 
706
class TestUIFactory(TextUIFactory):
 
707
    """A UI Factory for testing.
 
708
 
 
709
    Hide the progress bar but emit note()s.
 
710
    Redirect stdin.
 
711
    Allows get_password to be tested without real tty attached.
 
712
    """
 
713
 
 
714
    def __init__(self, stdout=None, stderr=None, stdin=None):
 
715
        if stdin is not None:
 
716
            # We use a StringIOWrapper to be able to test various
 
717
            # encodings, but the user is still responsible to
 
718
            # encode the string and to set the encoding attribute
 
719
            # of StringIOWrapper.
 
720
            stdin = StringIOWrapper(stdin)
 
721
        super(TestUIFactory, self).__init__(stdin, stdout, stderr)
 
722
 
 
723
    def clear(self):
 
724
        """See progress.ProgressBar.clear()."""
 
725
 
 
726
    def clear_term(self):
 
727
        """See progress.ProgressBar.clear_term()."""
 
728
 
 
729
    def finished(self):
 
730
        """See progress.ProgressBar.finished()."""
 
731
 
 
732
    def note(self, fmt_string, *args):
 
733
        """See progress.ProgressBar.note()."""
 
734
        if args:
 
735
            fmt_string = fmt_string % args
 
736
        self.stdout.write(fmt_string + "\n")
 
737
 
 
738
    def progress_bar(self):
 
739
        return self
 
740
 
 
741
    def nested_progress_bar(self):
 
742
        return self
 
743
 
 
744
    def update(self, message, count=None, total=None):
 
745
        """See progress.ProgressBar.update()."""
 
746
 
 
747
    def get_non_echoed_password(self):
 
748
        """Get password from stdin without trying to handle the echo mode"""
 
749
        password = self.stdin.readline()
 
750
        if not password:
 
751
            raise EOFError
 
752
        if password[-1] == '\n':
 
753
            password = password[:-1]
 
754
        return password
 
755
 
 
756
 
 
757
class TestCase(unittest.TestCase):
 
758
    """Base class for bzr unit tests.
 
759
 
 
760
    Tests that need access to disk resources should subclass
 
761
    TestCaseInTempDir not TestCase.
 
762
 
 
763
    Error and debug log messages are redirected from their usual
 
764
    location into a temporary file, the contents of which can be
 
765
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
 
766
    so that it can also capture file IO.  When the test completes this file
 
767
    is read into memory and removed from disk.
 
768
 
 
769
    There are also convenience functions to invoke bzr's command-line
 
770
    routine, and to build and check bzr trees.
 
771
 
 
772
    In addition to the usual method of overriding tearDown(), this class also
 
773
    allows subclasses to register functions into the _cleanups list, which is
 
774
    run in order as the object is torn down.  It's less likely this will be
 
775
    accidentally overlooked.
 
776
    """
 
777
 
 
778
    _active_threads = None
 
779
    _leaking_threads_tests = 0
 
780
    _first_thread_leaker_id = None
 
781
    _log_file_name = None
 
782
    _log_contents = ''
 
783
    _keep_log_file = False
 
784
    # record lsprof data when performing benchmark calls.
 
785
    _gather_lsprof_in_benchmarks = False
 
786
    attrs_to_keep = ('id', '_testMethodName', '_testMethodDoc',
 
787
                     '_log_contents', '_log_file_name', '_benchtime',
 
788
                     '_TestCase__testMethodName', '_TestCase__testMethodDoc',)
 
789
 
 
790
    def __init__(self, methodName='testMethod'):
 
791
        super(TestCase, self).__init__(methodName)
 
792
        self._cleanups = []
 
793
        self._bzr_test_setUp_run = False
 
794
        self._bzr_test_tearDown_run = False
 
795
 
 
796
    def setUp(self):
 
797
        unittest.TestCase.setUp(self)
 
798
        self._bzr_test_setUp_run = True
 
799
        self._cleanEnvironment()
 
800
        self._silenceUI()
 
801
        self._startLogFile()
 
802
        self._benchcalls = []
 
803
        self._benchtime = None
 
804
        self._clear_hooks()
 
805
        # Track locks - needs to be called before _clear_debug_flags.
 
806
        self._track_locks()
 
807
        self._clear_debug_flags()
 
808
        TestCase._active_threads = threading.activeCount()
 
809
        self.addCleanup(self._check_leaked_threads)
 
810
 
 
811
    def debug(self):
 
812
        # debug a frame up.
 
813
        import pdb
 
814
        pdb.Pdb().set_trace(sys._getframe().f_back)
 
815
 
 
816
    def _check_leaked_threads(self):
 
817
        active = threading.activeCount()
 
818
        leaked_threads = active - TestCase._active_threads
 
819
        TestCase._active_threads = active
 
820
        if leaked_threads:
 
821
            TestCase._leaking_threads_tests += 1
 
822
            if TestCase._first_thread_leaker_id is None:
 
823
                TestCase._first_thread_leaker_id = self.id()
 
824
 
 
825
    def _clear_debug_flags(self):
 
826
        """Prevent externally set debug flags affecting tests.
 
827
 
 
828
        Tests that want to use debug flags can just set them in the
 
829
        debug_flags set during setup/teardown.
 
830
        """
 
831
        self._preserved_debug_flags = set(debug.debug_flags)
 
832
        if 'allow_debug' not in selftest_debug_flags:
 
833
            debug.debug_flags.clear()
 
834
        self.addCleanup(self._restore_debug_flags)
 
835
 
 
836
    def _clear_hooks(self):
 
837
        # prevent hooks affecting tests
 
838
        self._preserved_hooks = {}
 
839
        for key, factory in hooks.known_hooks.items():
 
840
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
 
841
            current_hooks = hooks.known_hooks_key_to_object(key)
 
842
            self._preserved_hooks[parent] = (name, current_hooks)
 
843
        self.addCleanup(self._restoreHooks)
 
844
        for key, factory in hooks.known_hooks.items():
 
845
            parent, name = hooks.known_hooks_key_to_parent_and_attribute(key)
 
846
            setattr(parent, name, factory())
 
847
        # this hook should always be installed
 
848
        request._install_hook()
 
849
 
 
850
    def _silenceUI(self):
 
851
        """Turn off UI for duration of test"""
 
852
        # by default the UI is off; tests can turn it on if they want it.
 
853
        saved = ui.ui_factory
 
854
        def _restore():
 
855
            ui.ui_factory = saved
 
856
        ui.ui_factory = ui.SilentUIFactory()
 
857
        self.addCleanup(_restore)
 
858
 
 
859
    def _check_locks(self):
 
860
        """Check that all lock take/release actions have been paired."""
 
861
        # once we have fixed all the current lock problems, we can change the
 
862
        # following code to always check for mismatched locks, but only do
 
863
        # traceback showing with -Dlock (self._lock_check_thorough is True).
 
864
        # For now, because the test suite will fail, we only assert that lock
 
865
        # matching has occured with -Dlock.
 
866
        # unhook:
 
867
        acquired_locks = [lock for action, lock in self._lock_actions
 
868
                          if action == 'acquired']
 
869
        released_locks = [lock for action, lock in self._lock_actions
 
870
                          if action == 'released']
 
871
        broken_locks = [lock for action, lock in self._lock_actions
 
872
                        if action == 'broken']
 
873
        # trivially, given the tests for lock acquistion and release, if we
 
874
        # have as many in each list, it should be ok. Some lock tests also
 
875
        # break some locks on purpose and should be taken into account by
 
876
        # considering that breaking a lock is just a dirty way of releasing it.
 
877
        if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
 
878
            message = ('Different number of acquired and '
 
879
                       'released or broken locks. (%s, %s + %s)' %
 
880
                       (acquired_locks, released_locks, broken_locks))
 
881
            if not self._lock_check_thorough:
 
882
                # Rather than fail, just warn
 
883
                print "Broken test %s: %s" % (self, message)
 
884
                return
 
885
            self.fail(message)
 
886
 
 
887
    def _track_locks(self):
 
888
        """Track lock activity during tests."""
 
889
        self._lock_actions = []
 
890
        self._lock_check_thorough = 'lock' not in debug.debug_flags
 
891
        self.addCleanup(self._check_locks)
 
892
        _mod_lock.Lock.hooks.install_named_hook('lock_acquired',
 
893
                                                self._lock_acquired, None)
 
894
        _mod_lock.Lock.hooks.install_named_hook('lock_released',
 
895
                                                self._lock_released, None)
 
896
        _mod_lock.Lock.hooks.install_named_hook('lock_broken',
 
897
                                                self._lock_broken, None)
 
898
 
 
899
    def _lock_acquired(self, result):
 
900
        self._lock_actions.append(('acquired', result))
 
901
 
 
902
    def _lock_released(self, result):
 
903
        self._lock_actions.append(('released', result))
 
904
 
 
905
    def _lock_broken(self, result):
 
906
        self._lock_actions.append(('broken', result))
 
907
 
 
908
    def _ndiff_strings(self, a, b):
 
909
        """Return ndiff between two strings containing lines.
 
910
 
 
911
        A trailing newline is added if missing to make the strings
 
912
        print properly."""
 
913
        if b and b[-1] != '\n':
 
914
            b += '\n'
 
915
        if a and a[-1] != '\n':
 
916
            a += '\n'
 
917
        difflines = difflib.ndiff(a.splitlines(True),
 
918
                                  b.splitlines(True),
 
919
                                  linejunk=lambda x: False,
 
920
                                  charjunk=lambda x: False)
 
921
        return ''.join(difflines)
 
922
 
 
923
    def assertEqual(self, a, b, message=''):
 
924
        try:
 
925
            if a == b:
 
926
                return
 
927
        except UnicodeError, e:
 
928
            # If we can't compare without getting a UnicodeError, then
 
929
            # obviously they are different
 
930
            mutter('UnicodeError: %s', e)
 
931
        if message:
 
932
            message += '\n'
 
933
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
 
934
            % (message,
 
935
               pformat(a), pformat(b)))
 
936
 
 
937
    assertEquals = assertEqual
 
938
 
 
939
    def assertEqualDiff(self, a, b, message=None):
 
940
        """Assert two texts are equal, if not raise an exception.
 
941
 
 
942
        This is intended for use with multi-line strings where it can
 
943
        be hard to find the differences by eye.
 
944
        """
 
945
        # TODO: perhaps override assertEquals to call this for strings?
 
946
        if a == b:
 
947
            return
 
948
        if message is None:
 
949
            message = "texts not equal:\n"
 
950
        if a == b + '\n':
 
951
            message = 'first string is missing a final newline.\n'
 
952
        if a + '\n' == b:
 
953
            message = 'second string is missing a final newline.\n'
 
954
        raise AssertionError(message +
 
955
                             self._ndiff_strings(a, b))
 
956
 
 
957
    def assertEqualMode(self, mode, mode_test):
 
958
        self.assertEqual(mode, mode_test,
 
959
                         'mode mismatch %o != %o' % (mode, mode_test))
 
960
 
 
961
    def assertEqualStat(self, expected, actual):
 
962
        """assert that expected and actual are the same stat result.
 
963
 
 
964
        :param expected: A stat result.
 
965
        :param actual: A stat result.
 
966
        :raises AssertionError: If the expected and actual stat values differ
 
967
            other than by atime.
 
968
        """
 
969
        self.assertEqual(expected.st_size, actual.st_size)
 
970
        self.assertEqual(expected.st_mtime, actual.st_mtime)
 
971
        self.assertEqual(expected.st_ctime, actual.st_ctime)
 
972
        self.assertEqual(expected.st_dev, actual.st_dev)
 
973
        self.assertEqual(expected.st_ino, actual.st_ino)
 
974
        self.assertEqual(expected.st_mode, actual.st_mode)
 
975
 
 
976
    def assertLength(self, length, obj_with_len):
 
977
        """Assert that obj_with_len is of length length."""
 
978
        if len(obj_with_len) != length:
 
979
            self.fail("Incorrect length: wanted %d, got %d for %r" % (
 
980
                length, len(obj_with_len), obj_with_len))
 
981
 
 
982
    def assertPositive(self, val):
 
983
        """Assert that val is greater than 0."""
 
984
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
 
985
 
 
986
    def assertNegative(self, val):
 
987
        """Assert that val is less than 0."""
 
988
        self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
 
989
 
 
990
    def assertStartsWith(self, s, prefix):
 
991
        if not s.startswith(prefix):
 
992
            raise AssertionError('string %r does not start with %r' % (s, prefix))
 
993
 
 
994
    def assertEndsWith(self, s, suffix):
 
995
        """Asserts that s ends with suffix."""
 
996
        if not s.endswith(suffix):
 
997
            raise AssertionError('string %r does not end with %r' % (s, suffix))
 
998
 
 
999
    def assertContainsRe(self, haystack, needle_re, flags=0):
 
1000
        """Assert that a contains something matching a regular expression."""
 
1001
        if not re.search(needle_re, haystack, flags):
 
1002
            if '\n' in haystack or len(haystack) > 60:
 
1003
                # a long string, format it in a more readable way
 
1004
                raise AssertionError(
 
1005
                        'pattern "%s" not found in\n"""\\\n%s"""\n'
 
1006
                        % (needle_re, haystack))
 
1007
            else:
 
1008
                raise AssertionError('pattern "%s" not found in "%s"'
 
1009
                        % (needle_re, haystack))
 
1010
 
 
1011
    def assertNotContainsRe(self, haystack, needle_re, flags=0):
 
1012
        """Assert that a does not match a regular expression"""
 
1013
        if re.search(needle_re, haystack, flags):
 
1014
            raise AssertionError('pattern "%s" found in "%s"'
 
1015
                    % (needle_re, haystack))
 
1016
 
 
1017
    def assertSubset(self, sublist, superlist):
 
1018
        """Assert that every entry in sublist is present in superlist."""
 
1019
        missing = set(sublist) - set(superlist)
 
1020
        if len(missing) > 0:
 
1021
            raise AssertionError("value(s) %r not present in container %r" %
 
1022
                                 (missing, superlist))
 
1023
 
 
1024
    def assertListRaises(self, excClass, func, *args, **kwargs):
 
1025
        """Fail unless excClass is raised when the iterator from func is used.
 
1026
 
 
1027
        Many functions can return generators this makes sure
 
1028
        to wrap them in a list() call to make sure the whole generator
 
1029
        is run, and that the proper exception is raised.
 
1030
        """
 
1031
        try:
 
1032
            list(func(*args, **kwargs))
 
1033
        except excClass, e:
 
1034
            return e
 
1035
        else:
 
1036
            if getattr(excClass,'__name__', None) is not None:
 
1037
                excName = excClass.__name__
 
1038
            else:
 
1039
                excName = str(excClass)
 
1040
            raise self.failureException, "%s not raised" % excName
 
1041
 
 
1042
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
 
1043
        """Assert that a callable raises a particular exception.
 
1044
 
 
1045
        :param excClass: As for the except statement, this may be either an
 
1046
            exception class, or a tuple of classes.
 
1047
        :param callableObj: A callable, will be passed ``*args`` and
 
1048
            ``**kwargs``.
 
1049
 
 
1050
        Returns the exception so that you can examine it.
 
1051
        """
 
1052
        try:
 
1053
            callableObj(*args, **kwargs)
 
1054
        except excClass, e:
 
1055
            return e
 
1056
        else:
 
1057
            if getattr(excClass,'__name__', None) is not None:
 
1058
                excName = excClass.__name__
 
1059
            else:
 
1060
                # probably a tuple
 
1061
                excName = str(excClass)
 
1062
            raise self.failureException, "%s not raised" % excName
 
1063
 
 
1064
    def assertIs(self, left, right, message=None):
 
1065
        if not (left is right):
 
1066
            if message is not None:
 
1067
                raise AssertionError(message)
 
1068
            else:
 
1069
                raise AssertionError("%r is not %r." % (left, right))
 
1070
 
 
1071
    def assertIsNot(self, left, right, message=None):
 
1072
        if (left is right):
 
1073
            if message is not None:
 
1074
                raise AssertionError(message)
 
1075
            else:
 
1076
                raise AssertionError("%r is %r." % (left, right))
 
1077
 
 
1078
    def assertTransportMode(self, transport, path, mode):
 
1079
        """Fail if a path does not have mode "mode".
 
1080
 
 
1081
        If modes are not supported on this transport, the assertion is ignored.
 
1082
        """
 
1083
        if not transport._can_roundtrip_unix_modebits():
 
1084
            return
 
1085
        path_stat = transport.stat(path)
 
1086
        actual_mode = stat.S_IMODE(path_stat.st_mode)
 
1087
        self.assertEqual(mode, actual_mode,
 
1088
                         'mode of %r incorrect (%s != %s)'
 
1089
                         % (path, oct(mode), oct(actual_mode)))
 
1090
 
 
1091
    def assertIsSameRealPath(self, path1, path2):
 
1092
        """Fail if path1 and path2 points to different files"""
 
1093
        self.assertEqual(osutils.realpath(path1),
 
1094
                         osutils.realpath(path2),
 
1095
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
 
1096
 
 
1097
    def assertIsInstance(self, obj, kls, msg=None):
 
1098
        """Fail if obj is not an instance of kls
30
1099
        
31
 
 
32
 
def selftest(verbose=False):
33
 
    from unittest import TestLoader, TestSuite
34
 
    import bzrlib, bzrlib.store, bzrlib.inventory, bzrlib.branch
35
 
    import bzrlib.osutils, bzrlib.commands, bzrlib.merge3, bzrlib.plugin
36
 
    from doctest import DocTestSuite
37
 
    import os
38
 
    import shutil
39
 
    import time
40
 
    import sys
41
 
    import unittest
42
 
 
43
 
    global MODULES_TO_TEST, MODULES_TO_DOCTEST
44
 
 
45
 
    testmod_names = \
46
 
                  ['bzrlib.selftest.whitebox',
47
 
                   'bzrlib.selftest.versioning',
48
 
                   'bzrlib.selftest.testinv',
49
 
                   'bzrlib.selftest.testmerge3',
50
 
                   'bzrlib.selftest.testhashcache',
51
 
                   'bzrlib.selftest.teststatus',
52
 
                   'bzrlib.selftest.testlog',
53
 
                   'bzrlib.selftest.blackbox',
54
 
                   'bzrlib.selftest.testrevisionnamespaces',
55
 
                   'bzrlib.selftest.testbranch',
56
 
                   'bzrlib.selftest.testrevision',
57
 
                   'bzrlib.merge_core',
58
 
                   'bzrlib.selftest.testdiff',
 
1100
        :param msg: Supplementary message to show if the assertion fails.
 
1101
        """
 
1102
        if not isinstance(obj, kls):
 
1103
            m = "%r is an instance of %s rather than %s" % (
 
1104
                obj, obj.__class__, kls)
 
1105
            if msg:
 
1106
                m += ": " + msg
 
1107
            self.fail(m)
 
1108
 
 
1109
    def expectFailure(self, reason, assertion, *args, **kwargs):
 
1110
        """Invoke a test, expecting it to fail for the given reason.
 
1111
 
 
1112
        This is for assertions that ought to succeed, but currently fail.
 
1113
        (The failure is *expected* but not *wanted*.)  Please be very precise
 
1114
        about the failure you're expecting.  If a new bug is introduced,
 
1115
        AssertionError should be raised, not KnownFailure.
 
1116
 
 
1117
        Frequently, expectFailure should be followed by an opposite assertion.
 
1118
        See example below.
 
1119
 
 
1120
        Intended to be used with a callable that raises AssertionError as the
 
1121
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
 
1122
 
 
1123
        Raises KnownFailure if the test fails.  Raises AssertionError if the
 
1124
        test succeeds.
 
1125
 
 
1126
        example usage::
 
1127
 
 
1128
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
 
1129
                             dynamic_val)
 
1130
          self.assertEqual(42, dynamic_val)
 
1131
 
 
1132
          This means that a dynamic_val of 54 will cause the test to raise
 
1133
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
 
1134
          only a dynamic_val of 42 will allow the test to pass.  Anything other
 
1135
          than 54 or 42 will cause an AssertionError.
 
1136
        """
 
1137
        try:
 
1138
            assertion(*args, **kwargs)
 
1139
        except AssertionError:
 
1140
            raise KnownFailure(reason)
 
1141
        else:
 
1142
            self.fail('Unexpected success.  Should have failed: %s' % reason)
 
1143
 
 
1144
    def assertFileEqual(self, content, path):
 
1145
        """Fail if path does not contain 'content'."""
 
1146
        self.failUnlessExists(path)
 
1147
        f = file(path, 'rb')
 
1148
        try:
 
1149
            s = f.read()
 
1150
        finally:
 
1151
            f.close()
 
1152
        self.assertEqualDiff(content, s)
 
1153
 
 
1154
    def failUnlessExists(self, path):
 
1155
        """Fail unless path or paths, which may be abs or relative, exist."""
 
1156
        if not isinstance(path, basestring):
 
1157
            for p in path:
 
1158
                self.failUnlessExists(p)
 
1159
        else:
 
1160
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
1161
 
 
1162
    def failIfExists(self, path):
 
1163
        """Fail if path or paths, which may be abs or relative, exist."""
 
1164
        if not isinstance(path, basestring):
 
1165
            for p in path:
 
1166
                self.failIfExists(p)
 
1167
        else:
 
1168
            self.failIf(osutils.lexists(path),path+" exists")
 
1169
 
 
1170
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
 
1171
        """A helper for callDeprecated and applyDeprecated.
 
1172
 
 
1173
        :param a_callable: A callable to call.
 
1174
        :param args: The positional arguments for the callable
 
1175
        :param kwargs: The keyword arguments for the callable
 
1176
        :return: A tuple (warnings, result). result is the result of calling
 
1177
            a_callable(``*args``, ``**kwargs``).
 
1178
        """
 
1179
        local_warnings = []
 
1180
        def capture_warnings(msg, cls=None, stacklevel=None):
 
1181
            # we've hooked into a deprecation specific callpath,
 
1182
            # only deprecations should getting sent via it.
 
1183
            self.assertEqual(cls, DeprecationWarning)
 
1184
            local_warnings.append(msg)
 
1185
        original_warning_method = symbol_versioning.warn
 
1186
        symbol_versioning.set_warning_method(capture_warnings)
 
1187
        try:
 
1188
            result = a_callable(*args, **kwargs)
 
1189
        finally:
 
1190
            symbol_versioning.set_warning_method(original_warning_method)
 
1191
        return (local_warnings, result)
 
1192
 
 
1193
    def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
 
1194
        """Call a deprecated callable without warning the user.
 
1195
 
 
1196
        Note that this only captures warnings raised by symbol_versioning.warn,
 
1197
        not other callers that go direct to the warning module.
 
1198
 
 
1199
        To test that a deprecated method raises an error, do something like
 
1200
        this::
 
1201
 
 
1202
            self.assertRaises(errors.ReservedId,
 
1203
                self.applyDeprecated,
 
1204
                deprecated_in((1, 5, 0)),
 
1205
                br.append_revision,
 
1206
                'current:')
 
1207
 
 
1208
        :param deprecation_format: The deprecation format that the callable
 
1209
            should have been deprecated with. This is the same type as the
 
1210
            parameter to deprecated_method/deprecated_function. If the
 
1211
            callable is not deprecated with this format, an assertion error
 
1212
            will be raised.
 
1213
        :param a_callable: A callable to call. This may be a bound method or
 
1214
            a regular function. It will be called with ``*args`` and
 
1215
            ``**kwargs``.
 
1216
        :param args: The positional arguments for the callable
 
1217
        :param kwargs: The keyword arguments for the callable
 
1218
        :return: The result of a_callable(``*args``, ``**kwargs``)
 
1219
        """
 
1220
        call_warnings, result = self._capture_deprecation_warnings(a_callable,
 
1221
            *args, **kwargs)
 
1222
        expected_first_warning = symbol_versioning.deprecation_string(
 
1223
            a_callable, deprecation_format)
 
1224
        if len(call_warnings) == 0:
 
1225
            self.fail("No deprecation warning generated by call to %s" %
 
1226
                a_callable)
 
1227
        self.assertEqual(expected_first_warning, call_warnings[0])
 
1228
        return result
 
1229
 
 
1230
    def callCatchWarnings(self, fn, *args, **kw):
 
1231
        """Call a callable that raises python warnings.
 
1232
 
 
1233
        The caller's responsible for examining the returned warnings.
 
1234
 
 
1235
        If the callable raises an exception, the exception is not
 
1236
        caught and propagates up to the caller.  In that case, the list
 
1237
        of warnings is not available.
 
1238
 
 
1239
        :returns: ([warning_object, ...], fn_result)
 
1240
        """
 
1241
        # XXX: This is not perfect, because it completely overrides the
 
1242
        # warnings filters, and some code may depend on suppressing particular
 
1243
        # warnings.  It's the easiest way to insulate ourselves from -Werror,
 
1244
        # though.  -- Andrew, 20071062
 
1245
        wlist = []
 
1246
        def _catcher(message, category, filename, lineno, file=None, line=None):
 
1247
            # despite the name, 'message' is normally(?) a Warning subclass
 
1248
            # instance
 
1249
            wlist.append(message)
 
1250
        saved_showwarning = warnings.showwarning
 
1251
        saved_filters = warnings.filters
 
1252
        try:
 
1253
            warnings.showwarning = _catcher
 
1254
            warnings.filters = []
 
1255
            result = fn(*args, **kw)
 
1256
        finally:
 
1257
            warnings.showwarning = saved_showwarning
 
1258
            warnings.filters = saved_filters
 
1259
        return wlist, result
 
1260
 
 
1261
    def callDeprecated(self, expected, callable, *args, **kwargs):
 
1262
        """Assert that a callable is deprecated in a particular way.
 
1263
 
 
1264
        This is a very precise test for unusual requirements. The
 
1265
        applyDeprecated helper function is probably more suited for most tests
 
1266
        as it allows you to simply specify the deprecation format being used
 
1267
        and will ensure that that is issued for the function being called.
 
1268
 
 
1269
        Note that this only captures warnings raised by symbol_versioning.warn,
 
1270
        not other callers that go direct to the warning module.  To catch
 
1271
        general warnings, use callCatchWarnings.
 
1272
 
 
1273
        :param expected: a list of the deprecation warnings expected, in order
 
1274
        :param callable: The callable to call
 
1275
        :param args: The positional arguments for the callable
 
1276
        :param kwargs: The keyword arguments for the callable
 
1277
        """
 
1278
        call_warnings, result = self._capture_deprecation_warnings(callable,
 
1279
            *args, **kwargs)
 
1280
        self.assertEqual(expected, call_warnings)
 
1281
        return result
 
1282
 
 
1283
    def _startLogFile(self):
 
1284
        """Send bzr and test log messages to a temporary file.
 
1285
 
 
1286
        The file is removed as the test is torn down.
 
1287
        """
 
1288
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
 
1289
        self._log_file = os.fdopen(fileno, 'w+')
 
1290
        self._log_memento = bzrlib.trace.push_log_file(self._log_file)
 
1291
        self._log_file_name = name
 
1292
        self.addCleanup(self._finishLogFile)
 
1293
 
 
1294
    def _finishLogFile(self):
 
1295
        """Finished with the log file.
 
1296
 
 
1297
        Close the file and delete it, unless setKeepLogfile was called.
 
1298
        """
 
1299
        if self._log_file is None:
 
1300
            return
 
1301
        bzrlib.trace.pop_log_file(self._log_memento)
 
1302
        self._log_file.close()
 
1303
        self._log_file = None
 
1304
        if not self._keep_log_file:
 
1305
            os.remove(self._log_file_name)
 
1306
            self._log_file_name = None
 
1307
 
 
1308
    def setKeepLogfile(self):
 
1309
        """Make the logfile not be deleted when _finishLogFile is called."""
 
1310
        self._keep_log_file = True
 
1311
 
 
1312
    def addCleanup(self, callable, *args, **kwargs):
 
1313
        """Arrange to run a callable when this case is torn down.
 
1314
 
 
1315
        Callables are run in the reverse of the order they are registered,
 
1316
        ie last-in first-out.
 
1317
        """
 
1318
        self._cleanups.append((callable, args, kwargs))
 
1319
 
 
1320
    def _cleanEnvironment(self):
 
1321
        new_env = {
 
1322
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
 
1323
            'HOME': os.getcwd(),
 
1324
            # bzr now uses the Win32 API and doesn't rely on APPDATA, but the
 
1325
            # tests do check our impls match APPDATA
 
1326
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
1327
            'VISUAL': None,
 
1328
            'EDITOR': None,
 
1329
            'BZR_EMAIL': None,
 
1330
            'BZREMAIL': None, # may still be present in the environment
 
1331
            'EMAIL': None,
 
1332
            'BZR_PROGRESS_BAR': None,
 
1333
            'BZR_LOG': None,
 
1334
            'BZR_PLUGIN_PATH': None,
 
1335
            # Make sure that any text ui tests are consistent regardless of
 
1336
            # the environment the test case is run in; you may want tests that
 
1337
            # test other combinations.  'dumb' is a reasonable guess for tests
 
1338
            # going to a pipe or a StringIO.
 
1339
            'TERM': 'dumb',
 
1340
            'LINES': '25',
 
1341
            'COLUMNS': '80',
 
1342
            # SSH Agent
 
1343
            'SSH_AUTH_SOCK': None,
 
1344
            # Proxies
 
1345
            'http_proxy': None,
 
1346
            'HTTP_PROXY': None,
 
1347
            'https_proxy': None,
 
1348
            'HTTPS_PROXY': None,
 
1349
            'no_proxy': None,
 
1350
            'NO_PROXY': None,
 
1351
            'all_proxy': None,
 
1352
            'ALL_PROXY': None,
 
1353
            # Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
 
1354
            # least. If you do (care), please update this comment
 
1355
            # -- vila 20080401
 
1356
            'ftp_proxy': None,
 
1357
            'FTP_PROXY': None,
 
1358
            'BZR_REMOTE_PATH': None,
 
1359
        }
 
1360
        self.__old_env = {}
 
1361
        self.addCleanup(self._restoreEnvironment)
 
1362
        for name, value in new_env.iteritems():
 
1363
            self._captureVar(name, value)
 
1364
 
 
1365
    def _captureVar(self, name, newvalue):
 
1366
        """Set an environment variable, and reset it when finished."""
 
1367
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
 
1368
 
 
1369
    def _restore_debug_flags(self):
 
1370
        debug.debug_flags.clear()
 
1371
        debug.debug_flags.update(self._preserved_debug_flags)
 
1372
 
 
1373
    def _restoreEnvironment(self):
 
1374
        for name, value in self.__old_env.iteritems():
 
1375
            osutils.set_or_unset_env(name, value)
 
1376
 
 
1377
    def _restoreHooks(self):
 
1378
        for klass, (name, hooks) in self._preserved_hooks.items():
 
1379
            setattr(klass, name, hooks)
 
1380
 
 
1381
    def knownFailure(self, reason):
 
1382
        """This test has failed for some known reason."""
 
1383
        raise KnownFailure(reason)
 
1384
 
 
1385
    def _do_skip(self, result, reason):
 
1386
        addSkip = getattr(result, 'addSkip', None)
 
1387
        if not callable(addSkip):
 
1388
            result.addError(self, sys.exc_info())
 
1389
        else:
 
1390
            addSkip(self, reason)
 
1391
 
 
1392
    def run(self, result=None):
 
1393
        if result is None: result = self.defaultTestResult()
 
1394
        for feature in getattr(self, '_test_needs_features', []):
 
1395
            if not feature.available():
 
1396
                result.startTest(self)
 
1397
                if getattr(result, 'addNotSupported', None):
 
1398
                    result.addNotSupported(self, feature)
 
1399
                else:
 
1400
                    result.addSuccess(self)
 
1401
                result.stopTest(self)
 
1402
                return result
 
1403
        try:
 
1404
            try:
 
1405
                result.startTest(self)
 
1406
                absent_attr = object()
 
1407
                # Python 2.5
 
1408
                method_name = getattr(self, '_testMethodName', absent_attr)
 
1409
                if method_name is absent_attr:
 
1410
                    # Python 2.4
 
1411
                    method_name = getattr(self, '_TestCase__testMethodName')
 
1412
                testMethod = getattr(self, method_name)
 
1413
                try:
 
1414
                    try:
 
1415
                        self.setUp()
 
1416
                        if not self._bzr_test_setUp_run:
 
1417
                            self.fail(
 
1418
                                "test setUp did not invoke "
 
1419
                                "bzrlib.tests.TestCase's setUp")
 
1420
                    except KeyboardInterrupt:
 
1421
                        self._runCleanups()
 
1422
                        raise
 
1423
                    except TestSkipped, e:
 
1424
                        self._do_skip(result, e.args[0])
 
1425
                        self.tearDown()
 
1426
                        return result
 
1427
                    except:
 
1428
                        result.addError(self, sys.exc_info())
 
1429
                        self._runCleanups()
 
1430
                        return result
 
1431
 
 
1432
                    ok = False
 
1433
                    try:
 
1434
                        testMethod()
 
1435
                        ok = True
 
1436
                    except self.failureException:
 
1437
                        result.addFailure(self, sys.exc_info())
 
1438
                    except TestSkipped, e:
 
1439
                        if not e.args:
 
1440
                            reason = "No reason given."
 
1441
                        else:
 
1442
                            reason = e.args[0]
 
1443
                        self._do_skip(result, reason)
 
1444
                    except KeyboardInterrupt:
 
1445
                        self._runCleanups()
 
1446
                        raise
 
1447
                    except:
 
1448
                        result.addError(self, sys.exc_info())
 
1449
 
 
1450
                    try:
 
1451
                        self.tearDown()
 
1452
                        if not self._bzr_test_tearDown_run:
 
1453
                            self.fail(
 
1454
                                "test tearDown did not invoke "
 
1455
                                "bzrlib.tests.TestCase's tearDown")
 
1456
                    except KeyboardInterrupt:
 
1457
                        self._runCleanups()
 
1458
                        raise
 
1459
                    except:
 
1460
                        result.addError(self, sys.exc_info())
 
1461
                        self._runCleanups()
 
1462
                        ok = False
 
1463
                    if ok: result.addSuccess(self)
 
1464
                finally:
 
1465
                    result.stopTest(self)
 
1466
                return result
 
1467
            except TestNotApplicable:
 
1468
                # Not moved from the result [yet].
 
1469
                self._runCleanups()
 
1470
                raise
 
1471
            except KeyboardInterrupt:
 
1472
                self._runCleanups()
 
1473
                raise
 
1474
        finally:
 
1475
            saved_attrs = {}
 
1476
            for attr_name in self.attrs_to_keep:
 
1477
                if attr_name in self.__dict__:
 
1478
                    saved_attrs[attr_name] = self.__dict__[attr_name]
 
1479
            self.__dict__ = saved_attrs
 
1480
 
 
1481
    def tearDown(self):
 
1482
        self._runCleanups()
 
1483
        self._log_contents = ''
 
1484
        self._bzr_test_tearDown_run = True
 
1485
        unittest.TestCase.tearDown(self)
 
1486
 
 
1487
    def time(self, callable, *args, **kwargs):
 
1488
        """Run callable and accrue the time it takes to the benchmark time.
 
1489
 
 
1490
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
 
1491
        this will cause lsprofile statistics to be gathered and stored in
 
1492
        self._benchcalls.
 
1493
        """
 
1494
        if self._benchtime is None:
 
1495
            self._benchtime = 0
 
1496
        start = time.time()
 
1497
        try:
 
1498
            if not self._gather_lsprof_in_benchmarks:
 
1499
                return callable(*args, **kwargs)
 
1500
            else:
 
1501
                # record this benchmark
 
1502
                ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
 
1503
                stats.sort()
 
1504
                self._benchcalls.append(((callable, args, kwargs), stats))
 
1505
                return ret
 
1506
        finally:
 
1507
            self._benchtime += time.time() - start
 
1508
 
 
1509
    def _runCleanups(self):
 
1510
        """Run registered cleanup functions.
 
1511
 
 
1512
        This should only be called from TestCase.tearDown.
 
1513
        """
 
1514
        # TODO: Perhaps this should keep running cleanups even if
 
1515
        # one of them fails?
 
1516
 
 
1517
        # Actually pop the cleanups from the list so tearDown running
 
1518
        # twice is safe (this happens for skipped tests).
 
1519
        while self._cleanups:
 
1520
            cleanup, args, kwargs = self._cleanups.pop()
 
1521
            cleanup(*args, **kwargs)
 
1522
 
 
1523
    def log(self, *args):
 
1524
        mutter(*args)
 
1525
 
 
1526
    def _get_log(self, keep_log_file=False):
 
1527
        """Get the log from bzrlib.trace calls from this test.
 
1528
 
 
1529
        :param keep_log_file: When True, if the log is still a file on disk
 
1530
            leave it as a file on disk. When False, if the log is still a file
 
1531
            on disk, the log file is deleted and the log preserved as
 
1532
            self._log_contents.
 
1533
        :return: A string containing the log.
 
1534
        """
 
1535
        # flush the log file, to get all content
 
1536
        import bzrlib.trace
 
1537
        if bzrlib.trace._trace_file:
 
1538
            bzrlib.trace._trace_file.flush()
 
1539
        if self._log_contents:
 
1540
            # XXX: this can hardly contain the content flushed above --vila
 
1541
            # 20080128
 
1542
            return self._log_contents
 
1543
        if self._log_file_name is not None:
 
1544
            logfile = open(self._log_file_name)
 
1545
            try:
 
1546
                log_contents = logfile.read()
 
1547
            finally:
 
1548
                logfile.close()
 
1549
            if not keep_log_file:
 
1550
                self._log_contents = log_contents
 
1551
                try:
 
1552
                    os.remove(self._log_file_name)
 
1553
                except OSError, e:
 
1554
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
 
1555
                        sys.stderr.write(('Unable to delete log file '
 
1556
                                             ' %r\n' % self._log_file_name))
 
1557
                    else:
 
1558
                        raise
 
1559
            return log_contents
 
1560
        else:
 
1561
            return "DELETED log file to reduce memory footprint"
 
1562
 
 
1563
    def requireFeature(self, feature):
 
1564
        """This test requires a specific feature is available.
 
1565
 
 
1566
        :raises UnavailableFeature: When feature is not available.
 
1567
        """
 
1568
        if not feature.available():
 
1569
            raise UnavailableFeature(feature)
 
1570
 
 
1571
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
 
1572
            working_dir):
 
1573
        """Run bazaar command line, splitting up a string command line."""
 
1574
        if isinstance(args, basestring):
 
1575
            # shlex don't understand unicode strings,
 
1576
            # so args should be plain string (bialix 20070906)
 
1577
            args = list(shlex.split(str(args)))
 
1578
        return self._run_bzr_core(args, retcode=retcode,
 
1579
                encoding=encoding, stdin=stdin, working_dir=working_dir,
 
1580
                )
 
1581
 
 
1582
    def _run_bzr_core(self, args, retcode, encoding, stdin,
 
1583
            working_dir):
 
1584
        if encoding is None:
 
1585
            encoding = osutils.get_user_encoding()
 
1586
        stdout = StringIOWrapper()
 
1587
        stderr = StringIOWrapper()
 
1588
        stdout.encoding = encoding
 
1589
        stderr.encoding = encoding
 
1590
 
 
1591
        self.log('run bzr: %r', args)
 
1592
        # FIXME: don't call into logging here
 
1593
        handler = logging.StreamHandler(stderr)
 
1594
        handler.setLevel(logging.INFO)
 
1595
        logger = logging.getLogger('')
 
1596
        logger.addHandler(handler)
 
1597
        old_ui_factory = ui.ui_factory
 
1598
        ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
 
1599
 
 
1600
        cwd = None
 
1601
        if working_dir is not None:
 
1602
            cwd = osutils.getcwd()
 
1603
            os.chdir(working_dir)
 
1604
 
 
1605
        try:
 
1606
            result = self.apply_redirected(ui.ui_factory.stdin,
 
1607
                stdout, stderr,
 
1608
                bzrlib.commands.run_bzr_catch_user_errors,
 
1609
                args)
 
1610
        finally:
 
1611
            logger.removeHandler(handler)
 
1612
            ui.ui_factory = old_ui_factory
 
1613
            if cwd is not None:
 
1614
                os.chdir(cwd)
 
1615
 
 
1616
        out = stdout.getvalue()
 
1617
        err = stderr.getvalue()
 
1618
        if out:
 
1619
            self.log('output:\n%r', out)
 
1620
        if err:
 
1621
            self.log('errors:\n%r', err)
 
1622
        if retcode is not None:
 
1623
            self.assertEquals(retcode, result,
 
1624
                              message='Unexpected return code')
 
1625
        return out, err
 
1626
 
 
1627
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
 
1628
                working_dir=None, error_regexes=[], output_encoding=None):
 
1629
        """Invoke bzr, as if it were run from the command line.
 
1630
 
 
1631
        The argument list should not include the bzr program name - the
 
1632
        first argument is normally the bzr command.  Arguments may be
 
1633
        passed in three ways:
 
1634
 
 
1635
        1- A list of strings, eg ["commit", "a"].  This is recommended
 
1636
        when the command contains whitespace or metacharacters, or
 
1637
        is built up at run time.
 
1638
 
 
1639
        2- A single string, eg "add a".  This is the most convenient
 
1640
        for hardcoded commands.
 
1641
 
 
1642
        This runs bzr through the interface that catches and reports
 
1643
        errors, and with logging set to something approximating the
 
1644
        default, so that error reporting can be checked.
 
1645
 
 
1646
        This should be the main method for tests that want to exercise the
 
1647
        overall behavior of the bzr application (rather than a unit test
 
1648
        or a functional test of the library.)
 
1649
 
 
1650
        This sends the stdout/stderr results into the test's log,
 
1651
        where it may be useful for debugging.  See also run_captured.
 
1652
 
 
1653
        :keyword stdin: A string to be used as stdin for the command.
 
1654
        :keyword retcode: The status code the command should return;
 
1655
            default 0.
 
1656
        :keyword working_dir: The directory to run the command in
 
1657
        :keyword error_regexes: A list of expected error messages.  If
 
1658
            specified they must be seen in the error output of the command.
 
1659
        """
 
1660
        out, err = self._run_bzr_autosplit(
 
1661
            args=args,
 
1662
            retcode=retcode,
 
1663
            encoding=encoding,
 
1664
            stdin=stdin,
 
1665
            working_dir=working_dir,
 
1666
            )
 
1667
        self.assertIsInstance(error_regexes, (list, tuple))
 
1668
        for regex in error_regexes:
 
1669
            self.assertContainsRe(err, regex)
 
1670
        return out, err
 
1671
 
 
1672
    def run_bzr_error(self, error_regexes, *args, **kwargs):
 
1673
        """Run bzr, and check that stderr contains the supplied regexes
 
1674
 
 
1675
        :param error_regexes: Sequence of regular expressions which
 
1676
            must each be found in the error output. The relative ordering
 
1677
            is not enforced.
 
1678
        :param args: command-line arguments for bzr
 
1679
        :param kwargs: Keyword arguments which are interpreted by run_bzr
 
1680
            This function changes the default value of retcode to be 3,
 
1681
            since in most cases this is run when you expect bzr to fail.
 
1682
 
 
1683
        :return: (out, err) The actual output of running the command (in case
 
1684
            you want to do more inspection)
 
1685
 
 
1686
        Examples of use::
 
1687
 
 
1688
            # Make sure that commit is failing because there is nothing to do
 
1689
            self.run_bzr_error(['no changes to commit'],
 
1690
                               ['commit', '-m', 'my commit comment'])
 
1691
            # Make sure --strict is handling an unknown file, rather than
 
1692
            # giving us the 'nothing to do' error
 
1693
            self.build_tree(['unknown'])
 
1694
            self.run_bzr_error(['Commit refused because there are unknown files'],
 
1695
                               ['commit', --strict', '-m', 'my commit comment'])
 
1696
        """
 
1697
        kwargs.setdefault('retcode', 3)
 
1698
        kwargs['error_regexes'] = error_regexes
 
1699
        out, err = self.run_bzr(*args, **kwargs)
 
1700
        return out, err
 
1701
 
 
1702
    def run_bzr_subprocess(self, *args, **kwargs):
 
1703
        """Run bzr in a subprocess for testing.
 
1704
 
 
1705
        This starts a new Python interpreter and runs bzr in there.
 
1706
        This should only be used for tests that have a justifiable need for
 
1707
        this isolation: e.g. they are testing startup time, or signal
 
1708
        handling, or early startup code, etc.  Subprocess code can't be
 
1709
        profiled or debugged so easily.
 
1710
 
 
1711
        :keyword retcode: The status code that is expected.  Defaults to 0.  If
 
1712
            None is supplied, the status code is not checked.
 
1713
        :keyword env_changes: A dictionary which lists changes to environment
 
1714
            variables. A value of None will unset the env variable.
 
1715
            The values must be strings. The change will only occur in the
 
1716
            child, so you don't need to fix the environment after running.
 
1717
        :keyword universal_newlines: Convert CRLF => LF
 
1718
        :keyword allow_plugins: By default the subprocess is run with
 
1719
            --no-plugins to ensure test reproducibility. Also, it is possible
 
1720
            for system-wide plugins to create unexpected output on stderr,
 
1721
            which can cause unnecessary test failures.
 
1722
        """
 
1723
        env_changes = kwargs.get('env_changes', {})
 
1724
        working_dir = kwargs.get('working_dir', None)
 
1725
        allow_plugins = kwargs.get('allow_plugins', False)
 
1726
        if len(args) == 1:
 
1727
            if isinstance(args[0], list):
 
1728
                args = args[0]
 
1729
            elif isinstance(args[0], basestring):
 
1730
                args = list(shlex.split(args[0]))
 
1731
        else:
 
1732
            raise ValueError("passing varargs to run_bzr_subprocess")
 
1733
        process = self.start_bzr_subprocess(args, env_changes=env_changes,
 
1734
                                            working_dir=working_dir,
 
1735
                                            allow_plugins=allow_plugins)
 
1736
        # We distinguish between retcode=None and retcode not passed.
 
1737
        supplied_retcode = kwargs.get('retcode', 0)
 
1738
        return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
 
1739
            universal_newlines=kwargs.get('universal_newlines', False),
 
1740
            process_args=args)
 
1741
 
 
1742
    def start_bzr_subprocess(self, process_args, env_changes=None,
 
1743
                             skip_if_plan_to_signal=False,
 
1744
                             working_dir=None,
 
1745
                             allow_plugins=False):
 
1746
        """Start bzr in a subprocess for testing.
 
1747
 
 
1748
        This starts a new Python interpreter and runs bzr in there.
 
1749
        This should only be used for tests that have a justifiable need for
 
1750
        this isolation: e.g. they are testing startup time, or signal
 
1751
        handling, or early startup code, etc.  Subprocess code can't be
 
1752
        profiled or debugged so easily.
 
1753
 
 
1754
        :param process_args: a list of arguments to pass to the bzr executable,
 
1755
            for example ``['--version']``.
 
1756
        :param env_changes: A dictionary which lists changes to environment
 
1757
            variables. A value of None will unset the env variable.
 
1758
            The values must be strings. The change will only occur in the
 
1759
            child, so you don't need to fix the environment after running.
 
1760
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
 
1761
            is not available.
 
1762
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
1763
 
 
1764
        :returns: Popen object for the started process.
 
1765
        """
 
1766
        if skip_if_plan_to_signal:
 
1767
            if not getattr(os, 'kill', None):
 
1768
                raise TestSkipped("os.kill not available.")
 
1769
 
 
1770
        if env_changes is None:
 
1771
            env_changes = {}
 
1772
        old_env = {}
 
1773
 
 
1774
        def cleanup_environment():
 
1775
            for env_var, value in env_changes.iteritems():
 
1776
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
 
1777
 
 
1778
        def restore_environment():
 
1779
            for env_var, value in old_env.iteritems():
 
1780
                osutils.set_or_unset_env(env_var, value)
 
1781
 
 
1782
        bzr_path = self.get_bzr_path()
 
1783
 
 
1784
        cwd = None
 
1785
        if working_dir is not None:
 
1786
            cwd = osutils.getcwd()
 
1787
            os.chdir(working_dir)
 
1788
 
 
1789
        try:
 
1790
            # win32 subprocess doesn't support preexec_fn
 
1791
            # so we will avoid using it on all platforms, just to
 
1792
            # make sure the code path is used, and we don't break on win32
 
1793
            cleanup_environment()
 
1794
            command = [sys.executable]
 
1795
            # frozen executables don't need the path to bzr
 
1796
            if getattr(sys, "frozen", None) is None:
 
1797
                command.append(bzr_path)
 
1798
            if not allow_plugins:
 
1799
                command.append('--no-plugins')
 
1800
            command.extend(process_args)
 
1801
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
1802
        finally:
 
1803
            restore_environment()
 
1804
            if cwd is not None:
 
1805
                os.chdir(cwd)
 
1806
 
 
1807
        return process
 
1808
 
 
1809
    def _popen(self, *args, **kwargs):
 
1810
        """Place a call to Popen.
 
1811
 
 
1812
        Allows tests to override this method to intercept the calls made to
 
1813
        Popen for introspection.
 
1814
        """
 
1815
        return Popen(*args, **kwargs)
 
1816
 
 
1817
    def get_bzr_path(self):
 
1818
        """Return the path of the 'bzr' executable for this test suite."""
 
1819
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
1820
        if not os.path.isfile(bzr_path):
 
1821
            # We are probably installed. Assume sys.argv is the right file
 
1822
            bzr_path = sys.argv[0]
 
1823
        return bzr_path
 
1824
 
 
1825
    def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
 
1826
                              universal_newlines=False, process_args=None):
 
1827
        """Finish the execution of process.
 
1828
 
 
1829
        :param process: the Popen object returned from start_bzr_subprocess.
 
1830
        :param retcode: The status code that is expected.  Defaults to 0.  If
 
1831
            None is supplied, the status code is not checked.
 
1832
        :param send_signal: an optional signal to send to the process.
 
1833
        :param universal_newlines: Convert CRLF => LF
 
1834
        :returns: (stdout, stderr)
 
1835
        """
 
1836
        if send_signal is not None:
 
1837
            os.kill(process.pid, send_signal)
 
1838
        out, err = process.communicate()
 
1839
 
 
1840
        if universal_newlines:
 
1841
            out = out.replace('\r\n', '\n')
 
1842
            err = err.replace('\r\n', '\n')
 
1843
 
 
1844
        if retcode is not None and retcode != process.returncode:
 
1845
            if process_args is None:
 
1846
                process_args = "(unknown args)"
 
1847
            mutter('Output of bzr %s:\n%s', process_args, out)
 
1848
            mutter('Error for bzr %s:\n%s', process_args, err)
 
1849
            self.fail('Command bzr %s failed with retcode %s != %s'
 
1850
                      % (process_args, retcode, process.returncode))
 
1851
        return [out, err]
 
1852
 
 
1853
    def check_inventory_shape(self, inv, shape):
 
1854
        """Compare an inventory to a list of expected names.
 
1855
 
 
1856
        Fail if they are not precisely equal.
 
1857
        """
 
1858
        extras = []
 
1859
        shape = list(shape)             # copy
 
1860
        for path, ie in inv.entries():
 
1861
            name = path.replace('\\', '/')
 
1862
            if ie.kind == 'directory':
 
1863
                name = name + '/'
 
1864
            if name in shape:
 
1865
                shape.remove(name)
 
1866
            else:
 
1867
                extras.append(name)
 
1868
        if shape:
 
1869
            self.fail("expected paths not found in inventory: %r" % shape)
 
1870
        if extras:
 
1871
            self.fail("unexpected paths found in inventory: %r" % extras)
 
1872
 
 
1873
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
1874
                         a_callable=None, *args, **kwargs):
 
1875
        """Call callable with redirected std io pipes.
 
1876
 
 
1877
        Returns the return code."""
 
1878
        if not callable(a_callable):
 
1879
            raise ValueError("a_callable must be callable.")
 
1880
        if stdin is None:
 
1881
            stdin = StringIO("")
 
1882
        if stdout is None:
 
1883
            if getattr(self, "_log_file", None) is not None:
 
1884
                stdout = self._log_file
 
1885
            else:
 
1886
                stdout = StringIO()
 
1887
        if stderr is None:
 
1888
            if getattr(self, "_log_file", None is not None):
 
1889
                stderr = self._log_file
 
1890
            else:
 
1891
                stderr = StringIO()
 
1892
        real_stdin = sys.stdin
 
1893
        real_stdout = sys.stdout
 
1894
        real_stderr = sys.stderr
 
1895
        try:
 
1896
            sys.stdout = stdout
 
1897
            sys.stderr = stderr
 
1898
            sys.stdin = stdin
 
1899
            return a_callable(*args, **kwargs)
 
1900
        finally:
 
1901
            sys.stdout = real_stdout
 
1902
            sys.stderr = real_stderr
 
1903
            sys.stdin = real_stdin
 
1904
 
 
1905
    def reduceLockdirTimeout(self):
 
1906
        """Reduce the default lock timeout for the duration of the test, so that
 
1907
        if LockContention occurs during a test, it does so quickly.
 
1908
 
 
1909
        Tests that expect to provoke LockContention errors should call this.
 
1910
        """
 
1911
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
 
1912
        def resetTimeout():
 
1913
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
 
1914
        self.addCleanup(resetTimeout)
 
1915
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
1916
 
 
1917
    def make_utf8_encoded_stringio(self, encoding_type=None):
 
1918
        """Return a StringIOWrapper instance, that will encode Unicode
 
1919
        input to UTF-8.
 
1920
        """
 
1921
        if encoding_type is None:
 
1922
            encoding_type = 'strict'
 
1923
        sio = StringIO()
 
1924
        output_encoding = 'utf-8'
 
1925
        sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
 
1926
        sio.encoding = output_encoding
 
1927
        return sio
 
1928
 
 
1929
 
 
1930
class CapturedCall(object):
 
1931
    """A helper for capturing smart server calls for easy debug analysis."""
 
1932
 
 
1933
    def __init__(self, params, prefix_length):
 
1934
        """Capture the call with params and skip prefix_length stack frames."""
 
1935
        self.call = params
 
1936
        import traceback
 
1937
        # The last 5 frames are the __init__, the hook frame, and 3 smart
 
1938
        # client frames. Beyond this we could get more clever, but this is good
 
1939
        # enough for now.
 
1940
        stack = traceback.extract_stack()[prefix_length:-5]
 
1941
        self.stack = ''.join(traceback.format_list(stack))
 
1942
 
 
1943
    def __str__(self):
 
1944
        return self.call.method
 
1945
 
 
1946
    def __repr__(self):
 
1947
        return self.call.method
 
1948
 
 
1949
    def stack(self):
 
1950
        return self.stack
 
1951
 
 
1952
 
 
1953
class TestCaseWithMemoryTransport(TestCase):
 
1954
    """Common test class for tests that do not need disk resources.
 
1955
 
 
1956
    Tests that need disk resources should derive from TestCaseWithTransport.
 
1957
 
 
1958
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
 
1959
 
 
1960
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
1961
    a directory which does not exist. This serves to help ensure test isolation
 
1962
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
 
1963
    must exist. However, TestCaseWithMemoryTransport does not offer local
 
1964
    file defaults for the transport in tests, nor does it obey the command line
 
1965
    override, so tests that accidentally write to the common directory should
 
1966
    be rare.
 
1967
 
 
1968
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
 
1969
    a .bzr directory that stops us ascending higher into the filesystem.
 
1970
    """
 
1971
 
 
1972
    TEST_ROOT = None
 
1973
    _TEST_NAME = 'test'
 
1974
 
 
1975
    def __init__(self, methodName='runTest'):
 
1976
        # allow test parameterization after test construction and before test
 
1977
        # execution. Variables that the parameterizer sets need to be
 
1978
        # ones that are not set by setUp, or setUp will trash them.
 
1979
        super(TestCaseWithMemoryTransport, self).__init__(methodName)
 
1980
        self.vfs_transport_factory = default_transport
 
1981
        self.transport_server = None
 
1982
        self.transport_readonly_server = None
 
1983
        self.__vfs_server = None
 
1984
 
 
1985
    def get_transport(self, relpath=None):
 
1986
        """Return a writeable transport.
 
1987
 
 
1988
        This transport is for the test scratch space relative to
 
1989
        "self._test_root"
 
1990
 
 
1991
        :param relpath: a path relative to the base url.
 
1992
        """
 
1993
        t = get_transport(self.get_url(relpath))
 
1994
        self.assertFalse(t.is_readonly())
 
1995
        return t
 
1996
 
 
1997
    def get_readonly_transport(self, relpath=None):
 
1998
        """Return a readonly transport for the test scratch space
 
1999
 
 
2000
        This can be used to test that operations which should only need
 
2001
        readonly access in fact do not try to write.
 
2002
 
 
2003
        :param relpath: a path relative to the base url.
 
2004
        """
 
2005
        t = get_transport(self.get_readonly_url(relpath))
 
2006
        self.assertTrue(t.is_readonly())
 
2007
        return t
 
2008
 
 
2009
    def create_transport_readonly_server(self):
 
2010
        """Create a transport server from class defined at init.
 
2011
 
 
2012
        This is mostly a hook for daughter classes.
 
2013
        """
 
2014
        return self.transport_readonly_server()
 
2015
 
 
2016
    def get_readonly_server(self):
 
2017
        """Get the server instance for the readonly transport
 
2018
 
 
2019
        This is useful for some tests with specific servers to do diagnostics.
 
2020
        """
 
2021
        if self.__readonly_server is None:
 
2022
            if self.transport_readonly_server is None:
 
2023
                # readonly decorator requested
 
2024
                # bring up the server
 
2025
                self.__readonly_server = ReadonlyServer()
 
2026
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
2027
            else:
 
2028
                self.__readonly_server = self.create_transport_readonly_server()
 
2029
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
2030
            self.addCleanup(self.__readonly_server.tearDown)
 
2031
        return self.__readonly_server
 
2032
 
 
2033
    def get_readonly_url(self, relpath=None):
 
2034
        """Get a URL for the readonly transport.
 
2035
 
 
2036
        This will either be backed by '.' or a decorator to the transport
 
2037
        used by self.get_url()
 
2038
        relpath provides for clients to get a path relative to the base url.
 
2039
        These should only be downwards relative, not upwards.
 
2040
        """
 
2041
        base = self.get_readonly_server().get_url()
 
2042
        return self._adjust_url(base, relpath)
 
2043
 
 
2044
    def get_vfs_only_server(self):
 
2045
        """Get the vfs only read/write server instance.
 
2046
 
 
2047
        This is useful for some tests with specific servers that need
 
2048
        diagnostics.
 
2049
 
 
2050
        For TestCaseWithMemoryTransport this is always a MemoryServer, and there
 
2051
        is no means to override it.
 
2052
        """
 
2053
        if self.__vfs_server is None:
 
2054
            self.__vfs_server = MemoryServer()
 
2055
            self.__vfs_server.setUp()
 
2056
            self.addCleanup(self.__vfs_server.tearDown)
 
2057
        return self.__vfs_server
 
2058
 
 
2059
    def get_server(self):
 
2060
        """Get the read/write server instance.
 
2061
 
 
2062
        This is useful for some tests with specific servers that need
 
2063
        diagnostics.
 
2064
 
 
2065
        This is built from the self.transport_server factory. If that is None,
 
2066
        then the self.get_vfs_server is returned.
 
2067
        """
 
2068
        if self.__server is None:
 
2069
            if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
 
2070
                return self.get_vfs_only_server()
 
2071
            else:
 
2072
                # bring up a decorated means of access to the vfs only server.
 
2073
                self.__server = self.transport_server()
 
2074
                try:
 
2075
                    self.__server.setUp(self.get_vfs_only_server())
 
2076
                except TypeError, e:
 
2077
                    # This should never happen; the try:Except here is to assist
 
2078
                    # developers having to update code rather than seeing an
 
2079
                    # uninformative TypeError.
 
2080
                    raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
 
2081
            self.addCleanup(self.__server.tearDown)
 
2082
        return self.__server
 
2083
 
 
2084
    def _adjust_url(self, base, relpath):
 
2085
        """Get a URL (or maybe a path) for the readwrite transport.
 
2086
 
 
2087
        This will either be backed by '.' or to an equivalent non-file based
 
2088
        facility.
 
2089
        relpath provides for clients to get a path relative to the base url.
 
2090
        These should only be downwards relative, not upwards.
 
2091
        """
 
2092
        if relpath is not None and relpath != '.':
 
2093
            if not base.endswith('/'):
 
2094
                base = base + '/'
 
2095
            # XXX: Really base should be a url; we did after all call
 
2096
            # get_url()!  But sometimes it's just a path (from
 
2097
            # LocalAbspathServer), and it'd be wrong to append urlescaped data
 
2098
            # to a non-escaped local path.
 
2099
            if base.startswith('./') or base.startswith('/'):
 
2100
                base += relpath
 
2101
            else:
 
2102
                base += urlutils.escape(relpath)
 
2103
        return base
 
2104
 
 
2105
    def get_url(self, relpath=None):
 
2106
        """Get a URL (or maybe a path) for the readwrite transport.
 
2107
 
 
2108
        This will either be backed by '.' or to an equivalent non-file based
 
2109
        facility.
 
2110
        relpath provides for clients to get a path relative to the base url.
 
2111
        These should only be downwards relative, not upwards.
 
2112
        """
 
2113
        base = self.get_server().get_url()
 
2114
        return self._adjust_url(base, relpath)
 
2115
 
 
2116
    def get_vfs_only_url(self, relpath=None):
 
2117
        """Get a URL (or maybe a path for the plain old vfs transport.
 
2118
 
 
2119
        This will never be a smart protocol.  It always has all the
 
2120
        capabilities of the local filesystem, but it might actually be a
 
2121
        MemoryTransport or some other similar virtual filesystem.
 
2122
 
 
2123
        This is the backing transport (if any) of the server returned by
 
2124
        get_url and get_readonly_url.
 
2125
 
 
2126
        :param relpath: provides for clients to get a path relative to the base
 
2127
            url.  These should only be downwards relative, not upwards.
 
2128
        :return: A URL
 
2129
        """
 
2130
        base = self.get_vfs_only_server().get_url()
 
2131
        return self._adjust_url(base, relpath)
 
2132
 
 
2133
    def _create_safety_net(self):
 
2134
        """Make a fake bzr directory.
 
2135
 
 
2136
        This prevents any tests propagating up onto the TEST_ROOT directory's
 
2137
        real branch.
 
2138
        """
 
2139
        root = TestCaseWithMemoryTransport.TEST_ROOT
 
2140
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
2141
 
 
2142
    def _check_safety_net(self):
 
2143
        """Check that the safety .bzr directory have not been touched.
 
2144
 
 
2145
        _make_test_root have created a .bzr directory to prevent tests from
 
2146
        propagating. This method ensures than a test did not leaked.
 
2147
        """
 
2148
        root = TestCaseWithMemoryTransport.TEST_ROOT
 
2149
        wt = workingtree.WorkingTree.open(root)
 
2150
        last_rev = wt.last_revision()
 
2151
        if last_rev != 'null:':
 
2152
            # The current test have modified the /bzr directory, we need to
 
2153
            # recreate a new one or all the followng tests will fail.
 
2154
            # If you need to inspect its content uncomment the following line
 
2155
            # import pdb; pdb.set_trace()
 
2156
            _rmtree_temp_dir(root + '/.bzr')
 
2157
            self._create_safety_net()
 
2158
            raise AssertionError('%s/.bzr should not be modified' % root)
 
2159
 
 
2160
    def _make_test_root(self):
 
2161
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
 
2162
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
 
2163
            TestCaseWithMemoryTransport.TEST_ROOT = root
 
2164
 
 
2165
            self._create_safety_net()
 
2166
 
 
2167
            # The same directory is used by all tests, and we're not
 
2168
            # specifically told when all tests are finished.  This will do.
 
2169
            atexit.register(_rmtree_temp_dir, root)
 
2170
 
 
2171
        self.addCleanup(self._check_safety_net)
 
2172
 
 
2173
    def makeAndChdirToTestDir(self):
 
2174
        """Create a temporary directories for this one test.
 
2175
 
 
2176
        This must set self.test_home_dir and self.test_dir and chdir to
 
2177
        self.test_dir.
 
2178
 
 
2179
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
 
2180
        """
 
2181
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
 
2182
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
 
2183
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
 
2184
 
 
2185
    def make_branch(self, relpath, format=None):
 
2186
        """Create a branch on the transport at relpath."""
 
2187
        repo = self.make_repository(relpath, format=format)
 
2188
        return repo.bzrdir.create_branch()
 
2189
 
 
2190
    def make_bzrdir(self, relpath, format=None):
 
2191
        try:
 
2192
            # might be a relative or absolute path
 
2193
            maybe_a_url = self.get_url(relpath)
 
2194
            segments = maybe_a_url.rsplit('/', 1)
 
2195
            t = get_transport(maybe_a_url)
 
2196
            if len(segments) > 1 and segments[-1] not in ('', '.'):
 
2197
                t.ensure_base()
 
2198
            if format is None:
 
2199
                format = 'default'
 
2200
            if isinstance(format, basestring):
 
2201
                format = bzrdir.format_registry.make_bzrdir(format)
 
2202
            return format.initialize_on_transport(t)
 
2203
        except errors.UninitializableFormat:
 
2204
            raise TestSkipped("Format %s is not initializable." % format)
 
2205
 
 
2206
    def make_repository(self, relpath, shared=False, format=None):
 
2207
        """Create a repository on our default transport at relpath.
 
2208
 
 
2209
        Note that relpath must be a relative path, not a full url.
 
2210
        """
 
2211
        # FIXME: If you create a remoterepository this returns the underlying
 
2212
        # real format, which is incorrect.  Actually we should make sure that
 
2213
        # RemoteBzrDir returns a RemoteRepository.
 
2214
        # maybe  mbp 20070410
 
2215
        made_control = self.make_bzrdir(relpath, format=format)
 
2216
        return made_control.create_repository(shared=shared)
 
2217
 
 
2218
    def make_smart_server(self, path):
 
2219
        smart_server = server.SmartTCPServer_for_testing()
 
2220
        smart_server.setUp(self.get_server())
 
2221
        remote_transport = get_transport(smart_server.get_url()).clone(path)
 
2222
        self.addCleanup(smart_server.tearDown)
 
2223
        return remote_transport
 
2224
 
 
2225
    def make_branch_and_memory_tree(self, relpath, format=None):
 
2226
        """Create a branch on the default transport and a MemoryTree for it."""
 
2227
        b = self.make_branch(relpath, format=format)
 
2228
        return memorytree.MemoryTree.create_on_branch(b)
 
2229
 
 
2230
    def make_branch_builder(self, relpath, format=None):
 
2231
        branch = self.make_branch(relpath, format=format)
 
2232
        return branchbuilder.BranchBuilder(branch=branch)
 
2233
 
 
2234
    def overrideEnvironmentForTesting(self):
 
2235
        os.environ['HOME'] = self.test_home_dir
 
2236
        os.environ['BZR_HOME'] = self.test_home_dir
 
2237
 
 
2238
    def setUp(self):
 
2239
        super(TestCaseWithMemoryTransport, self).setUp()
 
2240
        self._make_test_root()
 
2241
        _currentdir = os.getcwdu()
 
2242
        def _leaveDirectory():
 
2243
            os.chdir(_currentdir)
 
2244
        self.addCleanup(_leaveDirectory)
 
2245
        self.makeAndChdirToTestDir()
 
2246
        self.overrideEnvironmentForTesting()
 
2247
        self.__readonly_server = None
 
2248
        self.__server = None
 
2249
        self.reduceLockdirTimeout()
 
2250
 
 
2251
    def setup_smart_server_with_call_log(self):
 
2252
        """Sets up a smart server as the transport server with a call log."""
 
2253
        self.transport_server = server.SmartTCPServer_for_testing
 
2254
        self.hpss_calls = []
 
2255
        import traceback
 
2256
        # Skip the current stack down to the caller of
 
2257
        # setup_smart_server_with_call_log
 
2258
        prefix_length = len(traceback.extract_stack()) - 2
 
2259
        def capture_hpss_call(params):
 
2260
            self.hpss_calls.append(
 
2261
                CapturedCall(params, prefix_length))
 
2262
        client._SmartClient.hooks.install_named_hook(
 
2263
            'call', capture_hpss_call, None)
 
2264
 
 
2265
    def reset_smart_call_log(self):
 
2266
        self.hpss_calls = []
 
2267
 
 
2268
 
 
2269
class TestCaseInTempDir(TestCaseWithMemoryTransport):
 
2270
    """Derived class that runs a test within a temporary directory.
 
2271
 
 
2272
    This is useful for tests that need to create a branch, etc.
 
2273
 
 
2274
    The directory is created in a slightly complex way: for each
 
2275
    Python invocation, a new temporary top-level directory is created.
 
2276
    All test cases create their own directory within that.  If the
 
2277
    tests complete successfully, the directory is removed.
 
2278
 
 
2279
    :ivar test_base_dir: The path of the top-level directory for this
 
2280
    test, which contains a home directory and a work directory.
 
2281
 
 
2282
    :ivar test_home_dir: An initially empty directory under test_base_dir
 
2283
    which is used as $HOME for this test.
 
2284
 
 
2285
    :ivar test_dir: A directory under test_base_dir used as the current
 
2286
    directory when the test proper is run.
 
2287
    """
 
2288
 
 
2289
    OVERRIDE_PYTHON = 'python'
 
2290
 
 
2291
    def check_file_contents(self, filename, expect):
 
2292
        self.log("check contents of file %s" % filename)
 
2293
        contents = file(filename, 'r').read()
 
2294
        if contents != expect:
 
2295
            self.log("expected: %r" % expect)
 
2296
            self.log("actually: %r" % contents)
 
2297
            self.fail("contents of %s not as expected" % filename)
 
2298
 
 
2299
    def _getTestDirPrefix(self):
 
2300
        # create a directory within the top level test directory
 
2301
        if sys.platform == 'win32':
 
2302
            name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
 
2303
            # windows is likely to have path-length limits so use a short name
 
2304
            name_prefix = name_prefix[-30:]
 
2305
        else:
 
2306
            name_prefix = re.sub('[/]', '_', self.id())
 
2307
        return name_prefix
 
2308
 
 
2309
    def makeAndChdirToTestDir(self):
 
2310
        """See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
 
2311
 
 
2312
        For TestCaseInTempDir we create a temporary directory based on the test
 
2313
        name and then create two subdirs - test and home under it.
 
2314
        """
 
2315
        name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
 
2316
            self._getTestDirPrefix())
 
2317
        name = name_prefix
 
2318
        for i in range(100):
 
2319
            if os.path.exists(name):
 
2320
                name = name_prefix + '_' + str(i)
 
2321
            else:
 
2322
                os.mkdir(name)
 
2323
                break
 
2324
        # now create test and home directories within this dir
 
2325
        self.test_base_dir = name
 
2326
        self.test_home_dir = self.test_base_dir + '/home'
 
2327
        os.mkdir(self.test_home_dir)
 
2328
        self.test_dir = self.test_base_dir + '/work'
 
2329
        os.mkdir(self.test_dir)
 
2330
        os.chdir(self.test_dir)
 
2331
        # put name of test inside
 
2332
        f = file(self.test_base_dir + '/name', 'w')
 
2333
        try:
 
2334
            f.write(self.id())
 
2335
        finally:
 
2336
            f.close()
 
2337
        self.addCleanup(self.deleteTestDir)
 
2338
 
 
2339
    def deleteTestDir(self):
 
2340
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
 
2341
        _rmtree_temp_dir(self.test_base_dir)
 
2342
 
 
2343
    def build_tree(self, shape, line_endings='binary', transport=None):
 
2344
        """Build a test tree according to a pattern.
 
2345
 
 
2346
        shape is a sequence of file specifications.  If the final
 
2347
        character is '/', a directory is created.
 
2348
 
 
2349
        This assumes that all the elements in the tree being built are new.
 
2350
 
 
2351
        This doesn't add anything to a branch.
 
2352
 
 
2353
        :type shape:    list or tuple.
 
2354
        :param line_endings: Either 'binary' or 'native'
 
2355
            in binary mode, exact contents are written in native mode, the
 
2356
            line endings match the default platform endings.
 
2357
        :param transport: A transport to write to, for building trees on VFS's.
 
2358
            If the transport is readonly or None, "." is opened automatically.
 
2359
        :return: None
 
2360
        """
 
2361
        if type(shape) not in (list, tuple):
 
2362
            raise AssertionError("Parameter 'shape' should be "
 
2363
                "a list or a tuple. Got %r instead" % (shape,))
 
2364
        # It's OK to just create them using forward slashes on windows.
 
2365
        if transport is None or transport.is_readonly():
 
2366
            transport = get_transport(".")
 
2367
        for name in shape:
 
2368
            self.assertIsInstance(name, basestring)
 
2369
            if name[-1] == '/':
 
2370
                transport.mkdir(urlutils.escape(name[:-1]))
 
2371
            else:
 
2372
                if line_endings == 'binary':
 
2373
                    end = '\n'
 
2374
                elif line_endings == 'native':
 
2375
                    end = os.linesep
 
2376
                else:
 
2377
                    raise errors.BzrError(
 
2378
                        'Invalid line ending request %r' % line_endings)
 
2379
                content = "contents of %s%s" % (name.encode('utf-8'), end)
 
2380
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
 
2381
 
 
2382
    def build_tree_contents(self, shape):
 
2383
        build_tree_contents(shape)
 
2384
 
 
2385
    def assertInWorkingTree(self, path, root_path='.', tree=None):
 
2386
        """Assert whether path or paths are in the WorkingTree"""
 
2387
        if tree is None:
 
2388
            tree = workingtree.WorkingTree.open(root_path)
 
2389
        if not isinstance(path, basestring):
 
2390
            for p in path:
 
2391
                self.assertInWorkingTree(p, tree=tree)
 
2392
        else:
 
2393
            self.assertIsNot(tree.path2id(path), None,
 
2394
                path+' not in working tree.')
 
2395
 
 
2396
    def assertNotInWorkingTree(self, path, root_path='.', tree=None):
 
2397
        """Assert whether path or paths are not in the WorkingTree"""
 
2398
        if tree is None:
 
2399
            tree = workingtree.WorkingTree.open(root_path)
 
2400
        if not isinstance(path, basestring):
 
2401
            for p in path:
 
2402
                self.assertNotInWorkingTree(p,tree=tree)
 
2403
        else:
 
2404
            self.assertIs(tree.path2id(path), None, path+' in working tree.')
 
2405
 
 
2406
 
 
2407
class TestCaseWithTransport(TestCaseInTempDir):
 
2408
    """A test case that provides get_url and get_readonly_url facilities.
 
2409
 
 
2410
    These back onto two transport servers, one for readonly access and one for
 
2411
    read write access.
 
2412
 
 
2413
    If no explicit class is provided for readonly access, a
 
2414
    ReadonlyTransportDecorator is used instead which allows the use of non disk
 
2415
    based read write transports.
 
2416
 
 
2417
    If an explicit class is provided for readonly access, that server and the
 
2418
    readwrite one must both define get_url() as resolving to os.getcwd().
 
2419
    """
 
2420
 
 
2421
    def get_vfs_only_server(self):
 
2422
        """See TestCaseWithMemoryTransport.
 
2423
 
 
2424
        This is useful for some tests with specific servers that need
 
2425
        diagnostics.
 
2426
        """
 
2427
        if self.__vfs_server is None:
 
2428
            self.__vfs_server = self.vfs_transport_factory()
 
2429
            self.__vfs_server.setUp()
 
2430
            self.addCleanup(self.__vfs_server.tearDown)
 
2431
        return self.__vfs_server
 
2432
 
 
2433
    def make_branch_and_tree(self, relpath, format=None):
 
2434
        """Create a branch on the transport and a tree locally.
 
2435
 
 
2436
        If the transport is not a LocalTransport, the Tree can't be created on
 
2437
        the transport.  In that case if the vfs_transport_factory is
 
2438
        LocalURLServer the working tree is created in the local
 
2439
        directory backing the transport, and the returned tree's branch and
 
2440
        repository will also be accessed locally. Otherwise a lightweight
 
2441
        checkout is created and returned.
 
2442
 
 
2443
        :param format: The BzrDirFormat.
 
2444
        :returns: the WorkingTree.
 
2445
        """
 
2446
        # TODO: always use the local disk path for the working tree,
 
2447
        # this obviously requires a format that supports branch references
 
2448
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
 
2449
        # RBC 20060208
 
2450
        b = self.make_branch(relpath, format=format)
 
2451
        try:
 
2452
            return b.bzrdir.create_workingtree()
 
2453
        except errors.NotLocalUrl:
 
2454
            # We can only make working trees locally at the moment.  If the
 
2455
            # transport can't support them, then we keep the non-disk-backed
 
2456
            # branch and create a local checkout.
 
2457
            if self.vfs_transport_factory is LocalURLServer:
 
2458
                # the branch is colocated on disk, we cannot create a checkout.
 
2459
                # hopefully callers will expect this.
 
2460
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
 
2461
                wt = local_controldir.create_workingtree()
 
2462
                if wt.branch._format != b._format:
 
2463
                    wt._branch = b
 
2464
                    # Make sure that assigning to wt._branch fixes wt.branch,
 
2465
                    # in case the implementation details of workingtree objects
 
2466
                    # change.
 
2467
                    self.assertIs(b, wt.branch)
 
2468
                return wt
 
2469
            else:
 
2470
                return b.create_checkout(relpath, lightweight=True)
 
2471
 
 
2472
    def assertIsDirectory(self, relpath, transport):
 
2473
        """Assert that relpath within transport is a directory.
 
2474
 
 
2475
        This may not be possible on all transports; in that case it propagates
 
2476
        a TransportNotPossible.
 
2477
        """
 
2478
        try:
 
2479
            mode = transport.stat(relpath).st_mode
 
2480
        except errors.NoSuchFile:
 
2481
            self.fail("path %s is not a directory; no such file"
 
2482
                      % (relpath))
 
2483
        if not stat.S_ISDIR(mode):
 
2484
            self.fail("path %s is not a directory; has mode %#o"
 
2485
                      % (relpath, mode))
 
2486
 
 
2487
    def assertTreesEqual(self, left, right):
 
2488
        """Check that left and right have the same content and properties."""
 
2489
        # we use a tree delta to check for equality of the content, and we
 
2490
        # manually check for equality of other things such as the parents list.
 
2491
        self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
 
2492
        differences = left.changes_from(right)
 
2493
        self.assertFalse(differences.has_changed(),
 
2494
            "Trees %r and %r are different: %r" % (left, right, differences))
 
2495
 
 
2496
    def setUp(self):
 
2497
        super(TestCaseWithTransport, self).setUp()
 
2498
        self.__vfs_server = None
 
2499
 
 
2500
 
 
2501
class ChrootedTestCase(TestCaseWithTransport):
 
2502
    """A support class that provides readonly urls outside the local namespace.
 
2503
 
 
2504
    This is done by checking if self.transport_server is a MemoryServer. if it
 
2505
    is then we are chrooted already, if it is not then an HttpServer is used
 
2506
    for readonly urls.
 
2507
 
 
2508
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
 
2509
                       be used without needed to redo it when a different
 
2510
                       subclass is in use ?
 
2511
    """
 
2512
 
 
2513
    def setUp(self):
 
2514
        super(ChrootedTestCase, self).setUp()
 
2515
        if not self.vfs_transport_factory == MemoryServer:
 
2516
            self.transport_readonly_server = HttpServer
 
2517
 
 
2518
 
 
2519
def condition_id_re(pattern):
 
2520
    """Create a condition filter which performs a re check on a test's id.
 
2521
 
 
2522
    :param pattern: A regular expression string.
 
2523
    :return: A callable that returns True if the re matches.
 
2524
    """
 
2525
    filter_re = osutils.re_compile_checked(pattern, 0,
 
2526
        'test filter')
 
2527
    def condition(test):
 
2528
        test_id = test.id()
 
2529
        return filter_re.search(test_id)
 
2530
    return condition
 
2531
 
 
2532
 
 
2533
def condition_isinstance(klass_or_klass_list):
 
2534
    """Create a condition filter which returns isinstance(param, klass).
 
2535
 
 
2536
    :return: A callable which when called with one parameter obj return the
 
2537
        result of isinstance(obj, klass_or_klass_list).
 
2538
    """
 
2539
    def condition(obj):
 
2540
        return isinstance(obj, klass_or_klass_list)
 
2541
    return condition
 
2542
 
 
2543
 
 
2544
def condition_id_in_list(id_list):
 
2545
    """Create a condition filter which verify that test's id in a list.
 
2546
 
 
2547
    :param id_list: A TestIdList object.
 
2548
    :return: A callable that returns True if the test's id appears in the list.
 
2549
    """
 
2550
    def condition(test):
 
2551
        return id_list.includes(test.id())
 
2552
    return condition
 
2553
 
 
2554
 
 
2555
def condition_id_startswith(starts):
 
2556
    """Create a condition filter verifying that test's id starts with a string.
 
2557
 
 
2558
    :param starts: A list of string.
 
2559
    :return: A callable that returns True if the test's id starts with one of
 
2560
        the given strings.
 
2561
    """
 
2562
    def condition(test):
 
2563
        for start in starts:
 
2564
            if test.id().startswith(start):
 
2565
                return True
 
2566
        return False
 
2567
    return condition
 
2568
 
 
2569
 
 
2570
def exclude_tests_by_condition(suite, condition):
 
2571
    """Create a test suite which excludes some tests from suite.
 
2572
 
 
2573
    :param suite: The suite to get tests from.
 
2574
    :param condition: A callable whose result evaluates True when called with a
 
2575
        test case which should be excluded from the result.
 
2576
    :return: A suite which contains the tests found in suite that fail
 
2577
        condition.
 
2578
    """
 
2579
    result = []
 
2580
    for test in iter_suite_tests(suite):
 
2581
        if not condition(test):
 
2582
            result.append(test)
 
2583
    return TestUtil.TestSuite(result)
 
2584
 
 
2585
 
 
2586
def filter_suite_by_condition(suite, condition):
 
2587
    """Create a test suite by filtering another one.
 
2588
 
 
2589
    :param suite: The source suite.
 
2590
    :param condition: A callable whose result evaluates True when called with a
 
2591
        test case which should be included in the result.
 
2592
    :return: A suite which contains the tests found in suite that pass
 
2593
        condition.
 
2594
    """
 
2595
    result = []
 
2596
    for test in iter_suite_tests(suite):
 
2597
        if condition(test):
 
2598
            result.append(test)
 
2599
    return TestUtil.TestSuite(result)
 
2600
 
 
2601
 
 
2602
def filter_suite_by_re(suite, pattern):
 
2603
    """Create a test suite by filtering another one.
 
2604
 
 
2605
    :param suite:           the source suite
 
2606
    :param pattern:         pattern that names must match
 
2607
    :returns: the newly created suite
 
2608
    """
 
2609
    condition = condition_id_re(pattern)
 
2610
    result_suite = filter_suite_by_condition(suite, condition)
 
2611
    return result_suite
 
2612
 
 
2613
 
 
2614
def filter_suite_by_id_list(suite, test_id_list):
 
2615
    """Create a test suite by filtering another one.
 
2616
 
 
2617
    :param suite: The source suite.
 
2618
    :param test_id_list: A list of the test ids to keep as strings.
 
2619
    :returns: the newly created suite
 
2620
    """
 
2621
    condition = condition_id_in_list(test_id_list)
 
2622
    result_suite = filter_suite_by_condition(suite, condition)
 
2623
    return result_suite
 
2624
 
 
2625
 
 
2626
def filter_suite_by_id_startswith(suite, start):
 
2627
    """Create a test suite by filtering another one.
 
2628
 
 
2629
    :param suite: The source suite.
 
2630
    :param start: A list of string the test id must start with one of.
 
2631
    :returns: the newly created suite
 
2632
    """
 
2633
    condition = condition_id_startswith(start)
 
2634
    result_suite = filter_suite_by_condition(suite, condition)
 
2635
    return result_suite
 
2636
 
 
2637
 
 
2638
def exclude_tests_by_re(suite, pattern):
 
2639
    """Create a test suite which excludes some tests from suite.
 
2640
 
 
2641
    :param suite: The suite to get tests from.
 
2642
    :param pattern: A regular expression string. Test ids that match this
 
2643
        pattern will be excluded from the result.
 
2644
    :return: A TestSuite that contains all the tests from suite without the
 
2645
        tests that matched pattern. The order of tests is the same as it was in
 
2646
        suite.
 
2647
    """
 
2648
    return exclude_tests_by_condition(suite, condition_id_re(pattern))
 
2649
 
 
2650
 
 
2651
def preserve_input(something):
 
2652
    """A helper for performing test suite transformation chains.
 
2653
 
 
2654
    :param something: Anything you want to preserve.
 
2655
    :return: Something.
 
2656
    """
 
2657
    return something
 
2658
 
 
2659
 
 
2660
def randomize_suite(suite):
 
2661
    """Return a new TestSuite with suite's tests in random order.
 
2662
 
 
2663
    The tests in the input suite are flattened into a single suite in order to
 
2664
    accomplish this. Any nested TestSuites are removed to provide global
 
2665
    randomness.
 
2666
    """
 
2667
    tests = list(iter_suite_tests(suite))
 
2668
    random.shuffle(tests)
 
2669
    return TestUtil.TestSuite(tests)
 
2670
 
 
2671
 
 
2672
def split_suite_by_condition(suite, condition):
 
2673
    """Split a test suite into two by a condition.
 
2674
 
 
2675
    :param suite: The suite to split.
 
2676
    :param condition: The condition to match on. Tests that match this
 
2677
        condition are returned in the first test suite, ones that do not match
 
2678
        are in the second suite.
 
2679
    :return: A tuple of two test suites, where the first contains tests from
 
2680
        suite matching the condition, and the second contains the remainder
 
2681
        from suite. The order within each output suite is the same as it was in
 
2682
        suite.
 
2683
    """
 
2684
    matched = []
 
2685
    did_not_match = []
 
2686
    for test in iter_suite_tests(suite):
 
2687
        if condition(test):
 
2688
            matched.append(test)
 
2689
        else:
 
2690
            did_not_match.append(test)
 
2691
    return TestUtil.TestSuite(matched), TestUtil.TestSuite(did_not_match)
 
2692
 
 
2693
 
 
2694
def split_suite_by_re(suite, pattern):
 
2695
    """Split a test suite into two by a regular expression.
 
2696
 
 
2697
    :param suite: The suite to split.
 
2698
    :param pattern: A regular expression string. Test ids that match this
 
2699
        pattern will be in the first test suite returned, and the others in the
 
2700
        second test suite returned.
 
2701
    :return: A tuple of two test suites, where the first contains tests from
 
2702
        suite matching pattern, and the second contains the remainder from
 
2703
        suite. The order within each output suite is the same as it was in
 
2704
        suite.
 
2705
    """
 
2706
    return split_suite_by_condition(suite, condition_id_re(pattern))
 
2707
 
 
2708
 
 
2709
def run_suite(suite, name='test', verbose=False, pattern=".*",
 
2710
              stop_on_failure=False,
 
2711
              transport=None, lsprof_timed=None, bench_history=None,
 
2712
              matching_tests_first=None,
 
2713
              list_only=False,
 
2714
              random_seed=None,
 
2715
              exclude_pattern=None,
 
2716
              strict=False,
 
2717
              runner_class=None,
 
2718
              suite_decorators=None,
 
2719
              stream=None):
 
2720
    """Run a test suite for bzr selftest.
 
2721
 
 
2722
    :param runner_class: The class of runner to use. Must support the
 
2723
        constructor arguments passed by run_suite which are more than standard
 
2724
        python uses.
 
2725
    :return: A boolean indicating success.
 
2726
    """
 
2727
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
 
2728
    if verbose:
 
2729
        verbosity = 2
 
2730
    else:
 
2731
        verbosity = 1
 
2732
    if runner_class is None:
 
2733
        runner_class = TextTestRunner
 
2734
    if stream is None:
 
2735
        stream = sys.stdout
 
2736
    runner = runner_class(stream=stream,
 
2737
                            descriptions=0,
 
2738
                            verbosity=verbosity,
 
2739
                            bench_history=bench_history,
 
2740
                            list_only=list_only,
 
2741
                            strict=strict,
 
2742
                            )
 
2743
    runner.stop_on_failure=stop_on_failure
 
2744
    # built in decorator factories:
 
2745
    decorators = [
 
2746
        random_order(random_seed, runner),
 
2747
        exclude_tests(exclude_pattern),
 
2748
        ]
 
2749
    if matching_tests_first:
 
2750
        decorators.append(tests_first(pattern))
 
2751
    else:
 
2752
        decorators.append(filter_tests(pattern))
 
2753
    if suite_decorators:
 
2754
        decorators.extend(suite_decorators)
 
2755
    for decorator in decorators:
 
2756
        suite = decorator(suite)
 
2757
    result = runner.run(suite)
 
2758
    if list_only:
 
2759
        return True
 
2760
    result.done()
 
2761
    if strict:
 
2762
        return result.wasStrictlySuccessful()
 
2763
    else:
 
2764
        return result.wasSuccessful()
 
2765
 
 
2766
 
 
2767
# A registry where get() returns a suite decorator.
 
2768
parallel_registry = registry.Registry()
 
2769
 
 
2770
 
 
2771
def fork_decorator(suite):
 
2772
    concurrency = osutils.local_concurrency()
 
2773
    if concurrency == 1:
 
2774
        return suite
 
2775
    from testtools import ConcurrentTestSuite
 
2776
    return ConcurrentTestSuite(suite, fork_for_tests)
 
2777
parallel_registry.register('fork', fork_decorator)
 
2778
 
 
2779
 
 
2780
def subprocess_decorator(suite):
 
2781
    concurrency = osutils.local_concurrency()
 
2782
    if concurrency == 1:
 
2783
        return suite
 
2784
    from testtools import ConcurrentTestSuite
 
2785
    return ConcurrentTestSuite(suite, reinvoke_for_tests)
 
2786
parallel_registry.register('subprocess', subprocess_decorator)
 
2787
 
 
2788
 
 
2789
def exclude_tests(exclude_pattern):
 
2790
    """Return a test suite decorator that excludes tests."""
 
2791
    if exclude_pattern is None:
 
2792
        return identity_decorator
 
2793
    def decorator(suite):
 
2794
        return ExcludeDecorator(suite, exclude_pattern)
 
2795
    return decorator
 
2796
 
 
2797
 
 
2798
def filter_tests(pattern):
 
2799
    if pattern == '.*':
 
2800
        return identity_decorator
 
2801
    def decorator(suite):
 
2802
        return FilterTestsDecorator(suite, pattern)
 
2803
    return decorator
 
2804
 
 
2805
 
 
2806
def random_order(random_seed, runner):
 
2807
    """Return a test suite decorator factory for randomising tests order.
 
2808
    
 
2809
    :param random_seed: now, a string which casts to a long, or a long.
 
2810
    :param runner: A test runner with a stream attribute to report on.
 
2811
    """
 
2812
    if random_seed is None:
 
2813
        return identity_decorator
 
2814
    def decorator(suite):
 
2815
        return RandomDecorator(suite, random_seed, runner.stream)
 
2816
    return decorator
 
2817
 
 
2818
 
 
2819
def tests_first(pattern):
 
2820
    if pattern == '.*':
 
2821
        return identity_decorator
 
2822
    def decorator(suite):
 
2823
        return TestFirstDecorator(suite, pattern)
 
2824
    return decorator
 
2825
 
 
2826
 
 
2827
def identity_decorator(suite):
 
2828
    """Return suite."""
 
2829
    return suite
 
2830
 
 
2831
 
 
2832
class TestDecorator(TestSuite):
 
2833
    """A decorator for TestCase/TestSuite objects.
 
2834
    
 
2835
    Usually, subclasses should override __iter__(used when flattening test
 
2836
    suites), which we do to filter, reorder, parallelise and so on, run() and
 
2837
    debug().
 
2838
    """
 
2839
 
 
2840
    def __init__(self, suite):
 
2841
        TestSuite.__init__(self)
 
2842
        self.addTest(suite)
 
2843
 
 
2844
    def countTestCases(self):
 
2845
        cases = 0
 
2846
        for test in self:
 
2847
            cases += test.countTestCases()
 
2848
        return cases
 
2849
 
 
2850
    def debug(self):
 
2851
        for test in self:
 
2852
            test.debug()
 
2853
 
 
2854
    def run(self, result):
 
2855
        # Use iteration on self, not self._tests, to allow subclasses to hook
 
2856
        # into __iter__.
 
2857
        for test in self:
 
2858
            if result.shouldStop:
 
2859
                break
 
2860
            test.run(result)
 
2861
        return result
 
2862
 
 
2863
 
 
2864
class ExcludeDecorator(TestDecorator):
 
2865
    """A decorator which excludes test matching an exclude pattern."""
 
2866
 
 
2867
    def __init__(self, suite, exclude_pattern):
 
2868
        TestDecorator.__init__(self, suite)
 
2869
        self.exclude_pattern = exclude_pattern
 
2870
        self.excluded = False
 
2871
 
 
2872
    def __iter__(self):
 
2873
        if self.excluded:
 
2874
            return iter(self._tests)
 
2875
        self.excluded = True
 
2876
        suite = exclude_tests_by_re(self, self.exclude_pattern)
 
2877
        del self._tests[:]
 
2878
        self.addTests(suite)
 
2879
        return iter(self._tests)
 
2880
 
 
2881
 
 
2882
class FilterTestsDecorator(TestDecorator):
 
2883
    """A decorator which filters tests to those matching a pattern."""
 
2884
 
 
2885
    def __init__(self, suite, pattern):
 
2886
        TestDecorator.__init__(self, suite)
 
2887
        self.pattern = pattern
 
2888
        self.filtered = False
 
2889
 
 
2890
    def __iter__(self):
 
2891
        if self.filtered:
 
2892
            return iter(self._tests)
 
2893
        self.filtered = True
 
2894
        suite = filter_suite_by_re(self, self.pattern)
 
2895
        del self._tests[:]
 
2896
        self.addTests(suite)
 
2897
        return iter(self._tests)
 
2898
 
 
2899
 
 
2900
class RandomDecorator(TestDecorator):
 
2901
    """A decorator which randomises the order of its tests."""
 
2902
 
 
2903
    def __init__(self, suite, random_seed, stream):
 
2904
        TestDecorator.__init__(self, suite)
 
2905
        self.random_seed = random_seed
 
2906
        self.randomised = False
 
2907
        self.stream = stream
 
2908
 
 
2909
    def __iter__(self):
 
2910
        if self.randomised:
 
2911
            return iter(self._tests)
 
2912
        self.randomised = True
 
2913
        self.stream.writeln("Randomizing test order using seed %s\n" %
 
2914
            (self.actual_seed()))
 
2915
        # Initialise the random number generator.
 
2916
        random.seed(self.actual_seed())
 
2917
        suite = randomize_suite(self)
 
2918
        del self._tests[:]
 
2919
        self.addTests(suite)
 
2920
        return iter(self._tests)
 
2921
 
 
2922
    def actual_seed(self):
 
2923
        if self.random_seed == "now":
 
2924
            # We convert the seed to a long to make it reuseable across
 
2925
            # invocations (because the user can reenter it).
 
2926
            self.random_seed = long(time.time())
 
2927
        else:
 
2928
            # Convert the seed to a long if we can
 
2929
            try:
 
2930
                self.random_seed = long(self.random_seed)
 
2931
            except:
 
2932
                pass
 
2933
        return self.random_seed
 
2934
 
 
2935
 
 
2936
class TestFirstDecorator(TestDecorator):
 
2937
    """A decorator which moves named tests to the front."""
 
2938
 
 
2939
    def __init__(self, suite, pattern):
 
2940
        TestDecorator.__init__(self, suite)
 
2941
        self.pattern = pattern
 
2942
        self.filtered = False
 
2943
 
 
2944
    def __iter__(self):
 
2945
        if self.filtered:
 
2946
            return iter(self._tests)
 
2947
        self.filtered = True
 
2948
        suites = split_suite_by_re(self, self.pattern)
 
2949
        del self._tests[:]
 
2950
        self.addTests(suites)
 
2951
        return iter(self._tests)
 
2952
 
 
2953
 
 
2954
def partition_tests(suite, count):
 
2955
    """Partition suite into count lists of tests."""
 
2956
    result = []
 
2957
    tests = list(iter_suite_tests(suite))
 
2958
    tests_per_process = int(math.ceil(float(len(tests)) / count))
 
2959
    for block in range(count):
 
2960
        low_test = block * tests_per_process
 
2961
        high_test = low_test + tests_per_process
 
2962
        process_tests = tests[low_test:high_test]
 
2963
        result.append(process_tests)
 
2964
    return result
 
2965
 
 
2966
 
 
2967
def fork_for_tests(suite):
 
2968
    """Take suite and start up one runner per CPU by forking()
 
2969
 
 
2970
    :return: An iterable of TestCase-like objects which can each have
 
2971
        run(result) called on them to feed tests to result.
 
2972
    """
 
2973
    concurrency = osutils.local_concurrency()
 
2974
    result = []
 
2975
    from subunit import TestProtocolClient, ProtocolTestCase
 
2976
    class TestInOtherProcess(ProtocolTestCase):
 
2977
        # Should be in subunit, I think. RBC.
 
2978
        def __init__(self, stream, pid):
 
2979
            ProtocolTestCase.__init__(self, stream)
 
2980
            self.pid = pid
 
2981
 
 
2982
        def run(self, result):
 
2983
            try:
 
2984
                ProtocolTestCase.run(self, result)
 
2985
            finally:
 
2986
                os.waitpid(self.pid, os.WNOHANG)
 
2987
 
 
2988
    test_blocks = partition_tests(suite, concurrency)
 
2989
    for process_tests in test_blocks:
 
2990
        process_suite = TestSuite()
 
2991
        process_suite.addTests(process_tests)
 
2992
        c2pread, c2pwrite = os.pipe()
 
2993
        pid = os.fork()
 
2994
        if pid == 0:
 
2995
            try:
 
2996
                os.close(c2pread)
 
2997
                # Leave stderr and stdout open so we can see test noise
 
2998
                # Close stdin so that the child goes away if it decides to
 
2999
                # read from stdin (otherwise its a roulette to see what
 
3000
                # child actually gets keystrokes for pdb etc).
 
3001
                sys.stdin.close()
 
3002
                sys.stdin = None
 
3003
                stream = os.fdopen(c2pwrite, 'wb', 1)
 
3004
                subunit_result = TestProtocolClient(stream)
 
3005
                process_suite.run(subunit_result)
 
3006
            finally:
 
3007
                os._exit(0)
 
3008
        else:
 
3009
            os.close(c2pwrite)
 
3010
            stream = os.fdopen(c2pread, 'rb', 1)
 
3011
            test = TestInOtherProcess(stream, pid)
 
3012
            result.append(test)
 
3013
    return result
 
3014
 
 
3015
 
 
3016
def reinvoke_for_tests(suite):
 
3017
    """Take suite and start up one runner per CPU using subprocess().
 
3018
 
 
3019
    :return: An iterable of TestCase-like objects which can each have
 
3020
        run(result) called on them to feed tests to result.
 
3021
    """
 
3022
    concurrency = osutils.local_concurrency()
 
3023
    result = []
 
3024
    from subunit import ProtocolTestCase
 
3025
    class TestInSubprocess(ProtocolTestCase):
 
3026
        def __init__(self, process, name):
 
3027
            ProtocolTestCase.__init__(self, process.stdout)
 
3028
            self.process = process
 
3029
            self.process.stdin.close()
 
3030
            self.name = name
 
3031
 
 
3032
        def run(self, result):
 
3033
            try:
 
3034
                ProtocolTestCase.run(self, result)
 
3035
            finally:
 
3036
                self.process.wait()
 
3037
                os.unlink(self.name)
 
3038
            # print "pid %d finished" % finished_process
 
3039
    test_blocks = partition_tests(suite, concurrency)
 
3040
    for process_tests in test_blocks:
 
3041
        # ugly; currently reimplement rather than reuses TestCase methods.
 
3042
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
3043
        if not os.path.isfile(bzr_path):
 
3044
            # We are probably installed. Assume sys.argv is the right file
 
3045
            bzr_path = sys.argv[0]
 
3046
        fd, test_list_file_name = tempfile.mkstemp()
 
3047
        test_list_file = os.fdopen(fd, 'wb', 1)
 
3048
        for test in process_tests:
 
3049
            test_list_file.write(test.id() + '\n')
 
3050
        test_list_file.close()
 
3051
        try:
 
3052
            argv = [bzr_path, 'selftest', '--load-list', test_list_file_name,
 
3053
                '--subunit']
 
3054
            if '--no-plugins' in sys.argv:
 
3055
                argv.append('--no-plugins')
 
3056
            # stderr=STDOUT would be ideal, but until we prevent noise on
 
3057
            # stderr it can interrupt the subunit protocol.
 
3058
            process = Popen(argv, stdin=PIPE, stdout=PIPE, stderr=PIPE,
 
3059
                bufsize=1)
 
3060
            test = TestInSubprocess(process, test_list_file_name)
 
3061
            result.append(test)
 
3062
        except:
 
3063
            os.unlink(test_list_file_name)
 
3064
            raise
 
3065
    return result
 
3066
 
 
3067
 
 
3068
class BZRTransformingResult(unittest.TestResult):
 
3069
 
 
3070
    def __init__(self, target):
 
3071
        unittest.TestResult.__init__(self)
 
3072
        self.result = target
 
3073
 
 
3074
    def startTest(self, test):
 
3075
        self.result.startTest(test)
 
3076
 
 
3077
    def stopTest(self, test):
 
3078
        self.result.stopTest(test)
 
3079
 
 
3080
    def addError(self, test, err):
 
3081
        feature = self._error_looks_like('UnavailableFeature: ', err)
 
3082
        if feature is not None:
 
3083
            self.result.addNotSupported(test, feature)
 
3084
        else:
 
3085
            self.result.addError(test, err)
 
3086
 
 
3087
    def addFailure(self, test, err):
 
3088
        known = self._error_looks_like('KnownFailure: ', err)
 
3089
        if known is not None:
 
3090
            self.result._addKnownFailure(test, [KnownFailure,
 
3091
                                                KnownFailure(known), None])
 
3092
        else:
 
3093
            self.result.addFailure(test, err)
 
3094
 
 
3095
    def addSkip(self, test, reason):
 
3096
        self.result.addSkip(test, reason)
 
3097
 
 
3098
    def addSuccess(self, test):
 
3099
        self.result.addSuccess(test)
 
3100
 
 
3101
    def _error_looks_like(self, prefix, err):
 
3102
        """Deserialize exception and returns the stringify value."""
 
3103
        import subunit
 
3104
        value = None
 
3105
        typ, exc, _ = err
 
3106
        if isinstance(exc, subunit.RemoteException):
 
3107
            # stringify the exception gives access to the remote traceback
 
3108
            # We search the last line for 'prefix'
 
3109
            lines = str(exc).split('\n')
 
3110
            while lines and not lines[-1]:
 
3111
                lines.pop(-1)
 
3112
            if lines:
 
3113
                if lines[-1].startswith(prefix):
 
3114
                    value = lines[-1][len(prefix):]
 
3115
        return value
 
3116
 
 
3117
 
 
3118
# Controlled by "bzr selftest -E=..." option
 
3119
selftest_debug_flags = set()
 
3120
 
 
3121
 
 
3122
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
 
3123
             transport=None,
 
3124
             test_suite_factory=None,
 
3125
             lsprof_timed=None,
 
3126
             bench_history=None,
 
3127
             matching_tests_first=None,
 
3128
             list_only=False,
 
3129
             random_seed=None,
 
3130
             exclude_pattern=None,
 
3131
             strict=False,
 
3132
             load_list=None,
 
3133
             debug_flags=None,
 
3134
             starting_with=None,
 
3135
             runner_class=None,
 
3136
             suite_decorators=None,
 
3137
             ):
 
3138
    """Run the whole test suite under the enhanced runner"""
 
3139
    # XXX: Very ugly way to do this...
 
3140
    # Disable warning about old formats because we don't want it to disturb
 
3141
    # any blackbox tests.
 
3142
    from bzrlib import repository
 
3143
    repository._deprecation_warning_done = True
 
3144
 
 
3145
    global default_transport
 
3146
    if transport is None:
 
3147
        transport = default_transport
 
3148
    old_transport = default_transport
 
3149
    default_transport = transport
 
3150
    global selftest_debug_flags
 
3151
    old_debug_flags = selftest_debug_flags
 
3152
    if debug_flags is not None:
 
3153
        selftest_debug_flags = set(debug_flags)
 
3154
    try:
 
3155
        if load_list is None:
 
3156
            keep_only = None
 
3157
        else:
 
3158
            keep_only = load_test_id_list(load_list)
 
3159
        if test_suite_factory is None:
 
3160
            suite = test_suite(keep_only, starting_with)
 
3161
        else:
 
3162
            suite = test_suite_factory()
 
3163
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
 
3164
                     stop_on_failure=stop_on_failure,
 
3165
                     transport=transport,
 
3166
                     lsprof_timed=lsprof_timed,
 
3167
                     bench_history=bench_history,
 
3168
                     matching_tests_first=matching_tests_first,
 
3169
                     list_only=list_only,
 
3170
                     random_seed=random_seed,
 
3171
                     exclude_pattern=exclude_pattern,
 
3172
                     strict=strict,
 
3173
                     runner_class=runner_class,
 
3174
                     suite_decorators=suite_decorators,
 
3175
                     )
 
3176
    finally:
 
3177
        default_transport = old_transport
 
3178
        selftest_debug_flags = old_debug_flags
 
3179
 
 
3180
 
 
3181
def load_test_id_list(file_name):
 
3182
    """Load a test id list from a text file.
 
3183
 
 
3184
    The format is one test id by line.  No special care is taken to impose
 
3185
    strict rules, these test ids are used to filter the test suite so a test id
 
3186
    that do not match an existing test will do no harm. This allows user to add
 
3187
    comments, leave blank lines, etc.
 
3188
    """
 
3189
    test_list = []
 
3190
    try:
 
3191
        ftest = open(file_name, 'rt')
 
3192
    except IOError, e:
 
3193
        if e.errno != errno.ENOENT:
 
3194
            raise
 
3195
        else:
 
3196
            raise errors.NoSuchFile(file_name)
 
3197
 
 
3198
    for test_name in ftest.readlines():
 
3199
        test_list.append(test_name.strip())
 
3200
    ftest.close()
 
3201
    return test_list
 
3202
 
 
3203
 
 
3204
def suite_matches_id_list(test_suite, id_list):
 
3205
    """Warns about tests not appearing or appearing more than once.
 
3206
 
 
3207
    :param test_suite: A TestSuite object.
 
3208
    :param test_id_list: The list of test ids that should be found in
 
3209
         test_suite.
 
3210
 
 
3211
    :return: (absents, duplicates) absents is a list containing the test found
 
3212
        in id_list but not in test_suite, duplicates is a list containing the
 
3213
        test found multiple times in test_suite.
 
3214
 
 
3215
    When using a prefined test id list, it may occurs that some tests do not
 
3216
    exist anymore or that some tests use the same id. This function warns the
 
3217
    tester about potential problems in his workflow (test lists are volatile)
 
3218
    or in the test suite itself (using the same id for several tests does not
 
3219
    help to localize defects).
 
3220
    """
 
3221
    # Build a dict counting id occurrences
 
3222
    tests = dict()
 
3223
    for test in iter_suite_tests(test_suite):
 
3224
        id = test.id()
 
3225
        tests[id] = tests.get(id, 0) + 1
 
3226
 
 
3227
    not_found = []
 
3228
    duplicates = []
 
3229
    for id in id_list:
 
3230
        occurs = tests.get(id, 0)
 
3231
        if not occurs:
 
3232
            not_found.append(id)
 
3233
        elif occurs > 1:
 
3234
            duplicates.append(id)
 
3235
 
 
3236
    return not_found, duplicates
 
3237
 
 
3238
 
 
3239
class TestIdList(object):
 
3240
    """Test id list to filter a test suite.
 
3241
 
 
3242
    Relying on the assumption that test ids are built as:
 
3243
    <module>[.<class>.<method>][(<param>+)], <module> being in python dotted
 
3244
    notation, this class offers methods to :
 
3245
    - avoid building a test suite for modules not refered to in the test list,
 
3246
    - keep only the tests listed from the module test suite.
 
3247
    """
 
3248
 
 
3249
    def __init__(self, test_id_list):
 
3250
        # When a test suite needs to be filtered against us we compare test ids
 
3251
        # for equality, so a simple dict offers a quick and simple solution.
 
3252
        self.tests = dict().fromkeys(test_id_list, True)
 
3253
 
 
3254
        # While unittest.TestCase have ids like:
 
3255
        # <module>.<class>.<method>[(<param+)],
 
3256
        # doctest.DocTestCase can have ids like:
 
3257
        # <module>
 
3258
        # <module>.<class>
 
3259
        # <module>.<function>
 
3260
        # <module>.<class>.<method>
 
3261
 
 
3262
        # Since we can't predict a test class from its name only, we settle on
 
3263
        # a simple constraint: a test id always begins with its module name.
 
3264
 
 
3265
        modules = {}
 
3266
        for test_id in test_id_list:
 
3267
            parts = test_id.split('.')
 
3268
            mod_name = parts.pop(0)
 
3269
            modules[mod_name] = True
 
3270
            for part in parts:
 
3271
                mod_name += '.' + part
 
3272
                modules[mod_name] = True
 
3273
        self.modules = modules
 
3274
 
 
3275
    def refers_to(self, module_name):
 
3276
        """Is there tests for the module or one of its sub modules."""
 
3277
        return self.modules.has_key(module_name)
 
3278
 
 
3279
    def includes(self, test_id):
 
3280
        return self.tests.has_key(test_id)
 
3281
 
 
3282
 
 
3283
class TestPrefixAliasRegistry(registry.Registry):
 
3284
    """A registry for test prefix aliases.
 
3285
 
 
3286
    This helps implement shorcuts for the --starting-with selftest
 
3287
    option. Overriding existing prefixes is not allowed but not fatal (a
 
3288
    warning will be emitted).
 
3289
    """
 
3290
 
 
3291
    def register(self, key, obj, help=None, info=None,
 
3292
                 override_existing=False):
 
3293
        """See Registry.register.
 
3294
 
 
3295
        Trying to override an existing alias causes a warning to be emitted,
 
3296
        not a fatal execption.
 
3297
        """
 
3298
        try:
 
3299
            super(TestPrefixAliasRegistry, self).register(
 
3300
                key, obj, help=help, info=info, override_existing=False)
 
3301
        except KeyError:
 
3302
            actual = self.get(key)
 
3303
            note('Test prefix alias %s is already used for %s, ignoring %s'
 
3304
                 % (key, actual, obj))
 
3305
 
 
3306
    def resolve_alias(self, id_start):
 
3307
        """Replace the alias by the prefix in the given string.
 
3308
 
 
3309
        Using an unknown prefix is an error to help catching typos.
 
3310
        """
 
3311
        parts = id_start.split('.')
 
3312
        try:
 
3313
            parts[0] = self.get(parts[0])
 
3314
        except KeyError:
 
3315
            raise errors.BzrCommandError(
 
3316
                '%s is not a known test prefix alias' % parts[0])
 
3317
        return '.'.join(parts)
 
3318
 
 
3319
 
 
3320
test_prefix_alias_registry = TestPrefixAliasRegistry()
 
3321
"""Registry of test prefix aliases."""
 
3322
 
 
3323
 
 
3324
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
 
3325
# appear prefixed ('bzrlib.' is "replaced" by 'bzrlib.').
 
3326
test_prefix_alias_registry.register('bzrlib', 'bzrlib')
 
3327
 
 
3328
# Obvious higest levels prefixes, feel free to add your own via a plugin
 
3329
test_prefix_alias_registry.register('bd', 'bzrlib.doc')
 
3330
test_prefix_alias_registry.register('bu', 'bzrlib.utils')
 
3331
test_prefix_alias_registry.register('bt', 'bzrlib.tests')
 
3332
test_prefix_alias_registry.register('bb', 'bzrlib.tests.blackbox')
 
3333
test_prefix_alias_registry.register('bp', 'bzrlib.plugins')
 
3334
 
 
3335
 
 
3336
def test_suite(keep_only=None, starting_with=None):
 
3337
    """Build and return TestSuite for the whole of bzrlib.
 
3338
 
 
3339
    :param keep_only: A list of test ids limiting the suite returned.
 
3340
 
 
3341
    :param starting_with: An id limiting the suite returned to the tests
 
3342
         starting with it.
 
3343
 
 
3344
    This function can be replaced if you need to change the default test
 
3345
    suite on a global basis, but it is not encouraged.
 
3346
    """
 
3347
    testmod_names = [
 
3348
                   'bzrlib.doc',
 
3349
                   'bzrlib.tests.blackbox',
 
3350
                   'bzrlib.tests.commands',
 
3351
                   'bzrlib.tests.per_branch',
 
3352
                   'bzrlib.tests.per_bzrdir',
 
3353
                   'bzrlib.tests.per_interrepository',
 
3354
                   'bzrlib.tests.per_intertree',
 
3355
                   'bzrlib.tests.per_inventory',
 
3356
                   'bzrlib.tests.per_interbranch',
 
3357
                   'bzrlib.tests.per_lock',
 
3358
                   'bzrlib.tests.per_transport',
 
3359
                   'bzrlib.tests.per_tree',
 
3360
                   'bzrlib.tests.per_repository',
 
3361
                   'bzrlib.tests.per_repository_chk',
 
3362
                   'bzrlib.tests.per_repository_reference',
 
3363
                   'bzrlib.tests.per_workingtree',
 
3364
                   'bzrlib.tests.test__annotator',
 
3365
                   'bzrlib.tests.test__chk_map',
 
3366
                   'bzrlib.tests.test__dirstate_helpers',
 
3367
                   'bzrlib.tests.test__groupcompress',
 
3368
                   'bzrlib.tests.test__known_graph',
 
3369
                   'bzrlib.tests.test__rio',
 
3370
                   'bzrlib.tests.test__walkdirs_win32',
 
3371
                   'bzrlib.tests.test_ancestry',
 
3372
                   'bzrlib.tests.test_annotate',
 
3373
                   'bzrlib.tests.test_api',
 
3374
                   'bzrlib.tests.test_atomicfile',
 
3375
                   'bzrlib.tests.test_bad_files',
 
3376
                   'bzrlib.tests.test_bencode',
 
3377
                   'bzrlib.tests.test_bisect_multi',
 
3378
                   'bzrlib.tests.test_branch',
 
3379
                   'bzrlib.tests.test_branchbuilder',
 
3380
                   'bzrlib.tests.test_btree_index',
 
3381
                   'bzrlib.tests.test_bugtracker',
 
3382
                   'bzrlib.tests.test_bundle',
 
3383
                   'bzrlib.tests.test_bzrdir',
 
3384
                   'bzrlib.tests.test__chunks_to_lines',
 
3385
                   'bzrlib.tests.test_cache_utf8',
 
3386
                   'bzrlib.tests.test_chk_map',
 
3387
                   'bzrlib.tests.test_chk_serializer',
 
3388
                   'bzrlib.tests.test_chunk_writer',
 
3389
                   'bzrlib.tests.test_clean_tree',
 
3390
                   'bzrlib.tests.test_commands',
 
3391
                   'bzrlib.tests.test_commit',
 
3392
                   'bzrlib.tests.test_commit_merge',
 
3393
                   'bzrlib.tests.test_config',
 
3394
                   'bzrlib.tests.test_conflicts',
 
3395
                   'bzrlib.tests.test_counted_lock',
 
3396
                   'bzrlib.tests.test_decorators',
 
3397
                   'bzrlib.tests.test_delta',
 
3398
                   'bzrlib.tests.test_debug',
 
3399
                   'bzrlib.tests.test_deprecated_graph',
 
3400
                   'bzrlib.tests.test_diff',
 
3401
                   'bzrlib.tests.test_directory_service',
 
3402
                   'bzrlib.tests.test_dirstate',
 
3403
                   'bzrlib.tests.test_email_message',
 
3404
                   'bzrlib.tests.test_eol_filters',
 
3405
                   'bzrlib.tests.test_errors',
 
3406
                   'bzrlib.tests.test_export',
 
3407
                   'bzrlib.tests.test_extract',
 
3408
                   'bzrlib.tests.test_fetch',
 
3409
                   'bzrlib.tests.test_fifo_cache',
 
3410
                   'bzrlib.tests.test_filters',
 
3411
                   'bzrlib.tests.test_ftp_transport',
 
3412
                   'bzrlib.tests.test_foreign',
 
3413
                   'bzrlib.tests.test_generate_docs',
 
3414
                   'bzrlib.tests.test_generate_ids',
 
3415
                   'bzrlib.tests.test_globbing',
 
3416
                   'bzrlib.tests.test_gpg',
 
3417
                   'bzrlib.tests.test_graph',
 
3418
                   'bzrlib.tests.test_groupcompress',
 
3419
                   'bzrlib.tests.test_hashcache',
 
3420
                   'bzrlib.tests.test_help',
 
3421
                   'bzrlib.tests.test_hooks',
 
3422
                   'bzrlib.tests.test_http',
 
3423
                   'bzrlib.tests.test_http_response',
 
3424
                   'bzrlib.tests.test_https_ca_bundle',
 
3425
                   'bzrlib.tests.test_identitymap',
 
3426
                   'bzrlib.tests.test_ignores',
 
3427
                   'bzrlib.tests.test_index',
 
3428
                   'bzrlib.tests.test_info',
 
3429
                   'bzrlib.tests.test_inv',
 
3430
                   'bzrlib.tests.test_inventory_delta',
 
3431
                   'bzrlib.tests.test_knit',
 
3432
                   'bzrlib.tests.test_lazy_import',
 
3433
                   'bzrlib.tests.test_lazy_regex',
 
3434
                   'bzrlib.tests.test_lockable_files',
 
3435
                   'bzrlib.tests.test_lockdir',
 
3436
                   'bzrlib.tests.test_log',
 
3437
                   'bzrlib.tests.test_lru_cache',
 
3438
                   'bzrlib.tests.test_lsprof',
 
3439
                   'bzrlib.tests.test_mail_client',
 
3440
                   'bzrlib.tests.test_memorytree',
 
3441
                   'bzrlib.tests.test_merge',
 
3442
                   'bzrlib.tests.test_merge3',
 
3443
                   'bzrlib.tests.test_merge_core',
 
3444
                   'bzrlib.tests.test_merge_directive',
 
3445
                   'bzrlib.tests.test_missing',
 
3446
                   'bzrlib.tests.test_msgeditor',
 
3447
                   'bzrlib.tests.test_multiparent',
 
3448
                   'bzrlib.tests.test_mutabletree',
 
3449
                   'bzrlib.tests.test_nonascii',
 
3450
                   'bzrlib.tests.test_options',
 
3451
                   'bzrlib.tests.test_osutils',
 
3452
                   'bzrlib.tests.test_osutils_encodings',
 
3453
                   'bzrlib.tests.test_pack',
 
3454
                   'bzrlib.tests.test_pack_repository',
 
3455
                   'bzrlib.tests.test_patch',
 
3456
                   'bzrlib.tests.test_patches',
 
3457
                   'bzrlib.tests.test_permissions',
 
3458
                   'bzrlib.tests.test_plugins',
 
3459
                   'bzrlib.tests.test_progress',
 
3460
                   'bzrlib.tests.test_read_bundle',
 
3461
                   'bzrlib.tests.test_reconcile',
 
3462
                   'bzrlib.tests.test_reconfigure',
 
3463
                   'bzrlib.tests.test_registry',
 
3464
                   'bzrlib.tests.test_remote',
 
3465
                   'bzrlib.tests.test_rename_map',
 
3466
                   'bzrlib.tests.test_repository',
 
3467
                   'bzrlib.tests.test_revert',
 
3468
                   'bzrlib.tests.test_revision',
 
3469
                   'bzrlib.tests.test_revisionspec',
 
3470
                   'bzrlib.tests.test_revisiontree',
 
3471
                   'bzrlib.tests.test_rio',
 
3472
                   'bzrlib.tests.test_rules',
 
3473
                   'bzrlib.tests.test_sampler',
 
3474
                   'bzrlib.tests.test_selftest',
 
3475
                   'bzrlib.tests.test_serializer',
 
3476
                   'bzrlib.tests.test_setup',
 
3477
                   'bzrlib.tests.test_sftp_transport',
 
3478
                   'bzrlib.tests.test_shelf',
 
3479
                   'bzrlib.tests.test_shelf_ui',
 
3480
                   'bzrlib.tests.test_smart',
 
3481
                   'bzrlib.tests.test_smart_add',
 
3482
                   'bzrlib.tests.test_smart_request',
 
3483
                   'bzrlib.tests.test_smart_transport',
 
3484
                   'bzrlib.tests.test_smtp_connection',
 
3485
                   'bzrlib.tests.test_source',
 
3486
                   'bzrlib.tests.test_ssh_transport',
 
3487
                   'bzrlib.tests.test_status',
 
3488
                   'bzrlib.tests.test_store',
 
3489
                   'bzrlib.tests.test_strace',
 
3490
                   'bzrlib.tests.test_subsume',
 
3491
                   'bzrlib.tests.test_switch',
 
3492
                   'bzrlib.tests.test_symbol_versioning',
 
3493
                   'bzrlib.tests.test_tag',
 
3494
                   'bzrlib.tests.test_testament',
 
3495
                   'bzrlib.tests.test_textfile',
 
3496
                   'bzrlib.tests.test_textmerge',
 
3497
                   'bzrlib.tests.test_timestamp',
 
3498
                   'bzrlib.tests.test_trace',
 
3499
                   'bzrlib.tests.test_transactions',
 
3500
                   'bzrlib.tests.test_transform',
 
3501
                   'bzrlib.tests.test_transport',
 
3502
                   'bzrlib.tests.test_transport_log',
 
3503
                   'bzrlib.tests.test_tree',
 
3504
                   'bzrlib.tests.test_treebuilder',
 
3505
                   'bzrlib.tests.test_tsort',
 
3506
                   'bzrlib.tests.test_tuned_gzip',
 
3507
                   'bzrlib.tests.test_ui',
 
3508
                   'bzrlib.tests.test_uncommit',
 
3509
                   'bzrlib.tests.test_upgrade',
 
3510
                   'bzrlib.tests.test_upgrade_stacked',
 
3511
                   'bzrlib.tests.test_urlutils',
 
3512
                   'bzrlib.tests.test_version',
 
3513
                   'bzrlib.tests.test_version_info',
 
3514
                   'bzrlib.tests.test_versionedfile',
 
3515
                   'bzrlib.tests.test_weave',
 
3516
                   'bzrlib.tests.test_whitebox',
 
3517
                   'bzrlib.tests.test_win32utils',
 
3518
                   'bzrlib.tests.test_workingtree',
 
3519
                   'bzrlib.tests.test_workingtree_4',
 
3520
                   'bzrlib.tests.test_wsgi',
 
3521
                   'bzrlib.tests.test_xml',
59
3522
                   ]
60
3523
 
61
 
    # XXX: should also test bzrlib.merge_core, but they seem to be out
62
 
    # of date with the code.
63
 
 
64
 
    for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
65
 
              bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
66
 
        if m not in MODULES_TO_DOCTEST:
67
 
            MODULES_TO_DOCTEST.append(m)
68
 
 
69
 
    
70
 
    TestBase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
71
 
    print '%-30s %s' % ('bzr binary', TestBase.BZRPATH)
72
 
 
73
 
    print
74
 
 
75
 
    suite = TestSuite()
76
 
 
77
 
    suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
78
 
 
79
 
    for m in MODULES_TO_TEST:
80
 
         suite.addTest(TestLoader().loadTestsFromModule(m))
81
 
 
82
 
    for m in (MODULES_TO_DOCTEST):
83
 
        suite.addTest(DocTestSuite(m))
84
 
 
85
 
    for p in bzrlib.plugin.all_plugins:
86
 
        if hasattr(p, 'test_suite'):
87
 
            suite.addTest(p.test_suite())
88
 
 
89
 
    import bzrlib.merge_core
90
 
    suite.addTest(unittest.makeSuite(bzrlib.merge_core.MergeTest, 'test_'))
91
 
 
92
 
    return run_suite(suite, 'testbzr', verbose=verbose)
93
 
 
94
 
 
95
 
 
 
3524
    loader = TestUtil.TestLoader()
 
3525
 
 
3526
    if keep_only is not None:
 
3527
        id_filter = TestIdList(keep_only)
 
3528
    if starting_with:
 
3529
        starting_with = [test_prefix_alias_registry.resolve_alias(start)
 
3530
                         for start in starting_with]
 
3531
        # We take precedence over keep_only because *at loading time* using
 
3532
        # both options means we will load less tests for the same final result.
 
3533
        def interesting_module(name):
 
3534
            for start in starting_with:
 
3535
                if (
 
3536
                    # Either the module name starts with the specified string
 
3537
                    name.startswith(start)
 
3538
                    # or it may contain tests starting with the specified string
 
3539
                    or start.startswith(name)
 
3540
                    ):
 
3541
                    return True
 
3542
            return False
 
3543
        loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
 
3544
 
 
3545
    elif keep_only is not None:
 
3546
        loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
 
3547
        def interesting_module(name):
 
3548
            return id_filter.refers_to(name)
 
3549
 
 
3550
    else:
 
3551
        loader = TestUtil.TestLoader()
 
3552
        def interesting_module(name):
 
3553
            # No filtering, all modules are interesting
 
3554
            return True
 
3555
 
 
3556
    suite = loader.suiteClass()
 
3557
 
 
3558
    # modules building their suite with loadTestsFromModuleNames
 
3559
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
3560
 
 
3561
    modules_to_doctest = [
 
3562
        'bzrlib',
 
3563
        'bzrlib.branchbuilder',
 
3564
        'bzrlib.export',
 
3565
        'bzrlib.inventory',
 
3566
        'bzrlib.iterablefile',
 
3567
        'bzrlib.lockdir',
 
3568
        'bzrlib.merge3',
 
3569
        'bzrlib.option',
 
3570
        'bzrlib.symbol_versioning',
 
3571
        'bzrlib.tests',
 
3572
        'bzrlib.timestamp',
 
3573
        'bzrlib.version_info_formats.format_custom',
 
3574
        ]
 
3575
 
 
3576
    for mod in modules_to_doctest:
 
3577
        if not interesting_module(mod):
 
3578
            # No tests to keep here, move along
 
3579
            continue
 
3580
        try:
 
3581
            # note that this really does mean "report only" -- doctest
 
3582
            # still runs the rest of the examples
 
3583
            doc_suite = doctest.DocTestSuite(mod,
 
3584
                optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
 
3585
        except ValueError, e:
 
3586
            print '**failed to get doctest for: %s\n%s' % (mod, e)
 
3587
            raise
 
3588
        if len(doc_suite._tests) == 0:
 
3589
            raise errors.BzrError("no doctests found in %s" % (mod,))
 
3590
        suite.addTest(doc_suite)
 
3591
 
 
3592
    default_encoding = sys.getdefaultencoding()
 
3593
    for name, plugin in bzrlib.plugin.plugins().items():
 
3594
        if not interesting_module(plugin.module.__name__):
 
3595
            continue
 
3596
        plugin_suite = plugin.test_suite()
 
3597
        # We used to catch ImportError here and turn it into just a warning,
 
3598
        # but really if you don't have --no-plugins this should be a failure.
 
3599
        # mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
 
3600
        if plugin_suite is None:
 
3601
            plugin_suite = plugin.load_plugin_tests(loader)
 
3602
        if plugin_suite is not None:
 
3603
            suite.addTest(plugin_suite)
 
3604
        if default_encoding != sys.getdefaultencoding():
 
3605
            bzrlib.trace.warning(
 
3606
                'Plugin "%s" tried to reset default encoding to: %s', name,
 
3607
                sys.getdefaultencoding())
 
3608
            reload(sys)
 
3609
            sys.setdefaultencoding(default_encoding)
 
3610
 
 
3611
    if starting_with:
 
3612
        suite = filter_suite_by_id_startswith(suite, starting_with)
 
3613
 
 
3614
    if keep_only is not None:
 
3615
        # Now that the referred modules have loaded their tests, keep only the
 
3616
        # requested ones.
 
3617
        suite = filter_suite_by_id_list(suite, id_filter)
 
3618
        # Do some sanity checks on the id_list filtering
 
3619
        not_found, duplicates = suite_matches_id_list(suite, keep_only)
 
3620
        if starting_with:
 
3621
            # The tester has used both keep_only and starting_with, so he is
 
3622
            # already aware that some tests are excluded from the list, there
 
3623
            # is no need to tell him which.
 
3624
            pass
 
3625
        else:
 
3626
            # Some tests mentioned in the list are not in the test suite. The
 
3627
            # list may be out of date, report to the tester.
 
3628
            for id in not_found:
 
3629
                bzrlib.trace.warning('"%s" not found in the test suite', id)
 
3630
        for id in duplicates:
 
3631
            bzrlib.trace.warning('"%s" is used as an id by several tests', id)
 
3632
 
 
3633
    return suite
 
3634
 
 
3635
 
 
3636
def multiply_scenarios(scenarios_left, scenarios_right):
 
3637
    """Multiply two sets of scenarios.
 
3638
 
 
3639
    :returns: the cartesian product of the two sets of scenarios, that is
 
3640
        a scenario for every possible combination of a left scenario and a
 
3641
        right scenario.
 
3642
    """
 
3643
    return [
 
3644
        ('%s,%s' % (left_name, right_name),
 
3645
         dict(left_dict.items() + right_dict.items()))
 
3646
        for left_name, left_dict in scenarios_left
 
3647
        for right_name, right_dict in scenarios_right]
 
3648
 
 
3649
 
 
3650
def multiply_tests(tests, scenarios, result):
 
3651
    """Multiply tests_list by scenarios into result.
 
3652
 
 
3653
    This is the core workhorse for test parameterisation.
 
3654
 
 
3655
    Typically the load_tests() method for a per-implementation test suite will
 
3656
    call multiply_tests and return the result.
 
3657
 
 
3658
    :param tests: The tests to parameterise.
 
3659
    :param scenarios: The scenarios to apply: pairs of (scenario_name,
 
3660
        scenario_param_dict).
 
3661
    :param result: A TestSuite to add created tests to.
 
3662
 
 
3663
    This returns the passed in result TestSuite with the cross product of all
 
3664
    the tests repeated once for each scenario.  Each test is adapted by adding
 
3665
    the scenario name at the end of its id(), and updating the test object's
 
3666
    __dict__ with the scenario_param_dict.
 
3667
 
 
3668
    >>> import bzrlib.tests.test_sampler
 
3669
    >>> r = multiply_tests(
 
3670
    ...     bzrlib.tests.test_sampler.DemoTest('test_nothing'),
 
3671
    ...     [('one', dict(param=1)),
 
3672
    ...      ('two', dict(param=2))],
 
3673
    ...     TestSuite())
 
3674
    >>> tests = list(iter_suite_tests(r))
 
3675
    >>> len(tests)
 
3676
    2
 
3677
    >>> tests[0].id()
 
3678
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
 
3679
    >>> tests[0].param
 
3680
    1
 
3681
    >>> tests[1].param
 
3682
    2
 
3683
    """
 
3684
    for test in iter_suite_tests(tests):
 
3685
        apply_scenarios(test, scenarios, result)
 
3686
    return result
 
3687
 
 
3688
 
 
3689
def apply_scenarios(test, scenarios, result):
 
3690
    """Apply the scenarios in scenarios to test and add to result.
 
3691
 
 
3692
    :param test: The test to apply scenarios to.
 
3693
    :param scenarios: An iterable of scenarios to apply to test.
 
3694
    :return: result
 
3695
    :seealso: apply_scenario
 
3696
    """
 
3697
    for scenario in scenarios:
 
3698
        result.addTest(apply_scenario(test, scenario))
 
3699
    return result
 
3700
 
 
3701
 
 
3702
def apply_scenario(test, scenario):
 
3703
    """Copy test and apply scenario to it.
 
3704
 
 
3705
    :param test: A test to adapt.
 
3706
    :param scenario: A tuple describing the scenarion.
 
3707
        The first element of the tuple is the new test id.
 
3708
        The second element is a dict containing attributes to set on the
 
3709
        test.
 
3710
    :return: The adapted test.
 
3711
    """
 
3712
    new_id = "%s(%s)" % (test.id(), scenario[0])
 
3713
    new_test = clone_test(test, new_id)
 
3714
    for name, value in scenario[1].items():
 
3715
        setattr(new_test, name, value)
 
3716
    return new_test
 
3717
 
 
3718
 
 
3719
def clone_test(test, new_id):
 
3720
    """Clone a test giving it a new id.
 
3721
 
 
3722
    :param test: The test to clone.
 
3723
    :param new_id: The id to assign to it.
 
3724
    :return: The new test.
 
3725
    """
 
3726
    from copy import deepcopy
 
3727
    new_test = deepcopy(test)
 
3728
    new_test.id = lambda: new_id
 
3729
    return new_test
 
3730
 
 
3731
 
 
3732
def _rmtree_temp_dir(dirname):
 
3733
    # If LANG=C we probably have created some bogus paths
 
3734
    # which rmtree(unicode) will fail to delete
 
3735
    # so make sure we are using rmtree(str) to delete everything
 
3736
    # except on win32, where rmtree(str) will fail
 
3737
    # since it doesn't have the property of byte-stream paths
 
3738
    # (they are either ascii or mbcs)
 
3739
    if sys.platform == 'win32':
 
3740
        # make sure we are using the unicode win32 api
 
3741
        dirname = unicode(dirname)
 
3742
    else:
 
3743
        dirname = dirname.encode(sys.getfilesystemencoding())
 
3744
    try:
 
3745
        osutils.rmtree(dirname)
 
3746
    except OSError, e:
 
3747
        if sys.platform == 'win32' and e.errno == errno.EACCES:
 
3748
            sys.stderr.write('Permission denied: '
 
3749
                             'unable to remove testing dir '
 
3750
                             '%s\n%s'
 
3751
                             % (os.path.basename(dirname), e))
 
3752
        else:
 
3753
            raise
 
3754
 
 
3755
 
 
3756
class Feature(object):
 
3757
    """An operating system Feature."""
 
3758
 
 
3759
    def __init__(self):
 
3760
        self._available = None
 
3761
 
 
3762
    def available(self):
 
3763
        """Is the feature available?
 
3764
 
 
3765
        :return: True if the feature is available.
 
3766
        """
 
3767
        if self._available is None:
 
3768
            self._available = self._probe()
 
3769
        return self._available
 
3770
 
 
3771
    def _probe(self):
 
3772
        """Implement this method in concrete features.
 
3773
 
 
3774
        :return: True if the feature is available.
 
3775
        """
 
3776
        raise NotImplementedError
 
3777
 
 
3778
    def __str__(self):
 
3779
        if getattr(self, 'feature_name', None):
 
3780
            return self.feature_name()
 
3781
        return self.__class__.__name__
 
3782
 
 
3783
 
 
3784
class _SymlinkFeature(Feature):
 
3785
 
 
3786
    def _probe(self):
 
3787
        return osutils.has_symlinks()
 
3788
 
 
3789
    def feature_name(self):
 
3790
        return 'symlinks'
 
3791
 
 
3792
SymlinkFeature = _SymlinkFeature()
 
3793
 
 
3794
 
 
3795
class _HardlinkFeature(Feature):
 
3796
 
 
3797
    def _probe(self):
 
3798
        return osutils.has_hardlinks()
 
3799
 
 
3800
    def feature_name(self):
 
3801
        return 'hardlinks'
 
3802
 
 
3803
HardlinkFeature = _HardlinkFeature()
 
3804
 
 
3805
 
 
3806
class _OsFifoFeature(Feature):
 
3807
 
 
3808
    def _probe(self):
 
3809
        return getattr(os, 'mkfifo', None)
 
3810
 
 
3811
    def feature_name(self):
 
3812
        return 'filesystem fifos'
 
3813
 
 
3814
OsFifoFeature = _OsFifoFeature()
 
3815
 
 
3816
 
 
3817
class _UnicodeFilenameFeature(Feature):
 
3818
    """Does the filesystem support Unicode filenames?"""
 
3819
 
 
3820
    def _probe(self):
 
3821
        try:
 
3822
            # Check for character combinations unlikely to be covered by any
 
3823
            # single non-unicode encoding. We use the characters
 
3824
            # - greek small letter alpha (U+03B1) and
 
3825
            # - braille pattern dots-123456 (U+283F).
 
3826
            os.stat(u'\u03b1\u283f')
 
3827
        except UnicodeEncodeError:
 
3828
            return False
 
3829
        except (IOError, OSError):
 
3830
            # The filesystem allows the Unicode filename but the file doesn't
 
3831
            # exist.
 
3832
            return True
 
3833
        else:
 
3834
            # The filesystem allows the Unicode filename and the file exists,
 
3835
            # for some reason.
 
3836
            return True
 
3837
 
 
3838
UnicodeFilenameFeature = _UnicodeFilenameFeature()
 
3839
 
 
3840
 
 
3841
def probe_unicode_in_user_encoding():
 
3842
    """Try to encode several unicode strings to use in unicode-aware tests.
 
3843
    Return first successfull match.
 
3844
 
 
3845
    :return:  (unicode value, encoded plain string value) or (None, None)
 
3846
    """
 
3847
    possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
 
3848
    for uni_val in possible_vals:
 
3849
        try:
 
3850
            str_val = uni_val.encode(osutils.get_user_encoding())
 
3851
        except UnicodeEncodeError:
 
3852
            # Try a different character
 
3853
            pass
 
3854
        else:
 
3855
            return uni_val, str_val
 
3856
    return None, None
 
3857
 
 
3858
 
 
3859
def probe_bad_non_ascii(encoding):
 
3860
    """Try to find [bad] character with code [128..255]
 
3861
    that cannot be decoded to unicode in some encoding.
 
3862
    Return None if all non-ascii characters is valid
 
3863
    for given encoding.
 
3864
    """
 
3865
    for i in xrange(128, 256):
 
3866
        char = chr(i)
 
3867
        try:
 
3868
            char.decode(encoding)
 
3869
        except UnicodeDecodeError:
 
3870
            return char
 
3871
    return None
 
3872
 
 
3873
 
 
3874
class _HTTPSServerFeature(Feature):
 
3875
    """Some tests want an https Server, check if one is available.
 
3876
 
 
3877
    Right now, the only way this is available is under python2.6 which provides
 
3878
    an ssl module.
 
3879
    """
 
3880
 
 
3881
    def _probe(self):
 
3882
        try:
 
3883
            import ssl
 
3884
            return True
 
3885
        except ImportError:
 
3886
            return False
 
3887
 
 
3888
    def feature_name(self):
 
3889
        return 'HTTPSServer'
 
3890
 
 
3891
 
 
3892
HTTPSServerFeature = _HTTPSServerFeature()
 
3893
 
 
3894
 
 
3895
class _UnicodeFilename(Feature):
 
3896
    """Does the filesystem support Unicode filenames?"""
 
3897
 
 
3898
    def _probe(self):
 
3899
        try:
 
3900
            os.stat(u'\u03b1')
 
3901
        except UnicodeEncodeError:
 
3902
            return False
 
3903
        except (IOError, OSError):
 
3904
            # The filesystem allows the Unicode filename but the file doesn't
 
3905
            # exist.
 
3906
            return True
 
3907
        else:
 
3908
            # The filesystem allows the Unicode filename and the file exists,
 
3909
            # for some reason.
 
3910
            return True
 
3911
 
 
3912
UnicodeFilename = _UnicodeFilename()
 
3913
 
 
3914
 
 
3915
class _UTF8Filesystem(Feature):
 
3916
    """Is the filesystem UTF-8?"""
 
3917
 
 
3918
    def _probe(self):
 
3919
        if osutils._fs_enc.upper() in ('UTF-8', 'UTF8'):
 
3920
            return True
 
3921
        return False
 
3922
 
 
3923
UTF8Filesystem = _UTF8Filesystem()
 
3924
 
 
3925
 
 
3926
class _CaseInsCasePresFilenameFeature(Feature):
 
3927
    """Is the file-system case insensitive, but case-preserving?"""
 
3928
 
 
3929
    def _probe(self):
 
3930
        fileno, name = tempfile.mkstemp(prefix='MixedCase')
 
3931
        try:
 
3932
            # first check truly case-preserving for created files, then check
 
3933
            # case insensitive when opening existing files.
 
3934
            name = osutils.normpath(name)
 
3935
            base, rel = osutils.split(name)
 
3936
            found_rel = osutils.canonical_relpath(base, name)
 
3937
            return (found_rel == rel
 
3938
                    and os.path.isfile(name.upper())
 
3939
                    and os.path.isfile(name.lower()))
 
3940
        finally:
 
3941
            os.close(fileno)
 
3942
            os.remove(name)
 
3943
 
 
3944
    def feature_name(self):
 
3945
        return "case-insensitive case-preserving filesystem"
 
3946
 
 
3947
CaseInsCasePresFilenameFeature = _CaseInsCasePresFilenameFeature()
 
3948
 
 
3949
 
 
3950
class _CaseInsensitiveFilesystemFeature(Feature):
 
3951
    """Check if underlying filesystem is case-insensitive but *not* case
 
3952
    preserving.
 
3953
    """
 
3954
    # Note that on Windows, Cygwin, MacOS etc, the file-systems are far
 
3955
    # more likely to be case preserving, so this case is rare.
 
3956
 
 
3957
    def _probe(self):
 
3958
        if CaseInsCasePresFilenameFeature.available():
 
3959
            return False
 
3960
 
 
3961
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
 
3962
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
 
3963
            TestCaseWithMemoryTransport.TEST_ROOT = root
 
3964
        else:
 
3965
            root = TestCaseWithMemoryTransport.TEST_ROOT
 
3966
        tdir = osutils.mkdtemp(prefix='case-sensitive-probe-', suffix='',
 
3967
            dir=root)
 
3968
        name_a = osutils.pathjoin(tdir, 'a')
 
3969
        name_A = osutils.pathjoin(tdir, 'A')
 
3970
        os.mkdir(name_a)
 
3971
        result = osutils.isdir(name_A)
 
3972
        _rmtree_temp_dir(tdir)
 
3973
        return result
 
3974
 
 
3975
    def feature_name(self):
 
3976
        return 'case-insensitive filesystem'
 
3977
 
 
3978
CaseInsensitiveFilesystemFeature = _CaseInsensitiveFilesystemFeature()
 
3979
 
 
3980
 
 
3981
class _SubUnitFeature(Feature):
 
3982
    """Check if subunit is available."""
 
3983
 
 
3984
    def _probe(self):
 
3985
        try:
 
3986
            import subunit
 
3987
            return True
 
3988
        except ImportError:
 
3989
            return False
 
3990
 
 
3991
    def feature_name(self):
 
3992
        return 'subunit'
 
3993
 
 
3994
SubUnitFeature = _SubUnitFeature()
 
3995
# Only define SubUnitBzrRunner if subunit is available.
 
3996
try:
 
3997
    from subunit import TestProtocolClient
 
3998
    class SubUnitBzrRunner(TextTestRunner):
 
3999
        def run(self, test):
 
4000
            result = TestProtocolClient(self.stream)
 
4001
            test.run(result)
 
4002
            return result
 
4003
except ImportError:
 
4004
    pass