~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: Martin Pool
  • Date: 2007-11-29 07:12:42 UTC
  • mto: This revision was merged to the branch mainline in revision 3048.
  • Revision ID: mbp@sourcefrog.net-20071129071242-1tcn2a18547udlvw
Fix up calls to TestCase.build_tree passing a string rather than a list

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 os
 
37
from pprint import pformat
 
38
import random
 
39
import re
 
40
import shlex
 
41
import stat
 
42
from subprocess import Popen, PIPE
 
43
import sys
 
44
import tempfile
 
45
import unittest
 
46
import time
 
47
import warnings
 
48
 
 
49
 
 
50
from bzrlib import (
 
51
    bzrdir,
 
52
    debug,
 
53
    errors,
 
54
    memorytree,
 
55
    osutils,
 
56
    progress,
 
57
    ui,
 
58
    urlutils,
 
59
    workingtree,
 
60
    )
 
61
import bzrlib.branch
 
62
import bzrlib.commands
 
63
import bzrlib.timestamp
 
64
import bzrlib.export
 
65
import bzrlib.inventory
 
66
import bzrlib.iterablefile
 
67
import bzrlib.lockdir
 
68
try:
 
69
    import bzrlib.lsprof
 
70
except ImportError:
 
71
    # lsprof not available
 
72
    pass
 
73
from bzrlib.merge import merge_inner
 
74
import bzrlib.merge3
 
75
import bzrlib.plugin
 
76
from bzrlib.revision import common_ancestor
 
77
import bzrlib.store
 
78
from bzrlib import symbol_versioning
 
79
from bzrlib.symbol_versioning import (
 
80
    deprecated_method,
 
81
    zero_ninetyone,
 
82
    zero_ninetytwo,
 
83
    )
 
84
import bzrlib.trace
 
85
from bzrlib.transport import get_transport
 
86
import bzrlib.transport
 
87
from bzrlib.transport.local import LocalURLServer
 
88
from bzrlib.transport.memory import MemoryServer
 
89
from bzrlib.transport.readonly import ReadonlyServer
 
90
from bzrlib.trace import mutter, note
 
91
from bzrlib.tests import TestUtil
 
92
from bzrlib.tests.HttpServer import HttpServer
 
93
from bzrlib.tests.TestUtil import (
 
94
                          TestSuite,
 
95
                          TestLoader,
 
96
                          )
 
97
from bzrlib.tests.EncodingAdapter import EncodingTestAdapter
 
98
from bzrlib.tests.treeshape import build_tree_contents
 
99
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
 
100
 
 
101
# Mark this python module as being part of the implementation
 
102
# of unittest: this gives us better tracebacks where the last
 
103
# shown frame is the test code, not our assertXYZ.
 
104
__unittest = 1
 
105
 
 
106
default_transport = LocalURLServer
 
107
 
 
108
MODULES_TO_TEST = []
 
109
MODULES_TO_DOCTEST = [
 
110
        bzrlib.timestamp,
 
111
        bzrlib.errors,
 
112
        bzrlib.export,
 
113
        bzrlib.inventory,
 
114
        bzrlib.iterablefile,
 
115
        bzrlib.lockdir,
 
116
        bzrlib.merge3,
 
117
        bzrlib.option,
 
118
        bzrlib.store,
 
119
        # quoted to avoid module-loading circularity
 
120
        'bzrlib.tests',
 
121
        ]
 
122
 
 
123
 
 
124
def packages_to_test():
 
125
    """Return a list of packages to test.
 
126
 
 
127
    The packages are not globally imported so that import failures are
 
128
    triggered when running selftest, not when importing the command.
 
129
    """
 
130
    import bzrlib.doc
 
131
    import bzrlib.tests.blackbox
 
132
    import bzrlib.tests.branch_implementations
 
133
    import bzrlib.tests.bzrdir_implementations
 
134
    import bzrlib.tests.commands
 
135
    import bzrlib.tests.interrepository_implementations
 
136
    import bzrlib.tests.interversionedfile_implementations
 
137
    import bzrlib.tests.intertree_implementations
 
138
    import bzrlib.tests.inventory_implementations
 
139
    import bzrlib.tests.per_lock
 
140
    import bzrlib.tests.repository_implementations
 
141
    import bzrlib.tests.revisionstore_implementations
 
142
    import bzrlib.tests.tree_implementations
 
143
    import bzrlib.tests.workingtree_implementations
 
144
    return [
 
145
            bzrlib.doc,
 
146
            bzrlib.tests.blackbox,
 
147
            bzrlib.tests.branch_implementations,
 
148
            bzrlib.tests.bzrdir_implementations,
 
149
            bzrlib.tests.commands,
 
150
            bzrlib.tests.interrepository_implementations,
 
151
            bzrlib.tests.interversionedfile_implementations,
 
152
            bzrlib.tests.intertree_implementations,
 
153
            bzrlib.tests.inventory_implementations,
 
154
            bzrlib.tests.per_lock,
 
155
            bzrlib.tests.repository_implementations,
 
156
            bzrlib.tests.revisionstore_implementations,
 
157
            bzrlib.tests.tree_implementations,
 
158
            bzrlib.tests.workingtree_implementations,
 
159
            ]
 
160
 
 
161
 
 
162
class ExtendedTestResult(unittest._TextTestResult):
 
163
    """Accepts, reports and accumulates the results of running tests.
 
164
 
 
165
    Compared to the unittest version this class adds support for
 
166
    profiling, benchmarking, stopping as soon as a test fails,  and
 
167
    skipping tests.  There are further-specialized subclasses for
 
168
    different types of display.
 
169
 
 
170
    When a test finishes, in whatever way, it calls one of the addSuccess,
 
171
    addFailure or addError classes.  These in turn may redirect to a more
 
172
    specific case for the special test results supported by our extended
 
173
    tests.
 
174
 
 
175
    Note that just one of these objects is fed the results from many tests.
 
176
    """
 
177
 
 
178
    stop_early = False
 
179
    
 
180
    def __init__(self, stream, descriptions, verbosity,
 
181
                 bench_history=None,
 
182
                 num_tests=None,
 
183
                 ):
 
184
        """Construct new TestResult.
 
185
 
 
186
        :param bench_history: Optionally, a writable file object to accumulate
 
187
            benchmark results.
 
188
        """
 
189
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
190
        if bench_history is not None:
 
191
            from bzrlib.version import _get_bzr_source_tree
 
192
            src_tree = _get_bzr_source_tree()
 
193
            if src_tree:
 
194
                try:
 
195
                    revision_id = src_tree.get_parent_ids()[0]
 
196
                except IndexError:
 
197
                    # XXX: if this is a brand new tree, do the same as if there
 
198
                    # is no branch.
 
199
                    revision_id = ''
 
200
            else:
 
201
                # XXX: If there's no branch, what should we do?
 
202
                revision_id = ''
 
203
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
 
204
        self._bench_history = bench_history
 
205
        self.ui = ui.ui_factory
 
206
        self.num_tests = num_tests
 
207
        self.error_count = 0
 
208
        self.failure_count = 0
 
209
        self.known_failure_count = 0
 
210
        self.skip_count = 0
 
211
        self.not_applicable_count = 0
 
212
        self.unsupported = {}
 
213
        self.count = 0
 
214
        self._overall_start_time = time.time()
 
215
    
 
216
    def _extractBenchmarkTime(self, testCase):
 
217
        """Add a benchmark time for the current test case."""
 
218
        return getattr(testCase, "_benchtime", None)
 
219
    
 
220
    def _elapsedTestTimeString(self):
 
221
        """Return a time string for the overall time the current test has taken."""
 
222
        return self._formatTime(time.time() - self._start_time)
 
223
 
 
224
    def _testTimeString(self, testCase):
 
225
        benchmark_time = self._extractBenchmarkTime(testCase)
 
226
        if benchmark_time is not None:
 
227
            return "%s/%s" % (
 
228
                self._formatTime(benchmark_time),
 
229
                self._elapsedTestTimeString())
 
230
        else:
 
231
            return "           %s" % self._elapsedTestTimeString()
 
232
 
 
233
    def _formatTime(self, seconds):
 
234
        """Format seconds as milliseconds with leading spaces."""
 
235
        # some benchmarks can take thousands of seconds to run, so we need 8
 
236
        # places
 
237
        return "%8dms" % (1000 * seconds)
 
238
 
 
239
    def _shortened_test_description(self, test):
 
240
        what = test.id()
 
241
        what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
 
242
        return what
 
243
 
 
244
    def startTest(self, test):
 
245
        unittest.TestResult.startTest(self, test)
 
246
        self.report_test_start(test)
 
247
        test.number = self.count
 
248
        self._recordTestStartTime()
 
249
 
 
250
    def _recordTestStartTime(self):
 
251
        """Record that a test has started."""
 
252
        self._start_time = time.time()
 
253
 
 
254
    def _cleanupLogFile(self, test):
 
255
        # We can only do this if we have one of our TestCases, not if
 
256
        # we have a doctest.
 
257
        setKeepLogfile = getattr(test, 'setKeepLogfile', None)
 
258
        if setKeepLogfile is not None:
 
259
            setKeepLogfile()
 
260
 
 
261
    def addError(self, test, err):
 
262
        """Tell result that test finished with an error.
 
263
 
 
264
        Called from the TestCase run() method when the test
 
265
        fails with an unexpected error.
 
266
        """
 
267
        self._testConcluded(test)
 
268
        if isinstance(err[1], TestSkipped):
 
269
            return self._addSkipped(test, err)
 
270
        elif isinstance(err[1], UnavailableFeature):
 
271
            return self.addNotSupported(test, err[1].args[0])
 
272
        else:
 
273
            unittest.TestResult.addError(self, test, err)
 
274
            self.error_count += 1
 
275
            self.report_error(test, err)
 
276
            if self.stop_early:
 
277
                self.stop()
 
278
 
 
279
    def addFailure(self, test, err):
 
280
        """Tell result that test failed.
 
281
 
 
282
        Called from the TestCase run() method when the test
 
283
        fails because e.g. an assert() method failed.
 
284
        """
 
285
        self._testConcluded(test)
 
286
        if isinstance(err[1], KnownFailure):
 
287
            return self._addKnownFailure(test, err)
 
288
        else:
 
289
            unittest.TestResult.addFailure(self, test, err)
 
290
            self.failure_count += 1
 
291
            self.report_failure(test, err)
 
292
            if self.stop_early:
 
293
                self.stop()
 
294
 
 
295
    def addSuccess(self, test):
 
296
        """Tell result that test completed successfully.
 
297
 
 
298
        Called from the TestCase run()
 
299
        """
 
300
        self._testConcluded(test)
 
301
        if self._bench_history is not None:
 
302
            benchmark_time = self._extractBenchmarkTime(test)
 
303
            if benchmark_time is not None:
 
304
                self._bench_history.write("%s %s\n" % (
 
305
                    self._formatTime(benchmark_time),
 
306
                    test.id()))
 
307
        self.report_success(test)
 
308
        unittest.TestResult.addSuccess(self, test)
 
309
 
 
310
    def _testConcluded(self, test):
 
311
        """Common code when a test has finished.
 
312
 
 
313
        Called regardless of whether it succeded, failed, etc.
 
314
        """
 
315
        self._cleanupLogFile(test)
 
316
 
 
317
    def _addKnownFailure(self, test, err):
 
318
        self.known_failure_count += 1
 
319
        self.report_known_failure(test, err)
 
320
 
 
321
    def addNotSupported(self, test, feature):
 
322
        """The test will not be run because of a missing feature.
 
323
        """
 
324
        # this can be called in two different ways: it may be that the
 
325
        # test started running, and then raised (through addError) 
 
326
        # UnavailableFeature.  Alternatively this method can be called
 
327
        # while probing for features before running the tests; in that
 
328
        # case we will see startTest and stopTest, but the test will never
 
329
        # actually run.
 
330
        self.unsupported.setdefault(str(feature), 0)
 
331
        self.unsupported[str(feature)] += 1
 
332
        self.report_unsupported(test, feature)
 
333
 
 
334
    def _addSkipped(self, test, skip_excinfo):
 
335
        if isinstance(skip_excinfo[1], TestNotApplicable):
 
336
            self.not_applicable_count += 1
 
337
            self.report_not_applicable(test, skip_excinfo)
 
338
        else:
 
339
            self.skip_count += 1
 
340
            self.report_skip(test, skip_excinfo)
 
341
        try:
 
342
            test.tearDown()
 
343
        except KeyboardInterrupt:
 
344
            raise
 
345
        except:
 
346
            self.addError(test, test._exc_info())
 
347
        else:
 
348
            # seems best to treat this as success from point-of-view of unittest
 
349
            # -- it actually does nothing so it barely matters :)
 
350
            unittest.TestResult.addSuccess(self, test)
 
351
 
 
352
    def printErrorList(self, flavour, errors):
 
353
        for test, err in errors:
 
354
            self.stream.writeln(self.separator1)
 
355
            self.stream.write("%s: " % flavour)
 
356
            self.stream.writeln(self.getDescription(test))
 
357
            if getattr(test, '_get_log', None) is not None:
 
358
                self.stream.write('\n')
 
359
                self.stream.write(
 
360
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-'))
 
361
                self.stream.write('\n')
 
362
                self.stream.write(test._get_log())
 
363
                self.stream.write('\n')
 
364
                self.stream.write(
 
365
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-'))
 
366
                self.stream.write('\n')
 
367
            self.stream.writeln(self.separator2)
 
368
            self.stream.writeln("%s" % err)
 
369
 
 
370
    def finished(self):
 
371
        pass
 
372
 
 
373
    def report_cleaning_up(self):
 
374
        pass
 
375
 
 
376
    def report_success(self, test):
 
377
        pass
 
378
 
 
379
    def wasStrictlySuccessful(self):
 
380
        if self.unsupported or self.known_failure_count:
 
381
            return False
 
382
        return self.wasSuccessful()
 
383
 
 
384
 
 
385
class TextTestResult(ExtendedTestResult):
 
386
    """Displays progress and results of tests in text form"""
 
387
 
 
388
    def __init__(self, stream, descriptions, verbosity,
 
389
                 bench_history=None,
 
390
                 num_tests=None,
 
391
                 pb=None,
 
392
                 ):
 
393
        ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
 
394
            bench_history, num_tests)
 
395
        if pb is None:
 
396
            self.pb = self.ui.nested_progress_bar()
 
397
            self._supplied_pb = False
 
398
        else:
 
399
            self.pb = pb
 
400
            self._supplied_pb = True
 
401
        self.pb.show_pct = False
 
402
        self.pb.show_spinner = False
 
403
        self.pb.show_eta = False,
 
404
        self.pb.show_count = False
 
405
        self.pb.show_bar = False
 
406
 
 
407
    def report_starting(self):
 
408
        self.pb.update('[test 0/%d] starting...' % (self.num_tests))
 
409
 
 
410
    def _progress_prefix_text(self):
 
411
        a = '[%d' % self.count
 
412
        if self.num_tests is not None:
 
413
            a +='/%d' % self.num_tests
 
414
        a += ' in %ds' % (time.time() - self._overall_start_time)
 
415
        if self.error_count:
 
416
            a += ', %d errors' % self.error_count
 
417
        if self.failure_count:
 
418
            a += ', %d failed' % self.failure_count
 
419
        if self.known_failure_count:
 
420
            a += ', %d known failures' % self.known_failure_count
 
421
        if self.skip_count:
 
422
            a += ', %d skipped' % self.skip_count
 
423
        if self.unsupported:
 
424
            a += ', %d missing features' % len(self.unsupported)
 
425
        a += ']'
 
426
        return a
 
427
 
 
428
    def report_test_start(self, test):
 
429
        self.count += 1
 
430
        self.pb.update(
 
431
                self._progress_prefix_text()
 
432
                + ' ' 
 
433
                + self._shortened_test_description(test))
 
434
 
 
435
    def _test_description(self, test):
 
436
        return self._shortened_test_description(test)
 
437
 
 
438
    def report_error(self, test, err):
 
439
        self.pb.note('ERROR: %s\n    %s\n', 
 
440
            self._test_description(test),
 
441
            err[1],
 
442
            )
 
443
 
 
444
    def report_failure(self, test, err):
 
445
        self.pb.note('FAIL: %s\n    %s\n', 
 
446
            self._test_description(test),
 
447
            err[1],
 
448
            )
 
449
 
 
450
    def report_known_failure(self, test, err):
 
451
        self.pb.note('XFAIL: %s\n%s\n',
 
452
            self._test_description(test), err[1])
 
453
 
 
454
    def report_skip(self, test, skip_excinfo):
 
455
        pass
 
456
 
 
457
    def report_not_applicable(self, test, skip_excinfo):
 
458
        pass
 
459
 
 
460
    def report_unsupported(self, test, feature):
 
461
        """test cannot be run because feature is missing."""
 
462
                  
 
463
    def report_cleaning_up(self):
 
464
        self.pb.update('cleaning up...')
 
465
 
 
466
    def finished(self):
 
467
        if not self._supplied_pb:
 
468
            self.pb.finished()
 
469
 
 
470
 
 
471
class VerboseTestResult(ExtendedTestResult):
 
472
    """Produce long output, with one line per test run plus times"""
 
473
 
 
474
    def _ellipsize_to_right(self, a_string, final_width):
 
475
        """Truncate and pad a string, keeping the right hand side"""
 
476
        if len(a_string) > final_width:
 
477
            result = '...' + a_string[3-final_width:]
 
478
        else:
 
479
            result = a_string
 
480
        return result.ljust(final_width)
 
481
 
 
482
    def report_starting(self):
 
483
        self.stream.write('running %d tests...\n' % self.num_tests)
 
484
 
 
485
    def report_test_start(self, test):
 
486
        self.count += 1
 
487
        name = self._shortened_test_description(test)
 
488
        # width needs space for 6 char status, plus 1 for slash, plus 2 10-char
 
489
        # numbers, plus a trailing blank
 
490
        # when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
 
491
        self.stream.write(self._ellipsize_to_right(name,
 
492
                          osutils.terminal_width()-30))
 
493
        self.stream.flush()
 
494
 
 
495
    def _error_summary(self, err):
 
496
        indent = ' ' * 4
 
497
        return '%s%s' % (indent, err[1])
 
498
 
 
499
    def report_error(self, test, err):
 
500
        self.stream.writeln('ERROR %s\n%s'
 
501
                % (self._testTimeString(test),
 
502
                   self._error_summary(err)))
 
503
 
 
504
    def report_failure(self, test, err):
 
505
        self.stream.writeln(' FAIL %s\n%s'
 
506
                % (self._testTimeString(test),
 
507
                   self._error_summary(err)))
 
508
 
 
509
    def report_known_failure(self, test, err):
 
510
        self.stream.writeln('XFAIL %s\n%s'
 
511
                % (self._testTimeString(test),
 
512
                   self._error_summary(err)))
 
513
 
 
514
    def report_success(self, test):
 
515
        self.stream.writeln('   OK %s' % self._testTimeString(test))
 
516
        for bench_called, stats in getattr(test, '_benchcalls', []):
 
517
            self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
518
            stats.pprint(file=self.stream)
 
519
        # flush the stream so that we get smooth output. This verbose mode is
 
520
        # used to show the output in PQM.
 
521
        self.stream.flush()
 
522
 
 
523
    def report_skip(self, test, skip_excinfo):
 
524
        self.stream.writeln(' SKIP %s\n%s'
 
525
                % (self._testTimeString(test),
 
526
                   self._error_summary(skip_excinfo)))
 
527
 
 
528
    def report_not_applicable(self, test, skip_excinfo):
 
529
        self.stream.writeln('  N/A %s\n%s'
 
530
                % (self._testTimeString(test),
 
531
                   self._error_summary(skip_excinfo)))
 
532
 
 
533
    def report_unsupported(self, test, feature):
 
534
        """test cannot be run because feature is missing."""
 
535
        self.stream.writeln("NODEP %s\n    The feature '%s' is not available."
 
536
                %(self._testTimeString(test), feature))
 
537
 
 
538
 
 
539
class TextTestRunner(object):
 
540
    stop_on_failure = False
 
541
 
 
542
    def __init__(self,
 
543
                 stream=sys.stderr,
 
544
                 descriptions=0,
 
545
                 verbosity=1,
 
546
                 bench_history=None,
 
547
                 list_only=False
 
548
                 ):
 
549
        self.stream = unittest._WritelnDecorator(stream)
 
550
        self.descriptions = descriptions
 
551
        self.verbosity = verbosity
 
552
        self._bench_history = bench_history
 
553
        self.list_only = list_only
 
554
 
 
555
    def run(self, test):
 
556
        "Run the given test case or test suite."
 
557
        startTime = time.time()
 
558
        if self.verbosity == 1:
 
559
            result_class = TextTestResult
 
560
        elif self.verbosity >= 2:
 
561
            result_class = VerboseTestResult
 
562
        result = result_class(self.stream,
 
563
                              self.descriptions,
 
564
                              self.verbosity,
 
565
                              bench_history=self._bench_history,
 
566
                              num_tests=test.countTestCases(),
 
567
                              )
 
568
        result.stop_early = self.stop_on_failure
 
569
        result.report_starting()
 
570
        if self.list_only:
 
571
            if self.verbosity >= 2:
 
572
                self.stream.writeln("Listing tests only ...\n")
 
573
            run = 0
 
574
            for t in iter_suite_tests(test):
 
575
                self.stream.writeln("%s" % (t.id()))
 
576
                run += 1
 
577
            actionTaken = "Listed"
 
578
        else: 
 
579
            test.run(result)
 
580
            run = result.testsRun
 
581
            actionTaken = "Ran"
 
582
        stopTime = time.time()
 
583
        timeTaken = stopTime - startTime
 
584
        result.printErrors()
 
585
        self.stream.writeln(result.separator2)
 
586
        self.stream.writeln("%s %d test%s in %.3fs" % (actionTaken,
 
587
                            run, run != 1 and "s" or "", timeTaken))
 
588
        self.stream.writeln()
 
589
        if not result.wasSuccessful():
 
590
            self.stream.write("FAILED (")
 
591
            failed, errored = map(len, (result.failures, result.errors))
 
592
            if failed:
 
593
                self.stream.write("failures=%d" % failed)
 
594
            if errored:
 
595
                if failed: self.stream.write(", ")
 
596
                self.stream.write("errors=%d" % errored)
 
597
            if result.known_failure_count:
 
598
                if failed or errored: self.stream.write(", ")
 
599
                self.stream.write("known_failure_count=%d" %
 
600
                    result.known_failure_count)
 
601
            self.stream.writeln(")")
 
602
        else:
 
603
            if result.known_failure_count:
 
604
                self.stream.writeln("OK (known_failures=%d)" %
 
605
                    result.known_failure_count)
 
606
            else:
 
607
                self.stream.writeln("OK")
 
608
        if result.skip_count > 0:
 
609
            skipped = result.skip_count
 
610
            self.stream.writeln('%d test%s skipped' %
 
611
                                (skipped, skipped != 1 and "s" or ""))
 
612
        if result.unsupported:
 
613
            for feature, count in sorted(result.unsupported.items()):
 
614
                self.stream.writeln("Missing feature '%s' skipped %d tests." %
 
615
                    (feature, count))
 
616
        result.finished()
 
617
        return result
 
618
 
 
619
 
 
620
def iter_suite_tests(suite):
 
621
    """Return all tests in a suite, recursing through nested suites"""
 
622
    for item in suite._tests:
 
623
        if isinstance(item, unittest.TestCase):
 
624
            yield item
 
625
        elif isinstance(item, unittest.TestSuite):
 
626
            for r in iter_suite_tests(item):
 
627
                yield r
 
628
        else:
 
629
            raise Exception('unknown object %r inside test suite %r'
 
630
                            % (item, suite))
 
631
 
 
632
 
 
633
class TestSkipped(Exception):
 
634
    """Indicates that a test was intentionally skipped, rather than failing."""
 
635
 
 
636
 
 
637
class TestNotApplicable(TestSkipped):
 
638
    """A test is not applicable to the situation where it was run.
 
639
 
 
640
    This is only normally raised by parameterized tests, if they find that 
 
641
    the instance they're constructed upon does not support one aspect 
 
642
    of its interface.
 
643
    """
 
644
 
 
645
 
 
646
class KnownFailure(AssertionError):
 
647
    """Indicates that a test failed in a precisely expected manner.
 
648
 
 
649
    Such failures dont block the whole test suite from passing because they are
 
650
    indicators of partially completed code or of future work. We have an
 
651
    explicit error for them so that we can ensure that they are always visible:
 
652
    KnownFailures are always shown in the output of bzr selftest.
 
653
    """
 
654
 
 
655
 
 
656
class UnavailableFeature(Exception):
 
657
    """A feature required for this test was not available.
 
658
 
 
659
    The feature should be used to construct the exception.
 
660
    """
 
661
 
 
662
 
 
663
class CommandFailed(Exception):
 
664
    pass
 
665
 
 
666
 
 
667
class StringIOWrapper(object):
 
668
    """A wrapper around cStringIO which just adds an encoding attribute.
 
669
    
 
670
    Internally we can check sys.stdout to see what the output encoding
 
671
    should be. However, cStringIO has no encoding attribute that we can
 
672
    set. So we wrap it instead.
 
673
    """
 
674
    encoding='ascii'
 
675
    _cstring = None
 
676
 
 
677
    def __init__(self, s=None):
 
678
        if s is not None:
 
679
            self.__dict__['_cstring'] = StringIO(s)
 
680
        else:
 
681
            self.__dict__['_cstring'] = StringIO()
 
682
 
 
683
    def __getattr__(self, name, getattr=getattr):
 
684
        return getattr(self.__dict__['_cstring'], name)
 
685
 
 
686
    def __setattr__(self, name, val):
 
687
        if name == 'encoding':
 
688
            self.__dict__['encoding'] = val
 
689
        else:
 
690
            return setattr(self._cstring, name, val)
 
691
 
 
692
 
 
693
class TestUIFactory(ui.CLIUIFactory):
 
694
    """A UI Factory for testing.
 
695
 
 
696
    Hide the progress bar but emit note()s.
 
697
    Redirect stdin.
 
698
    Allows get_password to be tested without real tty attached.
 
699
    """
 
700
 
 
701
    def __init__(self,
 
702
                 stdout=None,
 
703
                 stderr=None,
 
704
                 stdin=None):
 
705
        super(TestUIFactory, self).__init__()
 
706
        if stdin is not None:
 
707
            # We use a StringIOWrapper to be able to test various
 
708
            # encodings, but the user is still responsible to
 
709
            # encode the string and to set the encoding attribute
 
710
            # of StringIOWrapper.
 
711
            self.stdin = StringIOWrapper(stdin)
 
712
        if stdout is None:
 
713
            self.stdout = sys.stdout
 
714
        else:
 
715
            self.stdout = stdout
 
716
        if stderr is None:
 
717
            self.stderr = sys.stderr
 
718
        else:
 
719
            self.stderr = stderr
 
720
 
 
721
    def clear(self):
 
722
        """See progress.ProgressBar.clear()."""
 
723
 
 
724
    def clear_term(self):
 
725
        """See progress.ProgressBar.clear_term()."""
 
726
 
 
727
    def clear_term(self):
 
728
        """See progress.ProgressBar.clear_term()."""
 
729
 
 
730
    def finished(self):
 
731
        """See progress.ProgressBar.finished()."""
 
732
 
 
733
    def note(self, fmt_string, *args, **kwargs):
 
734
        """See progress.ProgressBar.note()."""
 
735
        self.stdout.write((fmt_string + "\n") % args)
 
736
 
 
737
    def progress_bar(self):
 
738
        return self
 
739
 
 
740
    def nested_progress_bar(self):
 
741
        return self
 
742
 
 
743
    def update(self, message, count=None, total=None):
 
744
        """See progress.ProgressBar.update()."""
 
745
 
 
746
    def get_non_echoed_password(self, prompt):
 
747
        """Get password from stdin without trying to handle the echo mode"""
 
748
        if prompt:
 
749
            self.stdout.write(prompt.encode(self.stdout.encoding, 'replace'))
 
750
        password = self.stdin.readline()
 
751
        if not password:
 
752
            raise EOFError
 
753
        if password[-1] == '\n':
 
754
            password = password[:-1]
 
755
        return password
 
756
 
 
757
 
 
758
class TestCase(unittest.TestCase):
 
759
    """Base class for bzr unit tests.
 
760
    
 
761
    Tests that need access to disk resources should subclass 
 
762
    TestCaseInTempDir not TestCase.
 
763
 
 
764
    Error and debug log messages are redirected from their usual
 
765
    location into a temporary file, the contents of which can be
 
766
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
 
767
    so that it can also capture file IO.  When the test completes this file
 
768
    is read into memory and removed from disk.
 
769
       
 
770
    There are also convenience functions to invoke bzr's command-line
 
771
    routine, and to build and check bzr trees.
 
772
   
 
773
    In addition to the usual method of overriding tearDown(), this class also
 
774
    allows subclasses to register functions into the _cleanups list, which is
 
775
    run in order as the object is torn down.  It's less likely this will be
 
776
    accidentally overlooked.
 
777
    """
 
778
 
 
779
    _log_file_name = None
 
780
    _log_contents = ''
 
781
    _keep_log_file = False
 
782
    # record lsprof data when performing benchmark calls.
 
783
    _gather_lsprof_in_benchmarks = False
 
784
 
 
785
    def __init__(self, methodName='testMethod'):
 
786
        super(TestCase, self).__init__(methodName)
 
787
        self._cleanups = []
 
788
 
 
789
    def setUp(self):
 
790
        unittest.TestCase.setUp(self)
 
791
        self._cleanEnvironment()
 
792
        bzrlib.trace.disable_default_logging()
 
793
        self._silenceUI()
 
794
        self._startLogFile()
 
795
        self._benchcalls = []
 
796
        self._benchtime = None
 
797
        self._clear_hooks()
 
798
        self._clear_debug_flags()
 
799
 
 
800
    def _clear_debug_flags(self):
 
801
        """Prevent externally set debug flags affecting tests.
 
802
        
 
803
        Tests that want to use debug flags can just set them in the
 
804
        debug_flags set during setup/teardown.
 
805
        """
 
806
        self._preserved_debug_flags = set(debug.debug_flags)
 
807
        debug.debug_flags.clear()
 
808
        self.addCleanup(self._restore_debug_flags)
 
809
 
 
810
    def _clear_hooks(self):
 
811
        # prevent hooks affecting tests
 
812
        import bzrlib.branch
 
813
        import bzrlib.smart.server
 
814
        self._preserved_hooks = {
 
815
            bzrlib.branch.Branch: bzrlib.branch.Branch.hooks,
 
816
            bzrlib.smart.server.SmartTCPServer: bzrlib.smart.server.SmartTCPServer.hooks,
 
817
            }
 
818
        self.addCleanup(self._restoreHooks)
 
819
        # reset all hooks to an empty instance of the appropriate type
 
820
        bzrlib.branch.Branch.hooks = bzrlib.branch.BranchHooks()
 
821
        bzrlib.smart.server.SmartTCPServer.hooks = bzrlib.smart.server.SmartServerHooks()
 
822
 
 
823
    def _silenceUI(self):
 
824
        """Turn off UI for duration of test"""
 
825
        # by default the UI is off; tests can turn it on if they want it.
 
826
        saved = ui.ui_factory
 
827
        def _restore():
 
828
            ui.ui_factory = saved
 
829
        ui.ui_factory = ui.SilentUIFactory()
 
830
        self.addCleanup(_restore)
 
831
 
 
832
    def _ndiff_strings(self, a, b):
 
833
        """Return ndiff between two strings containing lines.
 
834
        
 
835
        A trailing newline is added if missing to make the strings
 
836
        print properly."""
 
837
        if b and b[-1] != '\n':
 
838
            b += '\n'
 
839
        if a and a[-1] != '\n':
 
840
            a += '\n'
 
841
        difflines = difflib.ndiff(a.splitlines(True),
 
842
                                  b.splitlines(True),
 
843
                                  linejunk=lambda x: False,
 
844
                                  charjunk=lambda x: False)
 
845
        return ''.join(difflines)
 
846
 
 
847
    def assertEqual(self, a, b, message=''):
 
848
        try:
 
849
            if a == b:
 
850
                return
 
851
        except UnicodeError, e:
 
852
            # If we can't compare without getting a UnicodeError, then
 
853
            # obviously they are different
 
854
            mutter('UnicodeError: %s', e)
 
855
        if message:
 
856
            message += '\n'
 
857
        raise AssertionError("%snot equal:\na = %s\nb = %s\n"
 
858
            % (message,
 
859
               pformat(a), pformat(b)))
 
860
 
 
861
    assertEquals = assertEqual
 
862
 
 
863
    def assertEqualDiff(self, a, b, message=None):
 
864
        """Assert two texts are equal, if not raise an exception.
 
865
        
 
866
        This is intended for use with multi-line strings where it can 
 
867
        be hard to find the differences by eye.
 
868
        """
 
869
        # TODO: perhaps override assertEquals to call this for strings?
 
870
        if a == b:
 
871
            return
 
872
        if message is None:
 
873
            message = "texts not equal:\n"
 
874
        raise AssertionError(message +
 
875
                             self._ndiff_strings(a, b))
 
876
        
 
877
    def assertEqualMode(self, mode, mode_test):
 
878
        self.assertEqual(mode, mode_test,
 
879
                         'mode mismatch %o != %o' % (mode, mode_test))
 
880
 
 
881
    def assertPositive(self, val):
 
882
        """Assert that val is greater than 0."""
 
883
        self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
 
884
 
 
885
    def assertNegative(self, val):
 
886
        """Assert that val is less than 0."""
 
887
        self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
 
888
 
 
889
    def assertStartsWith(self, s, prefix):
 
890
        if not s.startswith(prefix):
 
891
            raise AssertionError('string %r does not start with %r' % (s, prefix))
 
892
 
 
893
    def assertEndsWith(self, s, suffix):
 
894
        """Asserts that s ends with suffix."""
 
895
        if not s.endswith(suffix):
 
896
            raise AssertionError('string %r does not end with %r' % (s, suffix))
 
897
 
 
898
    def assertContainsRe(self, haystack, needle_re):
 
899
        """Assert that a contains something matching a regular expression."""
 
900
        if not re.search(needle_re, haystack):
 
901
            if '\n' in haystack or len(haystack) > 60:
 
902
                # a long string, format it in a more readable way
 
903
                raise AssertionError(
 
904
                        'pattern "%s" not found in\n"""\\\n%s"""\n'
 
905
                        % (needle_re, haystack))
 
906
            else:
 
907
                raise AssertionError('pattern "%s" not found in "%s"'
 
908
                        % (needle_re, haystack))
 
909
 
 
910
    def assertNotContainsRe(self, haystack, needle_re):
 
911
        """Assert that a does not match a regular expression"""
 
912
        if re.search(needle_re, haystack):
 
913
            raise AssertionError('pattern "%s" found in "%s"'
 
914
                    % (needle_re, haystack))
 
915
 
 
916
    def assertSubset(self, sublist, superlist):
 
917
        """Assert that every entry in sublist is present in superlist."""
 
918
        missing = set(sublist) - set(superlist)
 
919
        if len(missing) > 0:
 
920
            raise AssertionError("value(s) %r not present in container %r" %
 
921
                                 (missing, superlist))
 
922
 
 
923
    def assertListRaises(self, excClass, func, *args, **kwargs):
 
924
        """Fail unless excClass is raised when the iterator from func is used.
 
925
        
 
926
        Many functions can return generators this makes sure
 
927
        to wrap them in a list() call to make sure the whole generator
 
928
        is run, and that the proper exception is raised.
 
929
        """
 
930
        try:
 
931
            list(func(*args, **kwargs))
 
932
        except excClass:
 
933
            return
 
934
        else:
 
935
            if getattr(excClass,'__name__', None) is not None:
 
936
                excName = excClass.__name__
 
937
            else:
 
938
                excName = str(excClass)
 
939
            raise self.failureException, "%s not raised" % excName
 
940
 
 
941
    def assertRaises(self, excClass, callableObj, *args, **kwargs):
 
942
        """Assert that a callable raises a particular exception.
 
943
 
 
944
        :param excClass: As for the except statement, this may be either an
 
945
            exception class, or a tuple of classes.
 
946
        :param callableObj: A callable, will be passed ``*args`` and
 
947
            ``**kwargs``.
 
948
 
 
949
        Returns the exception so that you can examine it.
 
950
        """
 
951
        try:
 
952
            callableObj(*args, **kwargs)
 
953
        except excClass, e:
 
954
            return e
 
955
        else:
 
956
            if getattr(excClass,'__name__', None) is not None:
 
957
                excName = excClass.__name__
 
958
            else:
 
959
                # probably a tuple
 
960
                excName = str(excClass)
 
961
            raise self.failureException, "%s not raised" % excName
 
962
 
 
963
    def assertIs(self, left, right, message=None):
 
964
        if not (left is right):
 
965
            if message is not None:
 
966
                raise AssertionError(message)
 
967
            else:
 
968
                raise AssertionError("%r is not %r." % (left, right))
 
969
 
 
970
    def assertIsNot(self, left, right, message=None):
 
971
        if (left is right):
 
972
            if message is not None:
 
973
                raise AssertionError(message)
 
974
            else:
 
975
                raise AssertionError("%r is %r." % (left, right))
 
976
 
 
977
    def assertTransportMode(self, transport, path, mode):
 
978
        """Fail if a path does not have mode mode.
 
979
        
 
980
        If modes are not supported on this transport, the assertion is ignored.
 
981
        """
 
982
        if not transport._can_roundtrip_unix_modebits():
 
983
            return
 
984
        path_stat = transport.stat(path)
 
985
        actual_mode = stat.S_IMODE(path_stat.st_mode)
 
986
        self.assertEqual(mode, actual_mode,
 
987
            'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
 
988
 
 
989
    def assertIsSameRealPath(self, path1, path2):
 
990
        """Fail if path1 and path2 points to different files"""
 
991
        self.assertEqual(osutils.realpath(path1),
 
992
                         osutils.realpath(path2),
 
993
                         "apparent paths:\na = %s\nb = %s\n," % (path1, path2))
 
994
 
 
995
    def assertIsInstance(self, obj, kls):
 
996
        """Fail if obj is not an instance of kls"""
 
997
        if not isinstance(obj, kls):
 
998
            self.fail("%r is an instance of %s rather than %s" % (
 
999
                obj, obj.__class__, kls))
 
1000
 
 
1001
    def expectFailure(self, reason, assertion, *args, **kwargs):
 
1002
        """Invoke a test, expecting it to fail for the given reason.
 
1003
 
 
1004
        This is for assertions that ought to succeed, but currently fail.
 
1005
        (The failure is *expected* but not *wanted*.)  Please be very precise
 
1006
        about the failure you're expecting.  If a new bug is introduced,
 
1007
        AssertionError should be raised, not KnownFailure.
 
1008
 
 
1009
        Frequently, expectFailure should be followed by an opposite assertion.
 
1010
        See example below.
 
1011
 
 
1012
        Intended to be used with a callable that raises AssertionError as the
 
1013
        'assertion' parameter.  args and kwargs are passed to the 'assertion'.
 
1014
 
 
1015
        Raises KnownFailure if the test fails.  Raises AssertionError if the
 
1016
        test succeeds.
 
1017
 
 
1018
        example usage::
 
1019
 
 
1020
          self.expectFailure('Math is broken', self.assertNotEqual, 54,
 
1021
                             dynamic_val)
 
1022
          self.assertEqual(42, dynamic_val)
 
1023
 
 
1024
          This means that a dynamic_val of 54 will cause the test to raise
 
1025
          a KnownFailure.  Once math is fixed and the expectFailure is removed,
 
1026
          only a dynamic_val of 42 will allow the test to pass.  Anything other
 
1027
          than 54 or 42 will cause an AssertionError.
 
1028
        """
 
1029
        try:
 
1030
            assertion(*args, **kwargs)
 
1031
        except AssertionError:
 
1032
            raise KnownFailure(reason)
 
1033
        else:
 
1034
            self.fail('Unexpected success.  Should have failed: %s' % reason)
 
1035
 
 
1036
    def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
 
1037
        """A helper for callDeprecated and applyDeprecated.
 
1038
 
 
1039
        :param a_callable: A callable to call.
 
1040
        :param args: The positional arguments for the callable
 
1041
        :param kwargs: The keyword arguments for the callable
 
1042
        :return: A tuple (warnings, result). result is the result of calling
 
1043
            a_callable(``*args``, ``**kwargs``).
 
1044
        """
 
1045
        local_warnings = []
 
1046
        def capture_warnings(msg, cls=None, stacklevel=None):
 
1047
            # we've hooked into a deprecation specific callpath,
 
1048
            # only deprecations should getting sent via it.
 
1049
            self.assertEqual(cls, DeprecationWarning)
 
1050
            local_warnings.append(msg)
 
1051
        original_warning_method = symbol_versioning.warn
 
1052
        symbol_versioning.set_warning_method(capture_warnings)
 
1053
        try:
 
1054
            result = a_callable(*args, **kwargs)
 
1055
        finally:
 
1056
            symbol_versioning.set_warning_method(original_warning_method)
 
1057
        return (local_warnings, result)
 
1058
 
 
1059
    def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
 
1060
        """Call a deprecated callable without warning the user.
 
1061
 
 
1062
        Note that this only captures warnings raised by symbol_versioning.warn,
 
1063
        not other callers that go direct to the warning module.
 
1064
 
 
1065
        To test that a deprecated method raises an error, do something like
 
1066
        this::
 
1067
 
 
1068
        self.assertRaises(errors.ReservedId,
 
1069
            self.applyDeprecated, zero_ninetyone,
 
1070
                br.append_revision, 'current:')
 
1071
 
 
1072
        :param deprecation_format: The deprecation format that the callable
 
1073
            should have been deprecated with. This is the same type as the
 
1074
            parameter to deprecated_method/deprecated_function. If the
 
1075
            callable is not deprecated with this format, an assertion error
 
1076
            will be raised.
 
1077
        :param a_callable: A callable to call. This may be a bound method or
 
1078
            a regular function. It will be called with ``*args`` and
 
1079
            ``**kwargs``.
 
1080
        :param args: The positional arguments for the callable
 
1081
        :param kwargs: The keyword arguments for the callable
 
1082
        :return: The result of a_callable(``*args``, ``**kwargs``)
 
1083
        """
 
1084
        call_warnings, result = self._capture_deprecation_warnings(a_callable,
 
1085
            *args, **kwargs)
 
1086
        expected_first_warning = symbol_versioning.deprecation_string(
 
1087
            a_callable, deprecation_format)
 
1088
        if len(call_warnings) == 0:
 
1089
            self.fail("No deprecation warning generated by call to %s" %
 
1090
                a_callable)
 
1091
        self.assertEqual(expected_first_warning, call_warnings[0])
 
1092
        return result
 
1093
 
 
1094
    def callCatchWarnings(self, fn, *args, **kw):
 
1095
        """Call a callable that raises python warnings.
 
1096
 
 
1097
        The caller's responsible for examining the returned warnings.
 
1098
 
 
1099
        If the callable raises an exception, the exception is not
 
1100
        caught and propagates up to the caller.  In that case, the list
 
1101
        of warnings is not available.
 
1102
 
 
1103
        :returns: ([warning_object, ...], fn_result)
 
1104
        """
 
1105
        # XXX: This is not perfect, because it completely overrides the
 
1106
        # warnings filters, and some code may depend on suppressing particular
 
1107
        # warnings.  It's the easiest way to insulate ourselves from -Werror,
 
1108
        # though.  -- Andrew, 20071062
 
1109
        wlist = []
 
1110
        def _catcher(message, category, filename, lineno, file=None):
 
1111
            # despite the name, 'message' is normally(?) a Warning subclass
 
1112
            # instance
 
1113
            wlist.append(message)
 
1114
        saved_showwarning = warnings.showwarning
 
1115
        saved_filters = warnings.filters
 
1116
        try:
 
1117
            warnings.showwarning = _catcher
 
1118
            warnings.filters = []
 
1119
            result = fn(*args, **kw)
 
1120
        finally:
 
1121
            warnings.showwarning = saved_showwarning
 
1122
            warnings.filters = saved_filters
 
1123
        return wlist, result
 
1124
 
 
1125
    def callDeprecated(self, expected, callable, *args, **kwargs):
 
1126
        """Assert that a callable is deprecated in a particular way.
 
1127
 
 
1128
        This is a very precise test for unusual requirements. The 
 
1129
        applyDeprecated helper function is probably more suited for most tests
 
1130
        as it allows you to simply specify the deprecation format being used
 
1131
        and will ensure that that is issued for the function being called.
 
1132
 
 
1133
        Note that this only captures warnings raised by symbol_versioning.warn,
 
1134
        not other callers that go direct to the warning module.  To catch
 
1135
        general warnings, use callCatchWarnings.
 
1136
 
 
1137
        :param expected: a list of the deprecation warnings expected, in order
 
1138
        :param callable: The callable to call
 
1139
        :param args: The positional arguments for the callable
 
1140
        :param kwargs: The keyword arguments for the callable
 
1141
        """
 
1142
        call_warnings, result = self._capture_deprecation_warnings(callable,
 
1143
            *args, **kwargs)
 
1144
        self.assertEqual(expected, call_warnings)
 
1145
        return result
 
1146
 
 
1147
    def _startLogFile(self):
 
1148
        """Send bzr and test log messages to a temporary file.
 
1149
 
 
1150
        The file is removed as the test is torn down.
 
1151
        """
 
1152
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
 
1153
        self._log_file = os.fdopen(fileno, 'w+')
 
1154
        self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
 
1155
        self._log_file_name = name
 
1156
        self.addCleanup(self._finishLogFile)
 
1157
 
 
1158
    def _finishLogFile(self):
 
1159
        """Finished with the log file.
 
1160
 
 
1161
        Close the file and delete it, unless setKeepLogfile was called.
 
1162
        """
 
1163
        if self._log_file is None:
 
1164
            return
 
1165
        bzrlib.trace.disable_test_log(self._log_nonce)
 
1166
        self._log_file.close()
 
1167
        self._log_file = None
 
1168
        if not self._keep_log_file:
 
1169
            os.remove(self._log_file_name)
 
1170
            self._log_file_name = None
 
1171
 
 
1172
    def setKeepLogfile(self):
 
1173
        """Make the logfile not be deleted when _finishLogFile is called."""
 
1174
        self._keep_log_file = True
 
1175
 
 
1176
    def addCleanup(self, callable):
 
1177
        """Arrange to run a callable when this case is torn down.
 
1178
 
 
1179
        Callables are run in the reverse of the order they are registered, 
 
1180
        ie last-in first-out.
 
1181
        """
 
1182
        if callable in self._cleanups:
 
1183
            raise ValueError("cleanup function %r already registered on %s" 
 
1184
                    % (callable, self))
 
1185
        self._cleanups.append(callable)
 
1186
 
 
1187
    def _cleanEnvironment(self):
 
1188
        new_env = {
 
1189
            'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
 
1190
            'HOME': os.getcwd(),
 
1191
            'APPDATA': None,  # bzr now use Win32 API and don't rely on APPDATA
 
1192
            'BZR_EDITOR': None, # test_msgeditor manipulates this variable
 
1193
            'BZR_EMAIL': None,
 
1194
            'BZREMAIL': None, # may still be present in the environment
 
1195
            'EMAIL': None,
 
1196
            'BZR_PROGRESS_BAR': None,
 
1197
            # SSH Agent
 
1198
            'SSH_AUTH_SOCK': None,
 
1199
            # Proxies
 
1200
            'http_proxy': None,
 
1201
            'HTTP_PROXY': None,
 
1202
            'https_proxy': None,
 
1203
            'HTTPS_PROXY': None,
 
1204
            'no_proxy': None,
 
1205
            'NO_PROXY': None,
 
1206
            'all_proxy': None,
 
1207
            'ALL_PROXY': None,
 
1208
            # Nobody cares about these ones AFAIK. So far at
 
1209
            # least. If you do (care), please update this comment
 
1210
            # -- vila 20061212
 
1211
            'ftp_proxy': None,
 
1212
            'FTP_PROXY': None,
 
1213
            'BZR_REMOTE_PATH': None,
 
1214
        }
 
1215
        self.__old_env = {}
 
1216
        self.addCleanup(self._restoreEnvironment)
 
1217
        for name, value in new_env.iteritems():
 
1218
            self._captureVar(name, value)
 
1219
 
 
1220
    def _captureVar(self, name, newvalue):
 
1221
        """Set an environment variable, and reset it when finished."""
 
1222
        self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
 
1223
 
 
1224
    def _restore_debug_flags(self):
 
1225
        debug.debug_flags.clear()
 
1226
        debug.debug_flags.update(self._preserved_debug_flags)
 
1227
 
 
1228
    def _restoreEnvironment(self):
 
1229
        for name, value in self.__old_env.iteritems():
 
1230
            osutils.set_or_unset_env(name, value)
 
1231
 
 
1232
    def _restoreHooks(self):
 
1233
        for klass, hooks in self._preserved_hooks.items():
 
1234
            setattr(klass, 'hooks', hooks)
 
1235
 
 
1236
    def knownFailure(self, reason):
 
1237
        """This test has failed for some known reason."""
 
1238
        raise KnownFailure(reason)
 
1239
 
 
1240
    def run(self, result=None):
 
1241
        if result is None: result = self.defaultTestResult()
 
1242
        for feature in getattr(self, '_test_needs_features', []):
 
1243
            if not feature.available():
 
1244
                result.startTest(self)
 
1245
                if getattr(result, 'addNotSupported', None):
 
1246
                    result.addNotSupported(self, feature)
 
1247
                else:
 
1248
                    result.addSuccess(self)
 
1249
                result.stopTest(self)
 
1250
                return
 
1251
        return unittest.TestCase.run(self, result)
 
1252
 
 
1253
    def tearDown(self):
 
1254
        self._runCleanups()
 
1255
        unittest.TestCase.tearDown(self)
 
1256
 
 
1257
    def time(self, callable, *args, **kwargs):
 
1258
        """Run callable and accrue the time it takes to the benchmark time.
 
1259
        
 
1260
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
 
1261
        this will cause lsprofile statistics to be gathered and stored in
 
1262
        self._benchcalls.
 
1263
        """
 
1264
        if self._benchtime is None:
 
1265
            self._benchtime = 0
 
1266
        start = time.time()
 
1267
        try:
 
1268
            if not self._gather_lsprof_in_benchmarks:
 
1269
                return callable(*args, **kwargs)
 
1270
            else:
 
1271
                # record this benchmark
 
1272
                ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
 
1273
                stats.sort()
 
1274
                self._benchcalls.append(((callable, args, kwargs), stats))
 
1275
                return ret
 
1276
        finally:
 
1277
            self._benchtime += time.time() - start
 
1278
 
 
1279
    def _runCleanups(self):
 
1280
        """Run registered cleanup functions. 
 
1281
 
 
1282
        This should only be called from TestCase.tearDown.
 
1283
        """
 
1284
        # TODO: Perhaps this should keep running cleanups even if 
 
1285
        # one of them fails?
 
1286
 
 
1287
        # Actually pop the cleanups from the list so tearDown running
 
1288
        # twice is safe (this happens for skipped tests).
 
1289
        while self._cleanups:
 
1290
            self._cleanups.pop()()
 
1291
 
 
1292
    def log(self, *args):
 
1293
        mutter(*args)
 
1294
 
 
1295
    def _get_log(self, keep_log_file=False):
 
1296
        """Get the log from bzrlib.trace calls from this test.
 
1297
 
 
1298
        :param keep_log_file: When True, if the log is still a file on disk
 
1299
            leave it as a file on disk. When False, if the log is still a file
 
1300
            on disk, the log file is deleted and the log preserved as
 
1301
            self._log_contents.
 
1302
        :return: A string containing the log.
 
1303
        """
 
1304
        # flush the log file, to get all content
 
1305
        import bzrlib.trace
 
1306
        bzrlib.trace._trace_file.flush()
 
1307
        if self._log_contents:
 
1308
            return self._log_contents
 
1309
        if self._log_file_name is not None:
 
1310
            logfile = open(self._log_file_name)
 
1311
            try:
 
1312
                log_contents = logfile.read()
 
1313
            finally:
 
1314
                logfile.close()
 
1315
            if not keep_log_file:
 
1316
                self._log_contents = log_contents
 
1317
                try:
 
1318
                    os.remove(self._log_file_name)
 
1319
                except OSError, e:
 
1320
                    if sys.platform == 'win32' and e.errno == errno.EACCES:
 
1321
                        sys.stderr.write(('Unable to delete log file '
 
1322
                                             ' %r\n' % self._log_file_name))
 
1323
                    else:
 
1324
                        raise
 
1325
            return log_contents
 
1326
        else:
 
1327
            return "DELETED log file to reduce memory footprint"
 
1328
 
 
1329
    def requireFeature(self, feature):
 
1330
        """This test requires a specific feature is available.
 
1331
 
 
1332
        :raises UnavailableFeature: When feature is not available.
 
1333
        """
 
1334
        if not feature.available():
 
1335
            raise UnavailableFeature(feature)
 
1336
 
 
1337
    def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
 
1338
            working_dir):
 
1339
        """Run bazaar command line, splitting up a string command line."""
 
1340
        if isinstance(args, basestring):
 
1341
            # shlex don't understand unicode strings,
 
1342
            # so args should be plain string (bialix 20070906)
 
1343
            args = list(shlex.split(str(args)))
 
1344
        return self._run_bzr_core(args, retcode=retcode,
 
1345
                encoding=encoding, stdin=stdin, working_dir=working_dir,
 
1346
                )
 
1347
 
 
1348
    def _run_bzr_core(self, args, retcode, encoding, stdin,
 
1349
            working_dir):
 
1350
        if encoding is None:
 
1351
            encoding = bzrlib.user_encoding
 
1352
        stdout = StringIOWrapper()
 
1353
        stderr = StringIOWrapper()
 
1354
        stdout.encoding = encoding
 
1355
        stderr.encoding = encoding
 
1356
 
 
1357
        self.log('run bzr: %r', args)
 
1358
        # FIXME: don't call into logging here
 
1359
        handler = logging.StreamHandler(stderr)
 
1360
        handler.setLevel(logging.INFO)
 
1361
        logger = logging.getLogger('')
 
1362
        logger.addHandler(handler)
 
1363
        old_ui_factory = ui.ui_factory
 
1364
        ui.ui_factory = TestUIFactory(stdin=stdin, stdout=stdout, stderr=stderr)
 
1365
 
 
1366
        cwd = None
 
1367
        if working_dir is not None:
 
1368
            cwd = osutils.getcwd()
 
1369
            os.chdir(working_dir)
 
1370
 
 
1371
        try:
 
1372
            result = self.apply_redirected(ui.ui_factory.stdin,
 
1373
                stdout, stderr,
 
1374
                bzrlib.commands.run_bzr_catch_user_errors,
 
1375
                args)
 
1376
        finally:
 
1377
            logger.removeHandler(handler)
 
1378
            ui.ui_factory = old_ui_factory
 
1379
            if cwd is not None:
 
1380
                os.chdir(cwd)
 
1381
 
 
1382
        out = stdout.getvalue()
 
1383
        err = stderr.getvalue()
 
1384
        if out:
 
1385
            self.log('output:\n%r', out)
 
1386
        if err:
 
1387
            self.log('errors:\n%r', err)
 
1388
        if retcode is not None:
 
1389
            self.assertEquals(retcode, result,
 
1390
                              message='Unexpected return code')
 
1391
        return out, err
 
1392
 
 
1393
    def run_bzr(self, args, retcode=0, encoding=None, stdin=None,
 
1394
                working_dir=None, error_regexes=[], output_encoding=None):
 
1395
        """Invoke bzr, as if it were run from the command line.
 
1396
 
 
1397
        The argument list should not include the bzr program name - the
 
1398
        first argument is normally the bzr command.  Arguments may be
 
1399
        passed in three ways:
 
1400
 
 
1401
        1- A list of strings, eg ["commit", "a"].  This is recommended
 
1402
        when the command contains whitespace or metacharacters, or 
 
1403
        is built up at run time.
 
1404
 
 
1405
        2- A single string, eg "add a".  This is the most convenient 
 
1406
        for hardcoded commands.
 
1407
 
 
1408
        This runs bzr through the interface that catches and reports
 
1409
        errors, and with logging set to something approximating the
 
1410
        default, so that error reporting can be checked.
 
1411
 
 
1412
        This should be the main method for tests that want to exercise the
 
1413
        overall behavior of the bzr application (rather than a unit test
 
1414
        or a functional test of the library.)
 
1415
 
 
1416
        This sends the stdout/stderr results into the test's log,
 
1417
        where it may be useful for debugging.  See also run_captured.
 
1418
 
 
1419
        :keyword stdin: A string to be used as stdin for the command.
 
1420
        :keyword retcode: The status code the command should return;
 
1421
            default 0.
 
1422
        :keyword working_dir: The directory to run the command in
 
1423
        :keyword error_regexes: A list of expected error messages.  If
 
1424
            specified they must be seen in the error output of the command.
 
1425
        """
 
1426
        out, err = self._run_bzr_autosplit(
 
1427
            args=args,
 
1428
            retcode=retcode,
 
1429
            encoding=encoding,
 
1430
            stdin=stdin,
 
1431
            working_dir=working_dir,
 
1432
            )
 
1433
        for regex in error_regexes:
 
1434
            self.assertContainsRe(err, regex)
 
1435
        return out, err
 
1436
 
 
1437
    def run_bzr_error(self, error_regexes, *args, **kwargs):
 
1438
        """Run bzr, and check that stderr contains the supplied regexes
 
1439
 
 
1440
        :param error_regexes: Sequence of regular expressions which
 
1441
            must each be found in the error output. The relative ordering
 
1442
            is not enforced.
 
1443
        :param args: command-line arguments for bzr
 
1444
        :param kwargs: Keyword arguments which are interpreted by run_bzr
 
1445
            This function changes the default value of retcode to be 3,
 
1446
            since in most cases this is run when you expect bzr to fail.
 
1447
 
 
1448
        :return: (out, err) The actual output of running the command (in case
 
1449
            you want to do more inspection)
 
1450
 
 
1451
        Examples of use::
 
1452
 
 
1453
            # Make sure that commit is failing because there is nothing to do
 
1454
            self.run_bzr_error(['no changes to commit'],
 
1455
                               ['commit', '-m', 'my commit comment'])
 
1456
            # Make sure --strict is handling an unknown file, rather than
 
1457
            # giving us the 'nothing to do' error
 
1458
            self.build_tree(['unknown'])
 
1459
            self.run_bzr_error(['Commit refused because there are unknown files'],
 
1460
                               ['commit', --strict', '-m', 'my commit comment'])
 
1461
        """
 
1462
        kwargs.setdefault('retcode', 3)
 
1463
        kwargs['error_regexes'] = error_regexes
 
1464
        out, err = self.run_bzr(*args, **kwargs)
 
1465
        return out, err
 
1466
 
 
1467
    def run_bzr_subprocess(self, *args, **kwargs):
 
1468
        """Run bzr in a subprocess for testing.
 
1469
 
 
1470
        This starts a new Python interpreter and runs bzr in there. 
 
1471
        This should only be used for tests that have a justifiable need for
 
1472
        this isolation: e.g. they are testing startup time, or signal
 
1473
        handling, or early startup code, etc.  Subprocess code can't be 
 
1474
        profiled or debugged so easily.
 
1475
 
 
1476
        :keyword retcode: The status code that is expected.  Defaults to 0.  If
 
1477
            None is supplied, the status code is not checked.
 
1478
        :keyword env_changes: A dictionary which lists changes to environment
 
1479
            variables. A value of None will unset the env variable.
 
1480
            The values must be strings. The change will only occur in the
 
1481
            child, so you don't need to fix the environment after running.
 
1482
        :keyword universal_newlines: Convert CRLF => LF
 
1483
        :keyword allow_plugins: By default the subprocess is run with
 
1484
            --no-plugins to ensure test reproducibility. Also, it is possible
 
1485
            for system-wide plugins to create unexpected output on stderr,
 
1486
            which can cause unnecessary test failures.
 
1487
        """
 
1488
        env_changes = kwargs.get('env_changes', {})
 
1489
        working_dir = kwargs.get('working_dir', None)
 
1490
        allow_plugins = kwargs.get('allow_plugins', False)
 
1491
        if len(args) == 1:
 
1492
            if isinstance(args[0], list):
 
1493
                args = args[0]
 
1494
            elif isinstance(args[0], basestring):
 
1495
                args = list(shlex.split(args[0]))
 
1496
        else:
 
1497
            symbol_versioning.warn(zero_ninetyone %
 
1498
                                   "passing varargs to run_bzr_subprocess",
 
1499
                                   DeprecationWarning, stacklevel=3)
 
1500
        process = self.start_bzr_subprocess(args, env_changes=env_changes,
 
1501
                                            working_dir=working_dir,
 
1502
                                            allow_plugins=allow_plugins)
 
1503
        # We distinguish between retcode=None and retcode not passed.
 
1504
        supplied_retcode = kwargs.get('retcode', 0)
 
1505
        return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
 
1506
            universal_newlines=kwargs.get('universal_newlines', False),
 
1507
            process_args=args)
 
1508
 
 
1509
    def start_bzr_subprocess(self, process_args, env_changes=None,
 
1510
                             skip_if_plan_to_signal=False,
 
1511
                             working_dir=None,
 
1512
                             allow_plugins=False):
 
1513
        """Start bzr in a subprocess for testing.
 
1514
 
 
1515
        This starts a new Python interpreter and runs bzr in there.
 
1516
        This should only be used for tests that have a justifiable need for
 
1517
        this isolation: e.g. they are testing startup time, or signal
 
1518
        handling, or early startup code, etc.  Subprocess code can't be
 
1519
        profiled or debugged so easily.
 
1520
 
 
1521
        :param process_args: a list of arguments to pass to the bzr executable,
 
1522
            for example ``['--version']``.
 
1523
        :param env_changes: A dictionary which lists changes to environment
 
1524
            variables. A value of None will unset the env variable.
 
1525
            The values must be strings. The change will only occur in the
 
1526
            child, so you don't need to fix the environment after running.
 
1527
        :param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
 
1528
            is not available.
 
1529
        :param allow_plugins: If False (default) pass --no-plugins to bzr.
 
1530
 
 
1531
        :returns: Popen object for the started process.
 
1532
        """
 
1533
        if skip_if_plan_to_signal:
 
1534
            if not getattr(os, 'kill', None):
 
1535
                raise TestSkipped("os.kill not available.")
 
1536
 
 
1537
        if env_changes is None:
 
1538
            env_changes = {}
 
1539
        old_env = {}
 
1540
 
 
1541
        def cleanup_environment():
 
1542
            for env_var, value in env_changes.iteritems():
 
1543
                old_env[env_var] = osutils.set_or_unset_env(env_var, value)
 
1544
 
 
1545
        def restore_environment():
 
1546
            for env_var, value in old_env.iteritems():
 
1547
                osutils.set_or_unset_env(env_var, value)
 
1548
 
 
1549
        bzr_path = self.get_bzr_path()
 
1550
 
 
1551
        cwd = None
 
1552
        if working_dir is not None:
 
1553
            cwd = osutils.getcwd()
 
1554
            os.chdir(working_dir)
 
1555
 
 
1556
        try:
 
1557
            # win32 subprocess doesn't support preexec_fn
 
1558
            # so we will avoid using it on all platforms, just to
 
1559
            # make sure the code path is used, and we don't break on win32
 
1560
            cleanup_environment()
 
1561
            command = [sys.executable, bzr_path]
 
1562
            if not allow_plugins:
 
1563
                command.append('--no-plugins')
 
1564
            command.extend(process_args)
 
1565
            process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
 
1566
        finally:
 
1567
            restore_environment()
 
1568
            if cwd is not None:
 
1569
                os.chdir(cwd)
 
1570
 
 
1571
        return process
 
1572
 
 
1573
    def _popen(self, *args, **kwargs):
 
1574
        """Place a call to Popen.
 
1575
 
 
1576
        Allows tests to override this method to intercept the calls made to
 
1577
        Popen for introspection.
 
1578
        """
 
1579
        return Popen(*args, **kwargs)
 
1580
 
 
1581
    def get_bzr_path(self):
 
1582
        """Return the path of the 'bzr' executable for this test suite."""
 
1583
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
1584
        if not os.path.isfile(bzr_path):
 
1585
            # We are probably installed. Assume sys.argv is the right file
 
1586
            bzr_path = sys.argv[0]
 
1587
        return bzr_path
 
1588
 
 
1589
    def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
 
1590
                              universal_newlines=False, process_args=None):
 
1591
        """Finish the execution of process.
 
1592
 
 
1593
        :param process: the Popen object returned from start_bzr_subprocess.
 
1594
        :param retcode: The status code that is expected.  Defaults to 0.  If
 
1595
            None is supplied, the status code is not checked.
 
1596
        :param send_signal: an optional signal to send to the process.
 
1597
        :param universal_newlines: Convert CRLF => LF
 
1598
        :returns: (stdout, stderr)
 
1599
        """
 
1600
        if send_signal is not None:
 
1601
            os.kill(process.pid, send_signal)
 
1602
        out, err = process.communicate()
 
1603
 
 
1604
        if universal_newlines:
 
1605
            out = out.replace('\r\n', '\n')
 
1606
            err = err.replace('\r\n', '\n')
 
1607
 
 
1608
        if retcode is not None and retcode != process.returncode:
 
1609
            if process_args is None:
 
1610
                process_args = "(unknown args)"
 
1611
            mutter('Output of bzr %s:\n%s', process_args, out)
 
1612
            mutter('Error for bzr %s:\n%s', process_args, err)
 
1613
            self.fail('Command bzr %s failed with retcode %s != %s'
 
1614
                      % (process_args, retcode, process.returncode))
 
1615
        return [out, err]
 
1616
 
 
1617
    def check_inventory_shape(self, inv, shape):
 
1618
        """Compare an inventory to a list of expected names.
 
1619
 
 
1620
        Fail if they are not precisely equal.
 
1621
        """
 
1622
        extras = []
 
1623
        shape = list(shape)             # copy
 
1624
        for path, ie in inv.entries():
 
1625
            name = path.replace('\\', '/')
 
1626
            if ie.kind == 'directory':
 
1627
                name = name + '/'
 
1628
            if name in shape:
 
1629
                shape.remove(name)
 
1630
            else:
 
1631
                extras.append(name)
 
1632
        if shape:
 
1633
            self.fail("expected paths not found in inventory: %r" % shape)
 
1634
        if extras:
 
1635
            self.fail("unexpected paths found in inventory: %r" % extras)
 
1636
 
 
1637
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
1638
                         a_callable=None, *args, **kwargs):
 
1639
        """Call callable with redirected std io pipes.
 
1640
 
 
1641
        Returns the return code."""
 
1642
        if not callable(a_callable):
 
1643
            raise ValueError("a_callable must be callable.")
 
1644
        if stdin is None:
 
1645
            stdin = StringIO("")
 
1646
        if stdout is None:
 
1647
            if getattr(self, "_log_file", None) is not None:
 
1648
                stdout = self._log_file
 
1649
            else:
 
1650
                stdout = StringIO()
 
1651
        if stderr is None:
 
1652
            if getattr(self, "_log_file", None is not None):
 
1653
                stderr = self._log_file
 
1654
            else:
 
1655
                stderr = StringIO()
 
1656
        real_stdin = sys.stdin
 
1657
        real_stdout = sys.stdout
 
1658
        real_stderr = sys.stderr
 
1659
        try:
 
1660
            sys.stdout = stdout
 
1661
            sys.stderr = stderr
 
1662
            sys.stdin = stdin
 
1663
            return a_callable(*args, **kwargs)
 
1664
        finally:
 
1665
            sys.stdout = real_stdout
 
1666
            sys.stderr = real_stderr
 
1667
            sys.stdin = real_stdin
 
1668
 
 
1669
    def reduceLockdirTimeout(self):
 
1670
        """Reduce the default lock timeout for the duration of the test, so that
 
1671
        if LockContention occurs during a test, it does so quickly.
 
1672
 
 
1673
        Tests that expect to provoke LockContention errors should call this.
 
1674
        """
 
1675
        orig_timeout = bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS
 
1676
        def resetTimeout():
 
1677
            bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = orig_timeout
 
1678
        self.addCleanup(resetTimeout)
 
1679
        bzrlib.lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
1680
 
 
1681
    def make_utf8_encoded_stringio(self, encoding_type=None):
 
1682
        """Return a StringIOWrapper instance, that will encode Unicode
 
1683
        input to UTF-8.
 
1684
        """
 
1685
        if encoding_type is None:
 
1686
            encoding_type = 'strict'
 
1687
        sio = StringIO()
 
1688
        output_encoding = 'utf-8'
 
1689
        sio = codecs.getwriter(output_encoding)(sio, errors=encoding_type)
 
1690
        sio.encoding = output_encoding
 
1691
        return sio
 
1692
 
 
1693
 
 
1694
class TestCaseWithMemoryTransport(TestCase):
 
1695
    """Common test class for tests that do not need disk resources.
 
1696
 
 
1697
    Tests that need disk resources should derive from TestCaseWithTransport.
 
1698
 
 
1699
    TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
 
1700
 
 
1701
    For TestCaseWithMemoryTransport the test_home_dir is set to the name of
 
1702
    a directory which does not exist. This serves to help ensure test isolation
 
1703
    is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
 
1704
    must exist. However, TestCaseWithMemoryTransport does not offer local
 
1705
    file defaults for the transport in tests, nor does it obey the command line
 
1706
    override, so tests that accidentally write to the common directory should
 
1707
    be rare.
 
1708
 
 
1709
    :cvar TEST_ROOT: Directory containing all temporary directories, plus
 
1710
    a .bzr directory that stops us ascending higher into the filesystem.
 
1711
    """
 
1712
 
 
1713
    TEST_ROOT = None
 
1714
    _TEST_NAME = 'test'
 
1715
 
 
1716
    def __init__(self, methodName='runTest'):
 
1717
        # allow test parameterisation after test construction and before test
 
1718
        # execution. Variables that the parameteriser sets need to be 
 
1719
        # ones that are not set by setUp, or setUp will trash them.
 
1720
        super(TestCaseWithMemoryTransport, self).__init__(methodName)
 
1721
        self.vfs_transport_factory = default_transport
 
1722
        self.transport_server = None
 
1723
        self.transport_readonly_server = None
 
1724
        self.__vfs_server = None
 
1725
 
 
1726
    def get_transport(self, relpath=None):
 
1727
        """Return a writeable transport.
 
1728
 
 
1729
        This transport is for the test scratch space relative to
 
1730
        "self._test_root"
 
1731
        
 
1732
        :param relpath: a path relative to the base url.
 
1733
        """
 
1734
        t = get_transport(self.get_url(relpath))
 
1735
        self.assertFalse(t.is_readonly())
 
1736
        return t
 
1737
 
 
1738
    def get_readonly_transport(self, relpath=None):
 
1739
        """Return a readonly transport for the test scratch space
 
1740
        
 
1741
        This can be used to test that operations which should only need
 
1742
        readonly access in fact do not try to write.
 
1743
 
 
1744
        :param relpath: a path relative to the base url.
 
1745
        """
 
1746
        t = get_transport(self.get_readonly_url(relpath))
 
1747
        self.assertTrue(t.is_readonly())
 
1748
        return t
 
1749
 
 
1750
    def create_transport_readonly_server(self):
 
1751
        """Create a transport server from class defined at init.
 
1752
 
 
1753
        This is mostly a hook for daughter classes.
 
1754
        """
 
1755
        return self.transport_readonly_server()
 
1756
 
 
1757
    def get_readonly_server(self):
 
1758
        """Get the server instance for the readonly transport
 
1759
 
 
1760
        This is useful for some tests with specific servers to do diagnostics.
 
1761
        """
 
1762
        if self.__readonly_server is None:
 
1763
            if self.transport_readonly_server is None:
 
1764
                # readonly decorator requested
 
1765
                # bring up the server
 
1766
                self.__readonly_server = ReadonlyServer()
 
1767
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
1768
            else:
 
1769
                self.__readonly_server = self.create_transport_readonly_server()
 
1770
                self.__readonly_server.setUp(self.get_vfs_only_server())
 
1771
            self.addCleanup(self.__readonly_server.tearDown)
 
1772
        return self.__readonly_server
 
1773
 
 
1774
    def get_readonly_url(self, relpath=None):
 
1775
        """Get a URL for the readonly transport.
 
1776
 
 
1777
        This will either be backed by '.' or a decorator to the transport 
 
1778
        used by self.get_url()
 
1779
        relpath provides for clients to get a path relative to the base url.
 
1780
        These should only be downwards relative, not upwards.
 
1781
        """
 
1782
        base = self.get_readonly_server().get_url()
 
1783
        return self._adjust_url(base, relpath)
 
1784
 
 
1785
    def get_vfs_only_server(self):
 
1786
        """Get the vfs only read/write server instance.
 
1787
 
 
1788
        This is useful for some tests with specific servers that need
 
1789
        diagnostics.
 
1790
 
 
1791
        For TestCaseWithMemoryTransport this is always a MemoryServer, and there
 
1792
        is no means to override it.
 
1793
        """
 
1794
        if self.__vfs_server is None:
 
1795
            self.__vfs_server = MemoryServer()
 
1796
            self.__vfs_server.setUp()
 
1797
            self.addCleanup(self.__vfs_server.tearDown)
 
1798
        return self.__vfs_server
 
1799
 
 
1800
    def get_server(self):
 
1801
        """Get the read/write server instance.
 
1802
 
 
1803
        This is useful for some tests with specific servers that need
 
1804
        diagnostics.
 
1805
 
 
1806
        This is built from the self.transport_server factory. If that is None,
 
1807
        then the self.get_vfs_server is returned.
 
1808
        """
 
1809
        if self.__server is None:
 
1810
            if self.transport_server is None or self.transport_server is self.vfs_transport_factory:
 
1811
                return self.get_vfs_only_server()
 
1812
            else:
 
1813
                # bring up a decorated means of access to the vfs only server.
 
1814
                self.__server = self.transport_server()
 
1815
                try:
 
1816
                    self.__server.setUp(self.get_vfs_only_server())
 
1817
                except TypeError, e:
 
1818
                    # This should never happen; the try:Except here is to assist
 
1819
                    # developers having to update code rather than seeing an
 
1820
                    # uninformative TypeError.
 
1821
                    raise Exception, "Old server API in use: %s, %s" % (self.__server, e)
 
1822
            self.addCleanup(self.__server.tearDown)
 
1823
        return self.__server
 
1824
 
 
1825
    def _adjust_url(self, base, relpath):
 
1826
        """Get a URL (or maybe a path) for the readwrite transport.
 
1827
 
 
1828
        This will either be backed by '.' or to an equivalent non-file based
 
1829
        facility.
 
1830
        relpath provides for clients to get a path relative to the base url.
 
1831
        These should only be downwards relative, not upwards.
 
1832
        """
 
1833
        if relpath is not None and relpath != '.':
 
1834
            if not base.endswith('/'):
 
1835
                base = base + '/'
 
1836
            # XXX: Really base should be a url; we did after all call
 
1837
            # get_url()!  But sometimes it's just a path (from
 
1838
            # LocalAbspathServer), and it'd be wrong to append urlescaped data
 
1839
            # to a non-escaped local path.
 
1840
            if base.startswith('./') or base.startswith('/'):
 
1841
                base += relpath
 
1842
            else:
 
1843
                base += urlutils.escape(relpath)
 
1844
        return base
 
1845
 
 
1846
    def get_url(self, relpath=None):
 
1847
        """Get a URL (or maybe a path) for the readwrite transport.
 
1848
 
 
1849
        This will either be backed by '.' or to an equivalent non-file based
 
1850
        facility.
 
1851
        relpath provides for clients to get a path relative to the base url.
 
1852
        These should only be downwards relative, not upwards.
 
1853
        """
 
1854
        base = self.get_server().get_url()
 
1855
        return self._adjust_url(base, relpath)
 
1856
 
 
1857
    def get_vfs_only_url(self, relpath=None):
 
1858
        """Get a URL (or maybe a path for the plain old vfs transport.
 
1859
 
 
1860
        This will never be a smart protocol.  It always has all the
 
1861
        capabilities of the local filesystem, but it might actually be a
 
1862
        MemoryTransport or some other similar virtual filesystem.
 
1863
 
 
1864
        This is the backing transport (if any) of the server returned by
 
1865
        get_url and get_readonly_url.
 
1866
 
 
1867
        :param relpath: provides for clients to get a path relative to the base
 
1868
            url.  These should only be downwards relative, not upwards.
 
1869
        :return: A URL
 
1870
        """
 
1871
        base = self.get_vfs_only_server().get_url()
 
1872
        return self._adjust_url(base, relpath)
 
1873
 
 
1874
    def _create_safety_net(self):
 
1875
        """Make a fake bzr directory.
 
1876
 
 
1877
        This prevents any tests propagating up onto the TEST_ROOT directory's
 
1878
        real branch.
 
1879
        """
 
1880
        root = TestCaseWithMemoryTransport.TEST_ROOT
 
1881
        bzrdir.BzrDir.create_standalone_workingtree(root)
 
1882
 
 
1883
    def _check_safety_net(self):
 
1884
        """Check that the safety .bzr directory have not been touched.
 
1885
 
 
1886
        _make_test_root have created a .bzr directory to prevent tests from
 
1887
        propagating. This method ensures than a test did not leaked.
 
1888
        """
 
1889
        root = TestCaseWithMemoryTransport.TEST_ROOT
 
1890
        wt = workingtree.WorkingTree.open(root)
 
1891
        last_rev = wt.last_revision()
 
1892
        if last_rev != 'null:':
 
1893
            # The current test have modified the /bzr directory, we need to
 
1894
            # recreate a new one or all the followng tests will fail.
 
1895
            # If you need to inspect its content uncomment the following line
 
1896
            # import pdb; pdb.set_trace()
 
1897
            _rmtree_temp_dir(root + '/.bzr')
 
1898
            self._create_safety_net()
 
1899
            raise AssertionError('%s/.bzr should not be modified' % root)
 
1900
 
 
1901
    def _make_test_root(self):
 
1902
        if TestCaseWithMemoryTransport.TEST_ROOT is None:
 
1903
            root = osutils.mkdtemp(prefix='testbzr-', suffix='.tmp')
 
1904
            TestCaseWithMemoryTransport.TEST_ROOT = root
 
1905
 
 
1906
            self._create_safety_net()
 
1907
 
 
1908
            # The same directory is used by all tests, and we're not
 
1909
            # specifically told when all tests are finished.  This will do.
 
1910
            atexit.register(_rmtree_temp_dir, root)
 
1911
 
 
1912
        self.addCleanup(self._check_safety_net)
 
1913
 
 
1914
    def makeAndChdirToTestDir(self):
 
1915
        """Create a temporary directories for this one test.
 
1916
        
 
1917
        This must set self.test_home_dir and self.test_dir and chdir to
 
1918
        self.test_dir.
 
1919
        
 
1920
        For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
 
1921
        """
 
1922
        os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
 
1923
        self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
 
1924
        self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
 
1925
        
 
1926
    def make_branch(self, relpath, format=None):
 
1927
        """Create a branch on the transport at relpath."""
 
1928
        repo = self.make_repository(relpath, format=format)
 
1929
        return repo.bzrdir.create_branch()
 
1930
 
 
1931
    def make_bzrdir(self, relpath, format=None):
 
1932
        try:
 
1933
            # might be a relative or absolute path
 
1934
            maybe_a_url = self.get_url(relpath)
 
1935
            segments = maybe_a_url.rsplit('/', 1)
 
1936
            t = get_transport(maybe_a_url)
 
1937
            if len(segments) > 1 and segments[-1] not in ('', '.'):
 
1938
                t.ensure_base()
 
1939
            if format is None:
 
1940
                format = 'default'
 
1941
            if isinstance(format, basestring):
 
1942
                format = bzrdir.format_registry.make_bzrdir(format)
 
1943
            return format.initialize_on_transport(t)
 
1944
        except errors.UninitializableFormat:
 
1945
            raise TestSkipped("Format %s is not initializable." % format)
 
1946
 
 
1947
    def make_repository(self, relpath, shared=False, format=None):
 
1948
        """Create a repository on our default transport at relpath.
 
1949
        
 
1950
        Note that relpath must be a relative path, not a full url.
 
1951
        """
 
1952
        # FIXME: If you create a remoterepository this returns the underlying
 
1953
        # real format, which is incorrect.  Actually we should make sure that 
 
1954
        # RemoteBzrDir returns a RemoteRepository.
 
1955
        # maybe  mbp 20070410
 
1956
        made_control = self.make_bzrdir(relpath, format=format)
 
1957
        return made_control.create_repository(shared=shared)
 
1958
 
 
1959
    def make_branch_and_memory_tree(self, relpath, format=None):
 
1960
        """Create a branch on the default transport and a MemoryTree for it."""
 
1961
        b = self.make_branch(relpath, format=format)
 
1962
        return memorytree.MemoryTree.create_on_branch(b)
 
1963
 
 
1964
    def overrideEnvironmentForTesting(self):
 
1965
        os.environ['HOME'] = self.test_home_dir
 
1966
        os.environ['BZR_HOME'] = self.test_home_dir
 
1967
        
 
1968
    def setUp(self):
 
1969
        super(TestCaseWithMemoryTransport, self).setUp()
 
1970
        self._make_test_root()
 
1971
        _currentdir = os.getcwdu()
 
1972
        def _leaveDirectory():
 
1973
            os.chdir(_currentdir)
 
1974
        self.addCleanup(_leaveDirectory)
 
1975
        self.makeAndChdirToTestDir()
 
1976
        self.overrideEnvironmentForTesting()
 
1977
        self.__readonly_server = None
 
1978
        self.__server = None
 
1979
        self.reduceLockdirTimeout()
 
1980
 
 
1981
     
 
1982
class TestCaseInTempDir(TestCaseWithMemoryTransport):
 
1983
    """Derived class that runs a test within a temporary directory.
 
1984
 
 
1985
    This is useful for tests that need to create a branch, etc.
 
1986
 
 
1987
    The directory is created in a slightly complex way: for each
 
1988
    Python invocation, a new temporary top-level directory is created.
 
1989
    All test cases create their own directory within that.  If the
 
1990
    tests complete successfully, the directory is removed.
 
1991
 
 
1992
    :ivar test_base_dir: The path of the top-level directory for this 
 
1993
    test, which contains a home directory and a work directory.
 
1994
 
 
1995
    :ivar test_home_dir: An initially empty directory under test_base_dir
 
1996
    which is used as $HOME for this test.
 
1997
 
 
1998
    :ivar test_dir: A directory under test_base_dir used as the current
 
1999
    directory when the test proper is run.
 
2000
    """
 
2001
 
 
2002
    OVERRIDE_PYTHON = 'python'
 
2003
 
 
2004
    def check_file_contents(self, filename, expect):
 
2005
        self.log("check contents of file %s" % filename)
 
2006
        contents = file(filename, 'r').read()
 
2007
        if contents != expect:
 
2008
            self.log("expected: %r" % expect)
 
2009
            self.log("actually: %r" % contents)
 
2010
            self.fail("contents of %s not as expected" % filename)
 
2011
 
 
2012
    def makeAndChdirToTestDir(self):
 
2013
        """See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
 
2014
        
 
2015
        For TestCaseInTempDir we create a temporary directory based on the test
 
2016
        name and then create two subdirs - test and home under it.
 
2017
        """
 
2018
        # create a directory within the top level test directory
 
2019
        candidate_dir = osutils.mkdtemp(dir=self.TEST_ROOT)
 
2020
        # now create test and home directories within this dir
 
2021
        self.test_base_dir = candidate_dir
 
2022
        self.test_home_dir = self.test_base_dir + '/home'
 
2023
        os.mkdir(self.test_home_dir)
 
2024
        self.test_dir = self.test_base_dir + '/work'
 
2025
        os.mkdir(self.test_dir)
 
2026
        os.chdir(self.test_dir)
 
2027
        # put name of test inside
 
2028
        f = file(self.test_base_dir + '/name', 'w')
 
2029
        try:
 
2030
            f.write(self.id())
 
2031
        finally:
 
2032
            f.close()
 
2033
        self.addCleanup(self.deleteTestDir)
 
2034
 
 
2035
    def deleteTestDir(self):
 
2036
        os.chdir(self.TEST_ROOT)
 
2037
        _rmtree_temp_dir(self.test_base_dir)
 
2038
 
 
2039
    def build_tree(self, shape, line_endings='binary', transport=None):
 
2040
        """Build a test tree according to a pattern.
 
2041
 
 
2042
        shape is a sequence of file specifications.  If the final
 
2043
        character is '/', a directory is created.
 
2044
 
 
2045
        This assumes that all the elements in the tree being built are new.
 
2046
 
 
2047
        This doesn't add anything to a branch.
 
2048
 
 
2049
        :type shape:    list or tuple.
 
2050
        :param line_endings: Either 'binary' or 'native'
 
2051
            in binary mode, exact contents are written in native mode, the
 
2052
            line endings match the default platform endings.
 
2053
        :param transport: A transport to write to, for building trees on VFS's.
 
2054
            If the transport is readonly or None, "." is opened automatically.
 
2055
        :return: None
 
2056
        """
 
2057
        if type(shape) not in (list, tuple):
 
2058
            raise AssertionError("Parameter 'shape' should be "
 
2059
                "a list or a tuple. Got %r instead" % (shape,))
 
2060
        # It's OK to just create them using forward slashes on windows.
 
2061
        if transport is None or transport.is_readonly():
 
2062
            transport = get_transport(".")
 
2063
        for name in shape:
 
2064
            self.assert_(isinstance(name, basestring))
 
2065
            if name[-1] == '/':
 
2066
                transport.mkdir(urlutils.escape(name[:-1]))
 
2067
            else:
 
2068
                if line_endings == 'binary':
 
2069
                    end = '\n'
 
2070
                elif line_endings == 'native':
 
2071
                    end = os.linesep
 
2072
                else:
 
2073
                    raise errors.BzrError(
 
2074
                        'Invalid line ending request %r' % line_endings)
 
2075
                content = "contents of %s%s" % (name.encode('utf-8'), end)
 
2076
                transport.put_bytes_non_atomic(urlutils.escape(name), content)
 
2077
 
 
2078
    def build_tree_contents(self, shape):
 
2079
        build_tree_contents(shape)
 
2080
 
 
2081
    def assertFileEqual(self, content, path):
 
2082
        """Fail if path does not contain 'content'."""
 
2083
        self.failUnlessExists(path)
 
2084
        f = file(path, 'rb')
 
2085
        try:
 
2086
            s = f.read()
 
2087
        finally:
 
2088
            f.close()
 
2089
        self.assertEqualDiff(content, s)
 
2090
 
 
2091
    def failUnlessExists(self, path):
 
2092
        """Fail unless path or paths, which may be abs or relative, exist."""
 
2093
        if not isinstance(path, basestring):
 
2094
            for p in path:
 
2095
                self.failUnlessExists(p)
 
2096
        else:
 
2097
            self.failUnless(osutils.lexists(path),path+" does not exist")
 
2098
 
 
2099
    def failIfExists(self, path):
 
2100
        """Fail if path or paths, which may be abs or relative, exist."""
 
2101
        if not isinstance(path, basestring):
 
2102
            for p in path:
 
2103
                self.failIfExists(p)
 
2104
        else:
 
2105
            self.failIf(osutils.lexists(path),path+" exists")
 
2106
 
 
2107
    def assertInWorkingTree(self, path, root_path='.', tree=None):
 
2108
        """Assert whether path or paths are in the WorkingTree"""
 
2109
        if tree is None:
 
2110
            tree = workingtree.WorkingTree.open(root_path)
 
2111
        if not isinstance(path, basestring):
 
2112
            for p in path:
 
2113
                self.assertInWorkingTree(p,tree=tree)
 
2114
        else:
 
2115
            self.assertIsNot(tree.path2id(path), None,
 
2116
                path+' not in working tree.')
 
2117
 
 
2118
    def assertNotInWorkingTree(self, path, root_path='.', tree=None):
 
2119
        """Assert whether path or paths are not in the WorkingTree"""
 
2120
        if tree is None:
 
2121
            tree = workingtree.WorkingTree.open(root_path)
 
2122
        if not isinstance(path, basestring):
 
2123
            for p in path:
 
2124
                self.assertNotInWorkingTree(p,tree=tree)
 
2125
        else:
 
2126
            self.assertIs(tree.path2id(path), None, path+' in working tree.')
 
2127
 
 
2128
 
 
2129
class TestCaseWithTransport(TestCaseInTempDir):
 
2130
    """A test case that provides get_url and get_readonly_url facilities.
 
2131
 
 
2132
    These back onto two transport servers, one for readonly access and one for
 
2133
    read write access.
 
2134
 
 
2135
    If no explicit class is provided for readonly access, a
 
2136
    ReadonlyTransportDecorator is used instead which allows the use of non disk
 
2137
    based read write transports.
 
2138
 
 
2139
    If an explicit class is provided for readonly access, that server and the 
 
2140
    readwrite one must both define get_url() as resolving to os.getcwd().
 
2141
    """
 
2142
 
 
2143
    def get_vfs_only_server(self):
 
2144
        """See TestCaseWithMemoryTransport.
 
2145
 
 
2146
        This is useful for some tests with specific servers that need
 
2147
        diagnostics.
 
2148
        """
 
2149
        if self.__vfs_server is None:
 
2150
            self.__vfs_server = self.vfs_transport_factory()
 
2151
            self.__vfs_server.setUp()
 
2152
            self.addCleanup(self.__vfs_server.tearDown)
 
2153
        return self.__vfs_server
 
2154
 
 
2155
    def make_branch_and_tree(self, relpath, format=None):
 
2156
        """Create a branch on the transport and a tree locally.
 
2157
 
 
2158
        If the transport is not a LocalTransport, the Tree can't be created on
 
2159
        the transport.  In that case if the vfs_transport_factory is
 
2160
        LocalURLServer the working tree is created in the local
 
2161
        directory backing the transport, and the returned tree's branch and
 
2162
        repository will also be accessed locally. Otherwise a lightweight
 
2163
        checkout is created and returned.
 
2164
 
 
2165
        :param format: The BzrDirFormat.
 
2166
        :returns: the WorkingTree.
 
2167
        """
 
2168
        # TODO: always use the local disk path for the working tree,
 
2169
        # this obviously requires a format that supports branch references
 
2170
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
 
2171
        # RBC 20060208
 
2172
        b = self.make_branch(relpath, format=format)
 
2173
        try:
 
2174
            return b.bzrdir.create_workingtree()
 
2175
        except errors.NotLocalUrl:
 
2176
            # We can only make working trees locally at the moment.  If the
 
2177
            # transport can't support them, then we keep the non-disk-backed
 
2178
            # branch and create a local checkout.
 
2179
            if self.vfs_transport_factory is LocalURLServer:
 
2180
                # the branch is colocated on disk, we cannot create a checkout.
 
2181
                # hopefully callers will expect this.
 
2182
                local_controldir= bzrdir.BzrDir.open(self.get_vfs_only_url(relpath))
 
2183
                return local_controldir.create_workingtree()
 
2184
            else:
 
2185
                return b.create_checkout(relpath, lightweight=True)
 
2186
 
 
2187
    def assertIsDirectory(self, relpath, transport):
 
2188
        """Assert that relpath within transport is a directory.
 
2189
 
 
2190
        This may not be possible on all transports; in that case it propagates
 
2191
        a TransportNotPossible.
 
2192
        """
 
2193
        try:
 
2194
            mode = transport.stat(relpath).st_mode
 
2195
        except errors.NoSuchFile:
 
2196
            self.fail("path %s is not a directory; no such file"
 
2197
                      % (relpath))
 
2198
        if not stat.S_ISDIR(mode):
 
2199
            self.fail("path %s is not a directory; has mode %#o"
 
2200
                      % (relpath, mode))
 
2201
 
 
2202
    def assertTreesEqual(self, left, right):
 
2203
        """Check that left and right have the same content and properties."""
 
2204
        # we use a tree delta to check for equality of the content, and we
 
2205
        # manually check for equality of other things such as the parents list.
 
2206
        self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
 
2207
        differences = left.changes_from(right)
 
2208
        self.assertFalse(differences.has_changed(),
 
2209
            "Trees %r and %r are different: %r" % (left, right, differences))
 
2210
 
 
2211
    def setUp(self):
 
2212
        super(TestCaseWithTransport, self).setUp()
 
2213
        self.__vfs_server = None
 
2214
 
 
2215
 
 
2216
class ChrootedTestCase(TestCaseWithTransport):
 
2217
    """A support class that provides readonly urls outside the local namespace.
 
2218
 
 
2219
    This is done by checking if self.transport_server is a MemoryServer. if it
 
2220
    is then we are chrooted already, if it is not then an HttpServer is used
 
2221
    for readonly urls.
 
2222
 
 
2223
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
 
2224
                       be used without needed to redo it when a different 
 
2225
                       subclass is in use ?
 
2226
    """
 
2227
 
 
2228
    def setUp(self):
 
2229
        super(ChrootedTestCase, self).setUp()
 
2230
        if not self.vfs_transport_factory == MemoryServer:
 
2231
            self.transport_readonly_server = HttpServer
 
2232
 
 
2233
 
 
2234
def filter_suite_by_re(suite, pattern, exclude_pattern=None,
 
2235
                       random_order=False):
 
2236
    """Create a test suite by filtering another one.
 
2237
    
 
2238
    :param suite:           the source suite
 
2239
    :param pattern:         pattern that names must match
 
2240
    :param exclude_pattern: pattern that names must not match, if any
 
2241
    :param random_order:    if True, tests in the new suite will be put in
 
2242
                            random order
 
2243
    :returns: the newly created suite
 
2244
    """ 
 
2245
    return sort_suite_by_re(suite, pattern, exclude_pattern,
 
2246
        random_order, False)
 
2247
 
 
2248
 
 
2249
def sort_suite_by_re(suite, pattern, exclude_pattern=None,
 
2250
                     random_order=False, append_rest=True):
 
2251
    """Create a test suite by sorting another one.
 
2252
    
 
2253
    :param suite:           the source suite
 
2254
    :param pattern:         pattern that names must match in order to go
 
2255
                            first in the new suite
 
2256
    :param exclude_pattern: pattern that names must not match, if any
 
2257
    :param random_order:    if True, tests in the new suite will be put in
 
2258
                            random order
 
2259
    :param append_rest:     if False, pattern is a strict filter and not
 
2260
                            just an ordering directive
 
2261
    :returns: the newly created suite
 
2262
    """ 
 
2263
    first = []
 
2264
    second = []
 
2265
    filter_re = re.compile(pattern)
 
2266
    if exclude_pattern is not None:
 
2267
        exclude_re = re.compile(exclude_pattern)
 
2268
    for test in iter_suite_tests(suite):
 
2269
        test_id = test.id()
 
2270
        if exclude_pattern is None or not exclude_re.search(test_id):
 
2271
            if filter_re.search(test_id):
 
2272
                first.append(test)
 
2273
            elif append_rest:
 
2274
                second.append(test)
 
2275
    if random_order:
 
2276
        random.shuffle(first)
 
2277
        random.shuffle(second)
 
2278
    return TestUtil.TestSuite(first + second)
 
2279
 
 
2280
 
 
2281
def run_suite(suite, name='test', verbose=False, pattern=".*",
 
2282
              stop_on_failure=False,
 
2283
              transport=None, lsprof_timed=None, bench_history=None,
 
2284
              matching_tests_first=None,
 
2285
              list_only=False,
 
2286
              random_seed=None,
 
2287
              exclude_pattern=None,
 
2288
              strict=False,
 
2289
              ):
 
2290
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
 
2291
    if verbose:
 
2292
        verbosity = 2
 
2293
    else:
 
2294
        verbosity = 1
 
2295
    runner = TextTestRunner(stream=sys.stdout,
 
2296
                            descriptions=0,
 
2297
                            verbosity=verbosity,
 
2298
                            bench_history=bench_history,
 
2299
                            list_only=list_only,
 
2300
                            )
 
2301
    runner.stop_on_failure=stop_on_failure
 
2302
    # Initialise the random number generator and display the seed used.
 
2303
    # We convert the seed to a long to make it reuseable across invocations.
 
2304
    random_order = False
 
2305
    if random_seed is not None:
 
2306
        random_order = True
 
2307
        if random_seed == "now":
 
2308
            random_seed = long(time.time())
 
2309
        else:
 
2310
            # Convert the seed to a long if we can
 
2311
            try:
 
2312
                random_seed = long(random_seed)
 
2313
            except:
 
2314
                pass
 
2315
        runner.stream.writeln("Randomizing test order using seed %s\n" %
 
2316
            (random_seed))
 
2317
        random.seed(random_seed)
 
2318
    # Customise the list of tests if requested
 
2319
    if pattern != '.*' or exclude_pattern is not None or random_order:
 
2320
        if matching_tests_first:
 
2321
            suite = sort_suite_by_re(suite, pattern, exclude_pattern,
 
2322
                random_order)
 
2323
        else:
 
2324
            suite = filter_suite_by_re(suite, pattern, exclude_pattern,
 
2325
                random_order)
 
2326
    result = runner.run(suite)
 
2327
 
 
2328
    if strict:
 
2329
        return result.wasStrictlySuccessful()
 
2330
 
 
2331
    return result.wasSuccessful()
 
2332
 
 
2333
 
 
2334
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
 
2335
             transport=None,
 
2336
             test_suite_factory=None,
 
2337
             lsprof_timed=None,
 
2338
             bench_history=None,
 
2339
             matching_tests_first=None,
 
2340
             list_only=False,
 
2341
             random_seed=None,
 
2342
             exclude_pattern=None,
 
2343
             strict=False,
 
2344
             ):
 
2345
    """Run the whole test suite under the enhanced runner"""
 
2346
    # XXX: Very ugly way to do this...
 
2347
    # Disable warning about old formats because we don't want it to disturb
 
2348
    # any blackbox tests.
 
2349
    from bzrlib import repository
 
2350
    repository._deprecation_warning_done = True
 
2351
 
 
2352
    global default_transport
 
2353
    if transport is None:
 
2354
        transport = default_transport
 
2355
    old_transport = default_transport
 
2356
    default_transport = transport
 
2357
    try:
 
2358
        if test_suite_factory is None:
 
2359
            suite = test_suite()
 
2360
        else:
 
2361
            suite = test_suite_factory()
 
2362
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
 
2363
                     stop_on_failure=stop_on_failure,
 
2364
                     transport=transport,
 
2365
                     lsprof_timed=lsprof_timed,
 
2366
                     bench_history=bench_history,
 
2367
                     matching_tests_first=matching_tests_first,
 
2368
                     list_only=list_only,
 
2369
                     random_seed=random_seed,
 
2370
                     exclude_pattern=exclude_pattern,
 
2371
                     strict=strict)
 
2372
    finally:
 
2373
        default_transport = old_transport
 
2374
 
 
2375
 
 
2376
def test_suite():
 
2377
    """Build and return TestSuite for the whole of bzrlib.
 
2378
    
 
2379
    This function can be replaced if you need to change the default test
 
2380
    suite on a global basis, but it is not encouraged.
 
2381
    """
 
2382
    testmod_names = [
 
2383
                   'bzrlib.util.tests.test_bencode',
 
2384
                   'bzrlib.tests.test__dirstate_helpers',
 
2385
                   'bzrlib.tests.test_ancestry',
 
2386
                   'bzrlib.tests.test_annotate',
 
2387
                   'bzrlib.tests.test_api',
 
2388
                   'bzrlib.tests.test_atomicfile',
 
2389
                   'bzrlib.tests.test_bad_files',
 
2390
                   'bzrlib.tests.test_bisect_multi',
 
2391
                   'bzrlib.tests.test_branch',
 
2392
                   'bzrlib.tests.test_branchbuilder',
 
2393
                   'bzrlib.tests.test_bugtracker',
 
2394
                   'bzrlib.tests.test_bundle',
 
2395
                   'bzrlib.tests.test_bzrdir',
 
2396
                   'bzrlib.tests.test_cache_utf8',
 
2397
                   'bzrlib.tests.test_commands',
 
2398
                   'bzrlib.tests.test_commit',
 
2399
                   'bzrlib.tests.test_commit_merge',
 
2400
                   'bzrlib.tests.test_config',
 
2401
                   'bzrlib.tests.test_conflicts',
 
2402
                   'bzrlib.tests.test_counted_lock',
 
2403
                   'bzrlib.tests.test_decorators',
 
2404
                   'bzrlib.tests.test_delta',
 
2405
                   'bzrlib.tests.test_deprecated_graph',
 
2406
                   'bzrlib.tests.test_diff',
 
2407
                   'bzrlib.tests.test_dirstate',
 
2408
                   'bzrlib.tests.test_email_message',
 
2409
                   'bzrlib.tests.test_errors',
 
2410
                   'bzrlib.tests.test_escaped_store',
 
2411
                   'bzrlib.tests.test_extract',
 
2412
                   'bzrlib.tests.test_fetch',
 
2413
                   'bzrlib.tests.test_ftp_transport',
 
2414
                   'bzrlib.tests.test_generate_docs',
 
2415
                   'bzrlib.tests.test_generate_ids',
 
2416
                   'bzrlib.tests.test_globbing',
 
2417
                   'bzrlib.tests.test_gpg',
 
2418
                   'bzrlib.tests.test_graph',
 
2419
                   'bzrlib.tests.test_hashcache',
 
2420
                   'bzrlib.tests.test_help',
 
2421
                   'bzrlib.tests.test_hooks',
 
2422
                   'bzrlib.tests.test_http',
 
2423
                   'bzrlib.tests.test_http_response',
 
2424
                   'bzrlib.tests.test_https_ca_bundle',
 
2425
                   'bzrlib.tests.test_identitymap',
 
2426
                   'bzrlib.tests.test_ignores',
 
2427
                   'bzrlib.tests.test_index',
 
2428
                   'bzrlib.tests.test_info',
 
2429
                   'bzrlib.tests.test_inv',
 
2430
                   'bzrlib.tests.test_knit',
 
2431
                   'bzrlib.tests.test_lazy_import',
 
2432
                   'bzrlib.tests.test_lazy_regex',
 
2433
                   'bzrlib.tests.test_lockdir',
 
2434
                   'bzrlib.tests.test_lockable_files',
 
2435
                   'bzrlib.tests.test_log',
 
2436
                   'bzrlib.tests.test_lsprof',
 
2437
                   'bzrlib.tests.test_lru_cache',
 
2438
                   'bzrlib.tests.test_mail_client',
 
2439
                   'bzrlib.tests.test_memorytree',
 
2440
                   'bzrlib.tests.test_merge',
 
2441
                   'bzrlib.tests.test_merge3',
 
2442
                   'bzrlib.tests.test_merge_core',
 
2443
                   'bzrlib.tests.test_merge_directive',
 
2444
                   'bzrlib.tests.test_missing',
 
2445
                   'bzrlib.tests.test_msgeditor',
 
2446
                   'bzrlib.tests.test_multiparent',
 
2447
                   'bzrlib.tests.test_nonascii',
 
2448
                   'bzrlib.tests.test_options',
 
2449
                   'bzrlib.tests.test_osutils',
 
2450
                   'bzrlib.tests.test_osutils_encodings',
 
2451
                   'bzrlib.tests.test_pack',
 
2452
                   'bzrlib.tests.test_patch',
 
2453
                   'bzrlib.tests.test_patches',
 
2454
                   'bzrlib.tests.test_permissions',
 
2455
                   'bzrlib.tests.test_plugins',
 
2456
                   'bzrlib.tests.test_progress',
 
2457
                   'bzrlib.tests.test_reconfigure',
 
2458
                   'bzrlib.tests.test_reconcile',
 
2459
                   'bzrlib.tests.test_registry',
 
2460
                   'bzrlib.tests.test_remote',
 
2461
                   'bzrlib.tests.test_repository',
 
2462
                   'bzrlib.tests.test_revert',
 
2463
                   'bzrlib.tests.test_revision',
 
2464
                   'bzrlib.tests.test_revisionnamespaces',
 
2465
                   'bzrlib.tests.test_revisiontree',
 
2466
                   'bzrlib.tests.test_rio',
 
2467
                   'bzrlib.tests.test_sampler',
 
2468
                   'bzrlib.tests.test_selftest',
 
2469
                   'bzrlib.tests.test_setup',
 
2470
                   'bzrlib.tests.test_sftp_transport',
 
2471
                   'bzrlib.tests.test_smart',
 
2472
                   'bzrlib.tests.test_smart_add',
 
2473
                   'bzrlib.tests.test_smart_transport',
 
2474
                   'bzrlib.tests.test_smtp_connection',
 
2475
                   'bzrlib.tests.test_source',
 
2476
                   'bzrlib.tests.test_ssh_transport',
 
2477
                   'bzrlib.tests.test_status',
 
2478
                   'bzrlib.tests.test_store',
 
2479
                   'bzrlib.tests.test_strace',
 
2480
                   'bzrlib.tests.test_subsume',
 
2481
                   'bzrlib.tests.test_switch',
 
2482
                   'bzrlib.tests.test_symbol_versioning',
 
2483
                   'bzrlib.tests.test_tag',
 
2484
                   'bzrlib.tests.test_testament',
 
2485
                   'bzrlib.tests.test_textfile',
 
2486
                   'bzrlib.tests.test_textmerge',
 
2487
                   'bzrlib.tests.test_timestamp',
 
2488
                   'bzrlib.tests.test_trace',
 
2489
                   'bzrlib.tests.test_transactions',
 
2490
                   'bzrlib.tests.test_transform',
 
2491
                   'bzrlib.tests.test_transport',
 
2492
                   'bzrlib.tests.test_tree',
 
2493
                   'bzrlib.tests.test_treebuilder',
 
2494
                   'bzrlib.tests.test_tsort',
 
2495
                   'bzrlib.tests.test_tuned_gzip',
 
2496
                   'bzrlib.tests.test_ui',
 
2497
                   'bzrlib.tests.test_upgrade',
 
2498
                   'bzrlib.tests.test_urlutils',
 
2499
                   'bzrlib.tests.test_versionedfile',
 
2500
                   'bzrlib.tests.test_version',
 
2501
                   'bzrlib.tests.test_version_info',
 
2502
                   'bzrlib.tests.test_weave',
 
2503
                   'bzrlib.tests.test_whitebox',
 
2504
                   'bzrlib.tests.test_win32utils',
 
2505
                   'bzrlib.tests.test_workingtree',
 
2506
                   'bzrlib.tests.test_workingtree_4',
 
2507
                   'bzrlib.tests.test_wsgi',
 
2508
                   'bzrlib.tests.test_xml',
 
2509
                   ]
 
2510
    test_transport_implementations = [
 
2511
        'bzrlib.tests.test_transport_implementations',
 
2512
        'bzrlib.tests.test_read_bundle',
 
2513
        ]
 
2514
    suite = TestUtil.TestSuite()
 
2515
    loader = TestUtil.TestLoader()
 
2516
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
2517
    from bzrlib.tests.test_transport_implementations import TransportTestProviderAdapter
 
2518
    adapter = TransportTestProviderAdapter()
 
2519
    adapt_modules(test_transport_implementations, adapter, loader, suite)
 
2520
    adapt_tests(
 
2521
        ["bzrlib.tests.test_msgeditor.MsgEditorTest."
 
2522
         "test__create_temp_file_with_commit_template_in_unicode_dir"],
 
2523
        EncodingTestAdapter(), loader, suite)
 
2524
    for package in packages_to_test():
 
2525
        suite.addTest(package.test_suite())
 
2526
    for m in MODULES_TO_TEST:
 
2527
        suite.addTest(loader.loadTestsFromModule(m))
 
2528
    for m in MODULES_TO_DOCTEST:
 
2529
        try:
 
2530
            suite.addTest(doctest.DocTestSuite(m))
 
2531
        except ValueError, e:
 
2532
            print '**failed to get doctest for: %s\n%s' %(m,e)
 
2533
            raise
 
2534
    default_encoding = sys.getdefaultencoding()
 
2535
    for name, plugin in bzrlib.plugin.plugins().items():
 
2536
        try:
 
2537
            plugin_suite = plugin.test_suite()
 
2538
        except ImportError, e:
 
2539
            bzrlib.trace.warning(
 
2540
                'Unable to test plugin "%s": %s', name, e)
 
2541
        else:
 
2542
            if plugin_suite is not None:
 
2543
                suite.addTest(plugin_suite)
 
2544
        if default_encoding != sys.getdefaultencoding():
 
2545
            bzrlib.trace.warning(
 
2546
                'Plugin "%s" tried to reset default encoding to: %s', name,
 
2547
                sys.getdefaultencoding())
 
2548
            reload(sys)
 
2549
            sys.setdefaultencoding(default_encoding)
 
2550
    return suite
 
2551
 
 
2552
 
 
2553
def multiply_tests_from_modules(module_name_list, scenario_iter):
 
2554
    """Adapt all tests in some given modules to given scenarios.
 
2555
 
 
2556
    This is the recommended public interface for test parameterization.
 
2557
    Typically the test_suite() method for a per-implementation test
 
2558
    suite will call multiply_tests_from_modules and return the 
 
2559
    result.
 
2560
 
 
2561
    :param module_name_list: List of fully-qualified names of test
 
2562
        modules.
 
2563
    :param scenario_iter: Iterable of pairs of (scenario_name, 
 
2564
        scenario_param_dict).
 
2565
 
 
2566
    This returns a new TestSuite containing the cross product of
 
2567
    all the tests in all the modules, each repeated for each scenario.
 
2568
    Each test is adapted by adding the scenario name at the end 
 
2569
    of its name, and updating the test object's __dict__ with the
 
2570
    scenario_param_dict.
 
2571
 
 
2572
    >>> r = multiply_tests_from_modules(
 
2573
    ...     ['bzrlib.tests.test_sampler'],
 
2574
    ...     [('one', dict(param=1)), 
 
2575
    ...      ('two', dict(param=2))])
 
2576
    >>> tests = list(iter_suite_tests(r))
 
2577
    >>> len(tests)
 
2578
    2
 
2579
    >>> tests[0].id()
 
2580
    'bzrlib.tests.test_sampler.DemoTest.test_nothing(one)'
 
2581
    >>> tests[0].param
 
2582
    1
 
2583
    >>> tests[1].param
 
2584
    2
 
2585
    """
 
2586
    loader = TestLoader()
 
2587
    suite = TestSuite()
 
2588
    adapter = TestScenarioApplier()
 
2589
    adapter.scenarios = list(scenario_iter)
 
2590
    adapt_modules(module_name_list, adapter, loader, suite)
 
2591
    return suite
 
2592
 
 
2593
 
 
2594
def multiply_scenarios(scenarios_left, scenarios_right):
 
2595
    """Multiply two sets of scenarios.
 
2596
 
 
2597
    :returns: the cartesian product of the two sets of scenarios, that is
 
2598
        a scenario for every possible combination of a left scenario and a
 
2599
        right scenario.
 
2600
    """
 
2601
    return [
 
2602
        ('%s,%s' % (left_name, right_name),
 
2603
         dict(left_dict.items() + right_dict.items()))
 
2604
        for left_name, left_dict in scenarios_left
 
2605
        for right_name, right_dict in scenarios_right]
 
2606
 
 
2607
 
 
2608
 
 
2609
def adapt_modules(mods_list, adapter, loader, suite):
 
2610
    """Adapt the modules in mods_list using adapter and add to suite."""
 
2611
    for test in iter_suite_tests(loader.loadTestsFromModuleNames(mods_list)):
 
2612
        suite.addTests(adapter.adapt(test))
 
2613
 
 
2614
 
 
2615
def adapt_tests(tests_list, adapter, loader, suite):
 
2616
    """Adapt the tests in tests_list using adapter and add to suite."""
 
2617
    for test in tests_list:
 
2618
        suite.addTests(adapter.adapt(loader.loadTestsFromName(test)))
 
2619
 
 
2620
 
 
2621
def _rmtree_temp_dir(dirname):
 
2622
    # If LANG=C we probably have created some bogus paths
 
2623
    # which rmtree(unicode) will fail to delete
 
2624
    # so make sure we are using rmtree(str) to delete everything
 
2625
    # except on win32, where rmtree(str) will fail
 
2626
    # since it doesn't have the property of byte-stream paths
 
2627
    # (they are either ascii or mbcs)
 
2628
    if sys.platform == 'win32':
 
2629
        # make sure we are using the unicode win32 api
 
2630
        dirname = unicode(dirname)
 
2631
    else:
 
2632
        dirname = dirname.encode(sys.getfilesystemencoding())
 
2633
    try:
 
2634
        osutils.rmtree(dirname)
 
2635
    except OSError, e:
 
2636
        if sys.platform == 'win32' and e.errno == errno.EACCES:
 
2637
            sys.stderr.write(('Permission denied: '
 
2638
                                 'unable to remove testing dir '
 
2639
                                 '%s\n' % os.path.basename(dirname)))
 
2640
        else:
 
2641
            raise
 
2642
 
 
2643
 
 
2644
class Feature(object):
 
2645
    """An operating system Feature."""
 
2646
 
 
2647
    def __init__(self):
 
2648
        self._available = None
 
2649
 
 
2650
    def available(self):
 
2651
        """Is the feature available?
 
2652
 
 
2653
        :return: True if the feature is available.
 
2654
        """
 
2655
        if self._available is None:
 
2656
            self._available = self._probe()
 
2657
        return self._available
 
2658
 
 
2659
    def _probe(self):
 
2660
        """Implement this method in concrete features.
 
2661
 
 
2662
        :return: True if the feature is available.
 
2663
        """
 
2664
        raise NotImplementedError
 
2665
 
 
2666
    def __str__(self):
 
2667
        if getattr(self, 'feature_name', None):
 
2668
            return self.feature_name()
 
2669
        return self.__class__.__name__
 
2670
 
 
2671
 
 
2672
class _SymlinkFeature(Feature):
 
2673
 
 
2674
    def _probe(self):
 
2675
        return osutils.has_symlinks()
 
2676
 
 
2677
    def feature_name(self):
 
2678
        return 'symlinks'
 
2679
 
 
2680
SymlinkFeature = _SymlinkFeature()
 
2681
 
 
2682
 
 
2683
class _OsFifoFeature(Feature):
 
2684
 
 
2685
    def _probe(self):
 
2686
        return getattr(os, 'mkfifo', None)
 
2687
 
 
2688
    def feature_name(self):
 
2689
        return 'filesystem fifos'
 
2690
 
 
2691
OsFifoFeature = _OsFifoFeature()
 
2692
 
 
2693
 
 
2694
class TestScenarioApplier(object):
 
2695
    """A tool to apply scenarios to tests."""
 
2696
 
 
2697
    def adapt(self, test):
 
2698
        """Return a TestSuite containing a copy of test for each scenario."""
 
2699
        result = unittest.TestSuite()
 
2700
        for scenario in self.scenarios:
 
2701
            result.addTest(self.adapt_test_to_scenario(test, scenario))
 
2702
        return result
 
2703
 
 
2704
    def adapt_test_to_scenario(self, test, scenario):
 
2705
        """Copy test and apply scenario to it.
 
2706
 
 
2707
        :param test: A test to adapt.
 
2708
        :param scenario: A tuple describing the scenarion.
 
2709
            The first element of the tuple is the new test id.
 
2710
            The second element is a dict containing attributes to set on the
 
2711
            test.
 
2712
        :return: The adapted test.
 
2713
        """
 
2714
        from copy import deepcopy
 
2715
        new_test = deepcopy(test)
 
2716
        for name, value in scenario[1].items():
 
2717
            setattr(new_test, name, value)
 
2718
        new_id = "%s(%s)" % (new_test.id(), scenario[0])
 
2719
        new_test.id = lambda: new_id
 
2720
        return new_test
 
2721
 
 
2722
 
 
2723
def probe_unicode_in_user_encoding():
 
2724
    """Try to encode several unicode strings to use in unicode-aware tests.
 
2725
    Return first successfull match.
 
2726
 
 
2727
    :return:  (unicode value, encoded plain string value) or (None, None)
 
2728
    """
 
2729
    possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
 
2730
    for uni_val in possible_vals:
 
2731
        try:
 
2732
            str_val = uni_val.encode(bzrlib.user_encoding)
 
2733
        except UnicodeEncodeError:
 
2734
            # Try a different character
 
2735
            pass
 
2736
        else:
 
2737
            return uni_val, str_val
 
2738
    return None, None
 
2739
 
 
2740
 
 
2741
def probe_bad_non_ascii(encoding):
 
2742
    """Try to find [bad] character with code [128..255]
 
2743
    that cannot be decoded to unicode in some encoding.
 
2744
    Return None if all non-ascii characters is valid
 
2745
    for given encoding.
 
2746
    """
 
2747
    for i in xrange(128, 256):
 
2748
        char = chr(i)
 
2749
        try:
 
2750
            char.decode(encoding)
 
2751
        except UnicodeDecodeError:
 
2752
            return char
 
2753
    return None
 
2754
 
 
2755
 
 
2756
class _FTPServerFeature(Feature):
 
2757
    """Some tests want an FTP Server, check if one is available.
 
2758
 
 
2759
    Right now, the only way this is available is if 'medusa' is installed.
 
2760
    http://www.amk.ca/python/code/medusa.html
 
2761
    """
 
2762
 
 
2763
    def _probe(self):
 
2764
        try:
 
2765
            import bzrlib.tests.ftp_server
 
2766
            return True
 
2767
        except ImportError:
 
2768
            return False
 
2769
 
 
2770
    def feature_name(self):
 
2771
        return 'FTPServer'
 
2772
 
 
2773
FTPServerFeature = _FTPServerFeature()