/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: John Arbash Meinel
  • Date: 2009-10-12 18:10:24 UTC
  • mto: This revision was merged to the branch mainline in revision 4736.
  • Revision ID: john@arbash-meinel.com-20091012181024-q21zm9xpyf62ld7t
Add some tests that we *can* compare to strings, even if we don't care
what the result actually is.

Show diffs side-by-side

added added

removed removed

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