/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: Jelmer Vernooij
  • Date: 2009-04-07 20:31:41 UTC
  • mto: This revision was merged to the branch mainline in revision 4405.
  • Revision ID: jelmer@samba.org-20090407203141-yjjovfgbcslac0kg
Support cloning of branches with ghosts in the left hand side history.

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