/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: Jan Balster
  • Date: 2006-08-15 12:39:42 UTC
  • mfrom: (1923 +trunk)
  • mto: This revision was merged to the branch mainline in revision 1928.
  • Revision ID: jan@merlinux.de-20060815123942-22c388c6e9a8ac91
merge bzr.dev 1923

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 by Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
 
18
# TODO: Perhaps there should be an API to find out if bzr running under the
 
19
# test suite -- some plugins might want to avoid making intrusive changes if
 
20
# this is the case.  However, we want behaviour under to test to diverge as
 
21
# little as possible, so this should be used rarely if it's added at all.
 
22
# (Suggestion from j-a-meinel, 2005-11-24)
 
23
 
 
24
# NOTE: Some classes in here use camelCaseNaming() rather than
 
25
# underscore_naming().  That's for consistency with unittest; it's not the
 
26
# general style of bzrlib.  Please continue that consistency when adding e.g.
 
27
# new assertFoo() methods.
 
28
 
 
29
import codecs
 
30
from cStringIO import StringIO
 
31
import difflib
 
32
import doctest
 
33
import errno
 
34
import logging
 
35
import os
 
36
import re
 
37
import shlex
 
38
import stat
 
39
from subprocess import Popen, PIPE
 
40
import sys
 
41
import tempfile
 
42
import unittest
 
43
import time
 
44
 
 
45
 
 
46
import bzrlib.branch
 
47
import bzrlib.bzrdir as bzrdir
 
48
import bzrlib.commands
 
49
import bzrlib.bundle.serializer
 
50
import bzrlib.errors as errors
 
51
import bzrlib.inventory
 
52
import bzrlib.iterablefile
 
53
import bzrlib.lockdir
 
54
try:
 
55
    import bzrlib.lsprof
 
56
except ImportError:
 
57
    # lsprof not available
 
58
    pass
 
59
from bzrlib.merge import merge_inner
 
60
import bzrlib.merge3
 
61
import bzrlib.osutils
 
62
import bzrlib.osutils as osutils
 
63
import bzrlib.plugin
 
64
import bzrlib.progress as progress
 
65
from bzrlib.revision import common_ancestor
 
66
from bzrlib.revisionspec import RevisionSpec
 
67
import bzrlib.store
 
68
import bzrlib.trace
 
69
from bzrlib.transport import get_transport
 
70
import bzrlib.transport
 
71
from bzrlib.transport.local import LocalRelpathServer
 
72
from bzrlib.transport.readonly import ReadonlyServer
 
73
from bzrlib.trace import mutter
 
74
from bzrlib.tests import TestUtil
 
75
from bzrlib.tests.TestUtil import (
 
76
                          TestSuite,
 
77
                          TestLoader,
 
78
                          )
 
79
from bzrlib.tests.treeshape import build_tree_contents
 
80
import bzrlib.urlutils as urlutils
 
81
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
 
82
 
 
83
default_transport = LocalRelpathServer
 
84
 
 
85
MODULES_TO_TEST = []
 
86
MODULES_TO_DOCTEST = [
 
87
                      bzrlib.branch,
 
88
                      bzrlib.bundle.serializer,
 
89
                      bzrlib.commands,
 
90
                      bzrlib.errors,
 
91
                      bzrlib.inventory,
 
92
                      bzrlib.iterablefile,
 
93
                      bzrlib.lockdir,
 
94
                      bzrlib.merge3,
 
95
                      bzrlib.option,
 
96
                      bzrlib.osutils,
 
97
                      bzrlib.store
 
98
                      ]
 
99
 
 
100
 
 
101
def packages_to_test():
 
102
    """Return a list of packages to test.
 
103
 
 
104
    The packages are not globally imported so that import failures are
 
105
    triggered when running selftest, not when importing the command.
 
106
    """
 
107
    import bzrlib.doc
 
108
    import bzrlib.tests.blackbox
 
109
    import bzrlib.tests.branch_implementations
 
110
    import bzrlib.tests.bzrdir_implementations
 
111
    import bzrlib.tests.interrepository_implementations
 
112
    import bzrlib.tests.interversionedfile_implementations
 
113
    import bzrlib.tests.intertree_implementations
 
114
    import bzrlib.tests.repository_implementations
 
115
    import bzrlib.tests.revisionstore_implementations
 
116
    import bzrlib.tests.tree_implementations
 
117
    import bzrlib.tests.workingtree_implementations
 
118
    return [
 
119
            bzrlib.doc,
 
120
            bzrlib.tests.blackbox,
 
121
            bzrlib.tests.branch_implementations,
 
122
            bzrlib.tests.bzrdir_implementations,
 
123
            bzrlib.tests.interrepository_implementations,
 
124
            bzrlib.tests.interversionedfile_implementations,
 
125
            bzrlib.tests.intertree_implementations,
 
126
            bzrlib.tests.repository_implementations,
 
127
            bzrlib.tests.revisionstore_implementations,
 
128
            bzrlib.tests.tree_implementations,
 
129
            bzrlib.tests.workingtree_implementations,
 
130
            ]
 
131
 
 
132
 
 
133
class _MyResult(unittest._TextTestResult):
 
134
    """Custom TestResult.
 
135
 
 
136
    Shows output in a different format, including displaying runtime for tests.
 
137
    """
 
138
    stop_early = False
 
139
    
 
140
    def __init__(self, stream, descriptions, verbosity, pb=None,
 
141
                 bench_history=None):
 
142
        unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
 
143
        self.pb = pb
 
144
        if bench_history is not None:
 
145
            #XXX is there a simpler way to get the revison id?
 
146
            branch = bzrlib.branch.Branch.open_containing('.')[0]
 
147
            revision_id = RevisionSpec(branch.revno()).in_history(branch).rev_id
 
148
            bench_history.write("--date %s %s\n" % (time.time(), revision_id))
 
149
        self._bench_history = bench_history
 
150
    
 
151
    def extractBenchmarkTime(self, testCase):
 
152
        """Add a benchmark time for the current test case."""
 
153
        self._benchmarkTime = getattr(testCase, "_benchtime", None)
 
154
    
 
155
    def _elapsedTestTimeString(self):
 
156
        """Return a time string for the overall time the current test has taken."""
 
157
        return self._formatTime(time.time() - self._start_time)
 
158
 
 
159
    def _testTimeString(self):
 
160
        if self._benchmarkTime is not None:
 
161
            return "%s/%s" % (
 
162
                self._formatTime(self._benchmarkTime),
 
163
                self._elapsedTestTimeString())
 
164
        else:
 
165
            return "      %s" % self._elapsedTestTimeString()
 
166
 
 
167
    def _formatTime(self, seconds):
 
168
        """Format seconds as milliseconds with leading spaces."""
 
169
        return "%5dms" % (1000 * seconds)
 
170
 
 
171
    def _ellipsise_unimportant_words(self, a_string, final_width,
 
172
                                   keep_start=False):
 
173
        """Add ellipses (sp?) for overly long strings.
 
174
        
 
175
        :param keep_start: If true preserve the start of a_string rather
 
176
                           than the end of it.
 
177
        """
 
178
        if keep_start:
 
179
            if len(a_string) > final_width:
 
180
                result = a_string[:final_width-3] + '...'
 
181
            else:
 
182
                result = a_string
 
183
        else:
 
184
            if len(a_string) > final_width:
 
185
                result = '...' + a_string[3-final_width:]
 
186
            else:
 
187
                result = a_string
 
188
        return result.ljust(final_width)
 
189
 
 
190
    def startTest(self, test):
 
191
        unittest.TestResult.startTest(self, test)
 
192
        # In a short description, the important words are in
 
193
        # the beginning, but in an id, the important words are
 
194
        # at the end
 
195
        SHOW_DESCRIPTIONS = False
 
196
 
 
197
        if not self.showAll and self.dots and self.pb is not None:
 
198
            final_width = 13
 
199
        else:
 
200
            final_width = osutils.terminal_width()
 
201
            final_width = final_width - 15 - 8
 
202
        what = None
 
203
        if SHOW_DESCRIPTIONS:
 
204
            what = test.shortDescription()
 
205
            if what:
 
206
                what = self._ellipsise_unimportant_words(what, final_width, keep_start=True)
 
207
        if what is None:
 
208
            what = test.id()
 
209
            if what.startswith('bzrlib.tests.'):
 
210
                what = what[13:]
 
211
            what = self._ellipsise_unimportant_words(what, final_width)
 
212
        if self.showAll:
 
213
            self.stream.write(what)
 
214
        elif self.dots and self.pb is not None:
 
215
            self.pb.update(what, self.testsRun - 1, None)
 
216
        self.stream.flush()
 
217
        self._recordTestStartTime()
 
218
 
 
219
    def _recordTestStartTime(self):
 
220
        """Record that a test has started."""
 
221
        self._start_time = time.time()
 
222
 
 
223
    def addError(self, test, err):
 
224
        if isinstance(err[1], TestSkipped):
 
225
            return self.addSkipped(test, err)    
 
226
        unittest.TestResult.addError(self, test, err)
 
227
        self.extractBenchmarkTime(test)
 
228
        if self.showAll:
 
229
            self.stream.writeln("ERROR %s" % self._testTimeString())
 
230
        elif self.dots and self.pb is None:
 
231
            self.stream.write('E')
 
232
        elif self.dots:
 
233
            self.pb.update(self._ellipsise_unimportant_words('ERROR', 13), self.testsRun, None)
 
234
            self.pb.note(self._ellipsise_unimportant_words(
 
235
                            test.id() + ': ERROR',
 
236
                            osutils.terminal_width()))
 
237
        self.stream.flush()
 
238
        if self.stop_early:
 
239
            self.stop()
 
240
 
 
241
    def addFailure(self, test, err):
 
242
        unittest.TestResult.addFailure(self, test, err)
 
243
        self.extractBenchmarkTime(test)
 
244
        if self.showAll:
 
245
            self.stream.writeln(" FAIL %s" % self._testTimeString())
 
246
        elif self.dots and self.pb is None:
 
247
            self.stream.write('F')
 
248
        elif self.dots:
 
249
            self.pb.update(self._ellipsise_unimportant_words('FAIL', 13), self.testsRun, None)
 
250
            self.pb.note(self._ellipsise_unimportant_words(
 
251
                            test.id() + ': FAIL',
 
252
                            osutils.terminal_width()))
 
253
        self.stream.flush()
 
254
        if self.stop_early:
 
255
            self.stop()
 
256
 
 
257
    def addSuccess(self, test):
 
258
        self.extractBenchmarkTime(test)
 
259
        if self._bench_history is not None:
 
260
            if self._benchmarkTime is not None:
 
261
                self._bench_history.write("%s %s\n" % (
 
262
                    self._formatTime(self._benchmarkTime),
 
263
                    test.id()))
 
264
        if self.showAll:
 
265
            self.stream.writeln('   OK %s' % self._testTimeString())
 
266
            for bench_called, stats in getattr(test, '_benchcalls', []):
 
267
                self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
 
268
                stats.pprint(file=self.stream)
 
269
        elif self.dots and self.pb is None:
 
270
            self.stream.write('~')
 
271
        elif self.dots:
 
272
            self.pb.update(self._ellipsise_unimportant_words('OK', 13), self.testsRun, None)
 
273
        self.stream.flush()
 
274
        unittest.TestResult.addSuccess(self, test)
 
275
 
 
276
    def addSkipped(self, test, skip_excinfo):
 
277
        self.extractBenchmarkTime(test)
 
278
        if self.showAll:
 
279
            print >>self.stream, ' SKIP %s' % self._testTimeString()
 
280
            print >>self.stream, '     %s' % skip_excinfo[1]
 
281
        elif self.dots and self.pb is None:
 
282
            self.stream.write('S')
 
283
        elif self.dots:
 
284
            self.pb.update(self._ellipsise_unimportant_words('SKIP', 13), self.testsRun, None)
 
285
        self.stream.flush()
 
286
        # seems best to treat this as success from point-of-view of unittest
 
287
        # -- it actually does nothing so it barely matters :)
 
288
        try:
 
289
            test.tearDown()
 
290
        except KeyboardInterrupt:
 
291
            raise
 
292
        except:
 
293
            self.addError(test, test.__exc_info())
 
294
        else:
 
295
            unittest.TestResult.addSuccess(self, test)
 
296
 
 
297
    def printErrorList(self, flavour, errors):
 
298
        for test, err in errors:
 
299
            self.stream.writeln(self.separator1)
 
300
            self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
 
301
            if getattr(test, '_get_log', None) is not None:
 
302
                print >>self.stream
 
303
                print >>self.stream, \
 
304
                        ('vvvv[log from %s]' % test.id()).ljust(78,'-')
 
305
                print >>self.stream, test._get_log()
 
306
                print >>self.stream, \
 
307
                        ('^^^^[log from %s]' % test.id()).ljust(78,'-')
 
308
            self.stream.writeln(self.separator2)
 
309
            self.stream.writeln("%s" % err)
 
310
 
 
311
 
 
312
class TextTestRunner(object):
 
313
    stop_on_failure = False
 
314
 
 
315
    def __init__(self,
 
316
                 stream=sys.stderr,
 
317
                 descriptions=0,
 
318
                 verbosity=1,
 
319
                 keep_output=False,
 
320
                 pb=None,
 
321
                 bench_history=None):
 
322
        self.stream = unittest._WritelnDecorator(stream)
 
323
        self.descriptions = descriptions
 
324
        self.verbosity = verbosity
 
325
        self.keep_output = keep_output
 
326
        self.pb = pb
 
327
        self._bench_history = bench_history
 
328
 
 
329
    def _makeResult(self):
 
330
        result = _MyResult(self.stream,
 
331
                           self.descriptions,
 
332
                           self.verbosity,
 
333
                           pb=self.pb,
 
334
                           bench_history=self._bench_history)
 
335
        result.stop_early = self.stop_on_failure
 
336
        return result
 
337
 
 
338
    def run(self, test):
 
339
        "Run the given test case or test suite."
 
340
        result = self._makeResult()
 
341
        startTime = time.time()
 
342
        if self.pb is not None:
 
343
            self.pb.update('Running tests', 0, test.countTestCases())
 
344
        test.run(result)
 
345
        stopTime = time.time()
 
346
        timeTaken = stopTime - startTime
 
347
        result.printErrors()
 
348
        self.stream.writeln(result.separator2)
 
349
        run = result.testsRun
 
350
        self.stream.writeln("Ran %d test%s in %.3fs" %
 
351
                            (run, run != 1 and "s" or "", timeTaken))
 
352
        self.stream.writeln()
 
353
        if not result.wasSuccessful():
 
354
            self.stream.write("FAILED (")
 
355
            failed, errored = map(len, (result.failures, result.errors))
 
356
            if failed:
 
357
                self.stream.write("failures=%d" % failed)
 
358
            if errored:
 
359
                if failed: self.stream.write(", ")
 
360
                self.stream.write("errors=%d" % errored)
 
361
            self.stream.writeln(")")
 
362
        else:
 
363
            self.stream.writeln("OK")
 
364
        if self.pb is not None:
 
365
            self.pb.update('Cleaning up', 0, 1)
 
366
        # This is still a little bogus, 
 
367
        # but only a little. Folk not using our testrunner will
 
368
        # have to delete their temp directories themselves.
 
369
        test_root = TestCaseInTempDir.TEST_ROOT
 
370
        if result.wasSuccessful() or not self.keep_output:
 
371
            if test_root is not None:
 
372
                # If LANG=C we probably have created some bogus paths
 
373
                # which rmtree(unicode) will fail to delete
 
374
                # so make sure we are using rmtree(str) to delete everything
 
375
                # except on win32, where rmtree(str) will fail
 
376
                # since it doesn't have the property of byte-stream paths
 
377
                # (they are either ascii or mbcs)
 
378
                if sys.platform == 'win32':
 
379
                    # make sure we are using the unicode win32 api
 
380
                    test_root = unicode(test_root)
 
381
                else:
 
382
                    test_root = test_root.encode(
 
383
                        sys.getfilesystemencoding())
 
384
                osutils.rmtree(test_root)
 
385
        else:
 
386
            if self.pb is not None:
 
387
                self.pb.note("Failed tests working directories are in '%s'\n",
 
388
                             test_root)
 
389
            else:
 
390
                self.stream.writeln(
 
391
                    "Failed tests working directories are in '%s'\n" %
 
392
                    test_root)
 
393
        TestCaseInTempDir.TEST_ROOT = None
 
394
        if self.pb is not None:
 
395
            self.pb.clear()
 
396
        return result
 
397
 
 
398
 
 
399
def iter_suite_tests(suite):
 
400
    """Return all tests in a suite, recursing through nested suites"""
 
401
    for item in suite._tests:
 
402
        if isinstance(item, unittest.TestCase):
 
403
            yield item
 
404
        elif isinstance(item, unittest.TestSuite):
 
405
            for r in iter_suite_tests(item):
 
406
                yield r
 
407
        else:
 
408
            raise Exception('unknown object %r inside test suite %r'
 
409
                            % (item, suite))
 
410
 
 
411
 
 
412
class TestSkipped(Exception):
 
413
    """Indicates that a test was intentionally skipped, rather than failing."""
 
414
    # XXX: Not used yet
 
415
 
 
416
 
 
417
class CommandFailed(Exception):
 
418
    pass
 
419
 
 
420
 
 
421
class StringIOWrapper(object):
 
422
    """A wrapper around cStringIO which just adds an encoding attribute.
 
423
    
 
424
    Internally we can check sys.stdout to see what the output encoding
 
425
    should be. However, cStringIO has no encoding attribute that we can
 
426
    set. So we wrap it instead.
 
427
    """
 
428
    encoding='ascii'
 
429
    _cstring = None
 
430
 
 
431
    def __init__(self, s=None):
 
432
        if s is not None:
 
433
            self.__dict__['_cstring'] = StringIO(s)
 
434
        else:
 
435
            self.__dict__['_cstring'] = StringIO()
 
436
 
 
437
    def __getattr__(self, name, getattr=getattr):
 
438
        return getattr(self.__dict__['_cstring'], name)
 
439
 
 
440
    def __setattr__(self, name, val):
 
441
        if name == 'encoding':
 
442
            self.__dict__['encoding'] = val
 
443
        else:
 
444
            return setattr(self._cstring, name, val)
 
445
 
 
446
 
 
447
class TestCase(unittest.TestCase):
 
448
    """Base class for bzr unit tests.
 
449
    
 
450
    Tests that need access to disk resources should subclass 
 
451
    TestCaseInTempDir not TestCase.
 
452
 
 
453
    Error and debug log messages are redirected from their usual
 
454
    location into a temporary file, the contents of which can be
 
455
    retrieved by _get_log().  We use a real OS file, not an in-memory object,
 
456
    so that it can also capture file IO.  When the test completes this file
 
457
    is read into memory and removed from disk.
 
458
       
 
459
    There are also convenience functions to invoke bzr's command-line
 
460
    routine, and to build and check bzr trees.
 
461
   
 
462
    In addition to the usual method of overriding tearDown(), this class also
 
463
    allows subclasses to register functions into the _cleanups list, which is
 
464
    run in order as the object is torn down.  It's less likely this will be
 
465
    accidentally overlooked.
 
466
    """
 
467
 
 
468
    _log_file_name = None
 
469
    _log_contents = ''
 
470
    # record lsprof data when performing benchmark calls.
 
471
    _gather_lsprof_in_benchmarks = False
 
472
 
 
473
    def __init__(self, methodName='testMethod'):
 
474
        super(TestCase, self).__init__(methodName)
 
475
        self._cleanups = []
 
476
 
 
477
    def setUp(self):
 
478
        unittest.TestCase.setUp(self)
 
479
        self._cleanEnvironment()
 
480
        bzrlib.trace.disable_default_logging()
 
481
        self._startLogFile()
 
482
        self._benchcalls = []
 
483
        self._benchtime = None
 
484
 
 
485
    def _ndiff_strings(self, a, b):
 
486
        """Return ndiff between two strings containing lines.
 
487
        
 
488
        A trailing newline is added if missing to make the strings
 
489
        print properly."""
 
490
        if b and b[-1] != '\n':
 
491
            b += '\n'
 
492
        if a and a[-1] != '\n':
 
493
            a += '\n'
 
494
        difflines = difflib.ndiff(a.splitlines(True),
 
495
                                  b.splitlines(True),
 
496
                                  linejunk=lambda x: False,
 
497
                                  charjunk=lambda x: False)
 
498
        return ''.join(difflines)
 
499
 
 
500
    def assertEqualDiff(self, a, b, message=None):
 
501
        """Assert two texts are equal, if not raise an exception.
 
502
        
 
503
        This is intended for use with multi-line strings where it can 
 
504
        be hard to find the differences by eye.
 
505
        """
 
506
        # TODO: perhaps override assertEquals to call this for strings?
 
507
        if a == b:
 
508
            return
 
509
        if message is None:
 
510
            message = "texts not equal:\n"
 
511
        raise AssertionError(message + 
 
512
                             self._ndiff_strings(a, b))      
 
513
        
 
514
    def assertEqualMode(self, mode, mode_test):
 
515
        self.assertEqual(mode, mode_test,
 
516
                         'mode mismatch %o != %o' % (mode, mode_test))
 
517
 
 
518
    def assertStartsWith(self, s, prefix):
 
519
        if not s.startswith(prefix):
 
520
            raise AssertionError('string %r does not start with %r' % (s, prefix))
 
521
 
 
522
    def assertEndsWith(self, s, suffix):
 
523
        """Asserts that s ends with suffix."""
 
524
        if not s.endswith(suffix):
 
525
            raise AssertionError('string %r does not end with %r' % (s, suffix))
 
526
 
 
527
    def assertContainsRe(self, haystack, needle_re):
 
528
        """Assert that a contains something matching a regular expression."""
 
529
        if not re.search(needle_re, haystack):
 
530
            raise AssertionError('pattern "%s" not found in "%s"'
 
531
                    % (needle_re, haystack))
 
532
 
 
533
    def assertNotContainsRe(self, haystack, needle_re):
 
534
        """Assert that a does not match a regular expression"""
 
535
        if re.search(needle_re, haystack):
 
536
            raise AssertionError('pattern "%s" found in "%s"'
 
537
                    % (needle_re, haystack))
 
538
 
 
539
    def assertSubset(self, sublist, superlist):
 
540
        """Assert that every entry in sublist is present in superlist."""
 
541
        missing = []
 
542
        for entry in sublist:
 
543
            if entry not in superlist:
 
544
                missing.append(entry)
 
545
        if len(missing) > 0:
 
546
            raise AssertionError("value(s) %r not present in container %r" % 
 
547
                                 (missing, superlist))
 
548
 
 
549
    def assertIs(self, left, right):
 
550
        if not (left is right):
 
551
            raise AssertionError("%r is not %r." % (left, right))
 
552
 
 
553
    def assertTransportMode(self, transport, path, mode):
 
554
        """Fail if a path does not have mode mode.
 
555
        
 
556
        If modes are not supported on this transport, the assertion is ignored.
 
557
        """
 
558
        if not transport._can_roundtrip_unix_modebits():
 
559
            return
 
560
        path_stat = transport.stat(path)
 
561
        actual_mode = stat.S_IMODE(path_stat.st_mode)
 
562
        self.assertEqual(mode, actual_mode,
 
563
            'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
 
564
 
 
565
    def assertIsInstance(self, obj, kls):
 
566
        """Fail if obj is not an instance of kls"""
 
567
        if not isinstance(obj, kls):
 
568
            self.fail("%r is an instance of %s rather than %s" % (
 
569
                obj, obj.__class__, kls))
 
570
 
 
571
    def _startLogFile(self):
 
572
        """Send bzr and test log messages to a temporary file.
 
573
 
 
574
        The file is removed as the test is torn down.
 
575
        """
 
576
        fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
 
577
        encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
 
578
        self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
 
579
        self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
 
580
        self._log_file_name = name
 
581
        self.addCleanup(self._finishLogFile)
 
582
 
 
583
    def _finishLogFile(self):
 
584
        """Finished with the log file.
 
585
 
 
586
        Read contents into memory, close, and delete.
 
587
        """
 
588
        if self._log_file is None:
 
589
            return
 
590
        bzrlib.trace.disable_test_log(self._log_nonce)
 
591
        self._log_file.seek(0)
 
592
        self._log_contents = self._log_file.read()
 
593
        self._log_file.close()
 
594
        os.remove(self._log_file_name)
 
595
        self._log_file = self._log_file_name = None
 
596
 
 
597
    def addCleanup(self, callable):
 
598
        """Arrange to run a callable when this case is torn down.
 
599
 
 
600
        Callables are run in the reverse of the order they are registered, 
 
601
        ie last-in first-out.
 
602
        """
 
603
        if callable in self._cleanups:
 
604
            raise ValueError("cleanup function %r already registered on %s" 
 
605
                    % (callable, self))
 
606
        self._cleanups.append(callable)
 
607
 
 
608
    def _cleanEnvironment(self):
 
609
        new_env = {
 
610
            'HOME': os.getcwd(),
 
611
            'APPDATA': os.getcwd(),
 
612
            'BZR_EMAIL': None,
 
613
            'BZREMAIL': None, # may still be present in the environment
 
614
            'EMAIL': None,
 
615
        }
 
616
        self.__old_env = {}
 
617
        self.addCleanup(self._restoreEnvironment)
 
618
        for name, value in new_env.iteritems():
 
619
            self._captureVar(name, value)
 
620
 
 
621
 
 
622
    def _captureVar(self, name, newvalue):
 
623
        """Set an environment variable, preparing it to be reset when finished."""
 
624
        self.__old_env[name] = os.environ.get(name, None)
 
625
        if newvalue is None:
 
626
            if name in os.environ:
 
627
                del os.environ[name]
 
628
        else:
 
629
            os.environ[name] = newvalue
 
630
 
 
631
    @staticmethod
 
632
    def _restoreVar(name, value):
 
633
        if value is None:
 
634
            if name in os.environ:
 
635
                del os.environ[name]
 
636
        else:
 
637
            os.environ[name] = value
 
638
 
 
639
    def _restoreEnvironment(self):
 
640
        for name, value in self.__old_env.iteritems():
 
641
            self._restoreVar(name, value)
 
642
 
 
643
    def tearDown(self):
 
644
        self._runCleanups()
 
645
        unittest.TestCase.tearDown(self)
 
646
 
 
647
    def time(self, callable, *args, **kwargs):
 
648
        """Run callable and accrue the time it takes to the benchmark time.
 
649
        
 
650
        If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
 
651
        this will cause lsprofile statistics to be gathered and stored in
 
652
        self._benchcalls.
 
653
        """
 
654
        if self._benchtime is None:
 
655
            self._benchtime = 0
 
656
        start = time.time()
 
657
        try:
 
658
            if not self._gather_lsprof_in_benchmarks:
 
659
                return callable(*args, **kwargs)
 
660
            else:
 
661
                # record this benchmark
 
662
                ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
 
663
                stats.sort()
 
664
                self._benchcalls.append(((callable, args, kwargs), stats))
 
665
                return ret
 
666
        finally:
 
667
            self._benchtime += time.time() - start
 
668
 
 
669
    def _runCleanups(self):
 
670
        """Run registered cleanup functions. 
 
671
 
 
672
        This should only be called from TestCase.tearDown.
 
673
        """
 
674
        # TODO: Perhaps this should keep running cleanups even if 
 
675
        # one of them fails?
 
676
        for cleanup_fn in reversed(self._cleanups):
 
677
            cleanup_fn()
 
678
 
 
679
    def log(self, *args):
 
680
        mutter(*args)
 
681
 
 
682
    def _get_log(self):
 
683
        """Return as a string the log for this test"""
 
684
        if self._log_file_name:
 
685
            return open(self._log_file_name).read()
 
686
        else:
 
687
            return self._log_contents
 
688
        # TODO: Delete the log after it's been read in
 
689
 
 
690
    def capture(self, cmd, retcode=0):
 
691
        """Shortcut that splits cmd into words, runs, and returns stdout"""
 
692
        return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
 
693
 
 
694
    def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None):
 
695
        """Invoke bzr and return (stdout, stderr).
 
696
 
 
697
        Useful for code that wants to check the contents of the
 
698
        output, the way error messages are presented, etc.
 
699
 
 
700
        This should be the main method for tests that want to exercise the
 
701
        overall behavior of the bzr application (rather than a unit test
 
702
        or a functional test of the library.)
 
703
 
 
704
        Much of the old code runs bzr by forking a new copy of Python, but
 
705
        that is slower, harder to debug, and generally not necessary.
 
706
 
 
707
        This runs bzr through the interface that catches and reports
 
708
        errors, and with logging set to something approximating the
 
709
        default, so that error reporting can be checked.
 
710
 
 
711
        :param argv: arguments to invoke bzr
 
712
        :param retcode: expected return code, or None for don't-care.
 
713
        :param encoding: encoding for sys.stdout and sys.stderr
 
714
        :param stdin: A string to be used as stdin for the command.
 
715
        """
 
716
        if encoding is None:
 
717
            encoding = bzrlib.user_encoding
 
718
        if stdin is not None:
 
719
            stdin = StringIO(stdin)
 
720
        stdout = StringIOWrapper()
 
721
        stderr = StringIOWrapper()
 
722
        stdout.encoding = encoding
 
723
        stderr.encoding = encoding
 
724
 
 
725
        self.log('run bzr: %r', argv)
 
726
        # FIXME: don't call into logging here
 
727
        handler = logging.StreamHandler(stderr)
 
728
        handler.setLevel(logging.INFO)
 
729
        logger = logging.getLogger('')
 
730
        logger.addHandler(handler)
 
731
        old_ui_factory = bzrlib.ui.ui_factory
 
732
        bzrlib.ui.ui_factory = bzrlib.tests.blackbox.TestUIFactory(
 
733
            stdout=stdout,
 
734
            stderr=stderr)
 
735
        bzrlib.ui.ui_factory.stdin = stdin
 
736
        try:
 
737
            result = self.apply_redirected(stdin, stdout, stderr,
 
738
                                           bzrlib.commands.run_bzr_catch_errors,
 
739
                                           argv)
 
740
        finally:
 
741
            logger.removeHandler(handler)
 
742
            bzrlib.ui.ui_factory = old_ui_factory
 
743
 
 
744
        out = stdout.getvalue()
 
745
        err = stderr.getvalue()
 
746
        if out:
 
747
            self.log('output:\n%r', out)
 
748
        if err:
 
749
            self.log('errors:\n%r', err)
 
750
        if retcode is not None:
 
751
            self.assertEquals(retcode, result)
 
752
        return out, err
 
753
 
 
754
    def run_bzr(self, *args, **kwargs):
 
755
        """Invoke bzr, as if it were run from the command line.
 
756
 
 
757
        This should be the main method for tests that want to exercise the
 
758
        overall behavior of the bzr application (rather than a unit test
 
759
        or a functional test of the library.)
 
760
 
 
761
        This sends the stdout/stderr results into the test's log,
 
762
        where it may be useful for debugging.  See also run_captured.
 
763
 
 
764
        :param stdin: A string to be used as stdin for the command.
 
765
        """
 
766
        retcode = kwargs.pop('retcode', 0)
 
767
        encoding = kwargs.pop('encoding', None)
 
768
        stdin = kwargs.pop('stdin', None)
 
769
        return self.run_bzr_captured(args, retcode=retcode, encoding=encoding, stdin=stdin)
 
770
 
 
771
    def run_bzr_decode(self, *args, **kwargs):
 
772
        if kwargs.has_key('encoding'):
 
773
            encoding = kwargs['encoding']
 
774
        else:
 
775
            encoding = bzrlib.user_encoding
 
776
        return self.run_bzr(*args, **kwargs)[0].decode(encoding)
 
777
 
 
778
    def run_bzr_error(self, error_regexes, *args, **kwargs):
 
779
        """Run bzr, and check that stderr contains the supplied regexes
 
780
        
 
781
        :param error_regexes: Sequence of regular expressions which 
 
782
            must each be found in the error output. The relative ordering
 
783
            is not enforced.
 
784
        :param args: command-line arguments for bzr
 
785
        :param kwargs: Keyword arguments which are interpreted by run_bzr
 
786
            This function changes the default value of retcode to be 3,
 
787
            since in most cases this is run when you expect bzr to fail.
 
788
        :return: (out, err) The actual output of running the command (in case you
 
789
                 want to do more inspection)
 
790
 
 
791
        Examples of use:
 
792
            # Make sure that commit is failing because there is nothing to do
 
793
            self.run_bzr_error(['no changes to commit'],
 
794
                               'commit', '-m', 'my commit comment')
 
795
            # Make sure --strict is handling an unknown file, rather than
 
796
            # giving us the 'nothing to do' error
 
797
            self.build_tree(['unknown'])
 
798
            self.run_bzr_error(['Commit refused because there are unknown files'],
 
799
                               'commit', '--strict', '-m', 'my commit comment')
 
800
        """
 
801
        kwargs.setdefault('retcode', 3)
 
802
        out, err = self.run_bzr(*args, **kwargs)
 
803
        for regex in error_regexes:
 
804
            self.assertContainsRe(err, regex)
 
805
        return out, err
 
806
 
 
807
    def run_bzr_subprocess(self, *args, **kwargs):
 
808
        """Run bzr in a subprocess for testing.
 
809
 
 
810
        This starts a new Python interpreter and runs bzr in there. 
 
811
        This should only be used for tests that have a justifiable need for
 
812
        this isolation: e.g. they are testing startup time, or signal
 
813
        handling, or early startup code, etc.  Subprocess code can't be 
 
814
        profiled or debugged so easily.
 
815
 
 
816
        :param retcode: The status code that is expected.  Defaults to 0.  If
 
817
        None is supplied, the status code is not checked.
 
818
        """
 
819
        bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
 
820
        args = list(args)
 
821
        process = Popen([sys.executable, bzr_path]+args, stdout=PIPE, 
 
822
                         stderr=PIPE)
 
823
        out = process.stdout.read()
 
824
        err = process.stderr.read()
 
825
        retcode = process.wait()
 
826
        supplied_retcode = kwargs.get('retcode', 0)
 
827
        if supplied_retcode is not None:
 
828
            assert supplied_retcode == retcode
 
829
        return [out, err]
 
830
 
 
831
    def check_inventory_shape(self, inv, shape):
 
832
        """Compare an inventory to a list of expected names.
 
833
 
 
834
        Fail if they are not precisely equal.
 
835
        """
 
836
        extras = []
 
837
        shape = list(shape)             # copy
 
838
        for path, ie in inv.entries():
 
839
            name = path.replace('\\', '/')
 
840
            if ie.kind == 'dir':
 
841
                name = name + '/'
 
842
            if name in shape:
 
843
                shape.remove(name)
 
844
            else:
 
845
                extras.append(name)
 
846
        if shape:
 
847
            self.fail("expected paths not found in inventory: %r" % shape)
 
848
        if extras:
 
849
            self.fail("unexpected paths found in inventory: %r" % extras)
 
850
 
 
851
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
852
                         a_callable=None, *args, **kwargs):
 
853
        """Call callable with redirected std io pipes.
 
854
 
 
855
        Returns the return code."""
 
856
        if not callable(a_callable):
 
857
            raise ValueError("a_callable must be callable.")
 
858
        if stdin is None:
 
859
            stdin = StringIO("")
 
860
        if stdout is None:
 
861
            if getattr(self, "_log_file", None) is not None:
 
862
                stdout = self._log_file
 
863
            else:
 
864
                stdout = StringIO()
 
865
        if stderr is None:
 
866
            if getattr(self, "_log_file", None is not None):
 
867
                stderr = self._log_file
 
868
            else:
 
869
                stderr = StringIO()
 
870
        real_stdin = sys.stdin
 
871
        real_stdout = sys.stdout
 
872
        real_stderr = sys.stderr
 
873
        try:
 
874
            sys.stdout = stdout
 
875
            sys.stderr = stderr
 
876
            sys.stdin = stdin
 
877
            return a_callable(*args, **kwargs)
 
878
        finally:
 
879
            sys.stdout = real_stdout
 
880
            sys.stderr = real_stderr
 
881
            sys.stdin = real_stdin
 
882
 
 
883
    def merge(self, branch_from, wt_to):
 
884
        """A helper for tests to do a ui-less merge.
 
885
 
 
886
        This should move to the main library when someone has time to integrate
 
887
        it in.
 
888
        """
 
889
        # minimal ui-less merge.
 
890
        wt_to.branch.fetch(branch_from)
 
891
        base_rev = common_ancestor(branch_from.last_revision(),
 
892
                                   wt_to.branch.last_revision(),
 
893
                                   wt_to.branch.repository)
 
894
        merge_inner(wt_to.branch, branch_from.basis_tree(), 
 
895
                    wt_to.branch.repository.revision_tree(base_rev),
 
896
                    this_tree=wt_to)
 
897
        wt_to.add_pending_merge(branch_from.last_revision())
 
898
 
 
899
 
 
900
BzrTestBase = TestCase
 
901
 
 
902
     
 
903
class TestCaseInTempDir(TestCase):
 
904
    """Derived class that runs a test within a temporary directory.
 
905
 
 
906
    This is useful for tests that need to create a branch, etc.
 
907
 
 
908
    The directory is created in a slightly complex way: for each
 
909
    Python invocation, a new temporary top-level directory is created.
 
910
    All test cases create their own directory within that.  If the
 
911
    tests complete successfully, the directory is removed.
 
912
 
 
913
    InTempDir is an old alias for FunctionalTestCase.
 
914
    """
 
915
 
 
916
    TEST_ROOT = None
 
917
    _TEST_NAME = 'test'
 
918
    OVERRIDE_PYTHON = 'python'
 
919
 
 
920
    def check_file_contents(self, filename, expect):
 
921
        self.log("check contents of file %s" % filename)
 
922
        contents = file(filename, 'r').read()
 
923
        if contents != expect:
 
924
            self.log("expected: %r" % expect)
 
925
            self.log("actually: %r" % contents)
 
926
            self.fail("contents of %s not as expected" % filename)
 
927
 
 
928
    def _make_test_root(self):
 
929
        if TestCaseInTempDir.TEST_ROOT is not None:
 
930
            return
 
931
        i = 0
 
932
        while True:
 
933
            root = u'test%04d.tmp' % i
 
934
            try:
 
935
                os.mkdir(root)
 
936
            except OSError, e:
 
937
                if e.errno == errno.EEXIST:
 
938
                    i += 1
 
939
                    continue
 
940
                else:
 
941
                    raise
 
942
            # successfully created
 
943
            TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
 
944
            break
 
945
        # make a fake bzr directory there to prevent any tests propagating
 
946
        # up onto the source directory's real branch
 
947
        bzrdir.BzrDir.create_standalone_workingtree(TestCaseInTempDir.TEST_ROOT)
 
948
 
 
949
    def setUp(self):
 
950
        super(TestCaseInTempDir, self).setUp()
 
951
        self._make_test_root()
 
952
        _currentdir = os.getcwdu()
 
953
        # shorten the name, to avoid test failures due to path length
 
954
        short_id = self.id().replace('bzrlib.tests.', '') \
 
955
                   .replace('__main__.', '')[-100:]
 
956
        # it's possible the same test class is run several times for
 
957
        # parameterized tests, so make sure the names don't collide.  
 
958
        i = 0
 
959
        while True:
 
960
            if i > 0:
 
961
                candidate_dir = '%s/%s.%d' % (self.TEST_ROOT, short_id, i)
 
962
            else:
 
963
                candidate_dir = '%s/%s' % (self.TEST_ROOT, short_id)
 
964
            if os.path.exists(candidate_dir):
 
965
                i = i + 1
 
966
                continue
 
967
            else:
 
968
                self.test_dir = candidate_dir
 
969
                os.mkdir(self.test_dir)
 
970
                os.chdir(self.test_dir)
 
971
                break
 
972
        os.environ['HOME'] = self.test_dir
 
973
        os.environ['APPDATA'] = self.test_dir
 
974
        def _leaveDirectory():
 
975
            os.chdir(_currentdir)
 
976
        self.addCleanup(_leaveDirectory)
 
977
        
 
978
    def build_tree(self, shape, line_endings='native', transport=None):
 
979
        """Build a test tree according to a pattern.
 
980
 
 
981
        shape is a sequence of file specifications.  If the final
 
982
        character is '/', a directory is created.
 
983
 
 
984
        This assumes that all the elements in the tree being built are new.
 
985
 
 
986
        This doesn't add anything to a branch.
 
987
        :param line_endings: Either 'binary' or 'native'
 
988
                             in binary mode, exact contents are written
 
989
                             in native mode, the line endings match the
 
990
                             default platform endings.
 
991
 
 
992
        :param transport: A transport to write to, for building trees on 
 
993
                          VFS's. If the transport is readonly or None,
 
994
                          "." is opened automatically.
 
995
        """
 
996
        # It's OK to just create them using forward slashes on windows.
 
997
        if transport is None or transport.is_readonly():
 
998
            transport = get_transport(".")
 
999
        for name in shape:
 
1000
            self.assert_(isinstance(name, basestring))
 
1001
            if name[-1] == '/':
 
1002
                transport.mkdir(urlutils.escape(name[:-1]))
 
1003
            else:
 
1004
                if line_endings == 'binary':
 
1005
                    end = '\n'
 
1006
                elif line_endings == 'native':
 
1007
                    end = os.linesep
 
1008
                else:
 
1009
                    raise errors.BzrError('Invalid line ending request %r' % (line_endings,))
 
1010
                content = "contents of %s%s" % (name.encode('utf-8'), end)
 
1011
                # Technically 'put()' is the right command. However, put
 
1012
                # uses an AtomicFile, which requires an extra rename into place
 
1013
                # As long as the files didn't exist in the past, append() will
 
1014
                # do the same thing as put()
 
1015
                # On jam's machine, make_kernel_like_tree is:
 
1016
                #   put:    4.5-7.5s (averaging 6s)
 
1017
                #   append: 2.9-4.5s
 
1018
                transport.append(urlutils.escape(name), StringIO(content))
 
1019
 
 
1020
    def build_tree_contents(self, shape):
 
1021
        build_tree_contents(shape)
 
1022
 
 
1023
    def failUnlessExists(self, path):
 
1024
        """Fail unless path, which may be abs or relative, exists."""
 
1025
        self.failUnless(osutils.lexists(path))
 
1026
 
 
1027
    def failIfExists(self, path):
 
1028
        """Fail if path, which may be abs or relative, exists."""
 
1029
        self.failIf(osutils.lexists(path))
 
1030
        
 
1031
    def assertFileEqual(self, content, path):
 
1032
        """Fail if path does not contain 'content'."""
 
1033
        self.failUnless(osutils.lexists(path))
 
1034
        # TODO: jam 20060427 Shouldn't this be 'rb'?
 
1035
        self.assertEqualDiff(content, open(path, 'r').read())
 
1036
 
 
1037
 
 
1038
class TestCaseWithTransport(TestCaseInTempDir):
 
1039
    """A test case that provides get_url and get_readonly_url facilities.
 
1040
 
 
1041
    These back onto two transport servers, one for readonly access and one for
 
1042
    read write access.
 
1043
 
 
1044
    If no explicit class is provided for readonly access, a
 
1045
    ReadonlyTransportDecorator is used instead which allows the use of non disk
 
1046
    based read write transports.
 
1047
 
 
1048
    If an explicit class is provided for readonly access, that server and the 
 
1049
    readwrite one must both define get_url() as resolving to os.getcwd().
 
1050
    """
 
1051
 
 
1052
    def __init__(self, methodName='testMethod'):
 
1053
        super(TestCaseWithTransport, self).__init__(methodName)
 
1054
        self.__readonly_server = None
 
1055
        self.__server = None
 
1056
        self.transport_server = default_transport
 
1057
        self.transport_readonly_server = None
 
1058
 
 
1059
    def get_readonly_url(self, relpath=None):
 
1060
        """Get a URL for the readonly transport.
 
1061
 
 
1062
        This will either be backed by '.' or a decorator to the transport 
 
1063
        used by self.get_url()
 
1064
        relpath provides for clients to get a path relative to the base url.
 
1065
        These should only be downwards relative, not upwards.
 
1066
        """
 
1067
        base = self.get_readonly_server().get_url()
 
1068
        if relpath is not None:
 
1069
            if not base.endswith('/'):
 
1070
                base = base + '/'
 
1071
            base = base + relpath
 
1072
        return base
 
1073
 
 
1074
    def get_readonly_server(self):
 
1075
        """Get the server instance for the readonly transport
 
1076
 
 
1077
        This is useful for some tests with specific servers to do diagnostics.
 
1078
        """
 
1079
        if self.__readonly_server is None:
 
1080
            if self.transport_readonly_server is None:
 
1081
                # readonly decorator requested
 
1082
                # bring up the server
 
1083
                self.get_url()
 
1084
                self.__readonly_server = ReadonlyServer()
 
1085
                self.__readonly_server.setUp(self.__server)
 
1086
            else:
 
1087
                self.__readonly_server = self.transport_readonly_server()
 
1088
                self.__readonly_server.setUp()
 
1089
            self.addCleanup(self.__readonly_server.tearDown)
 
1090
        return self.__readonly_server
 
1091
 
 
1092
    def get_server(self):
 
1093
        """Get the read/write server instance.
 
1094
 
 
1095
        This is useful for some tests with specific servers that need
 
1096
        diagnostics.
 
1097
        """
 
1098
        if self.__server is None:
 
1099
            self.__server = self.transport_server()
 
1100
            self.__server.setUp()
 
1101
            self.addCleanup(self.__server.tearDown)
 
1102
        return self.__server
 
1103
 
 
1104
    def get_url(self, relpath=None):
 
1105
        """Get a URL for the readwrite transport.
 
1106
 
 
1107
        This will either be backed by '.' or to an equivalent non-file based
 
1108
        facility.
 
1109
        relpath provides for clients to get a path relative to the base url.
 
1110
        These should only be downwards relative, not upwards.
 
1111
        """
 
1112
        base = self.get_server().get_url()
 
1113
        if relpath is not None and relpath != '.':
 
1114
            if not base.endswith('/'):
 
1115
                base = base + '/'
 
1116
            base = base + urlutils.escape(relpath)
 
1117
        return base
 
1118
 
 
1119
    def get_transport(self):
 
1120
        """Return a writeable transport for the test scratch space"""
 
1121
        t = get_transport(self.get_url())
 
1122
        self.assertFalse(t.is_readonly())
 
1123
        return t
 
1124
 
 
1125
    def get_readonly_transport(self):
 
1126
        """Return a readonly transport for the test scratch space
 
1127
        
 
1128
        This can be used to test that operations which should only need
 
1129
        readonly access in fact do not try to write.
 
1130
        """
 
1131
        t = get_transport(self.get_readonly_url())
 
1132
        self.assertTrue(t.is_readonly())
 
1133
        return t
 
1134
 
 
1135
    def make_branch(self, relpath, format=None):
 
1136
        """Create a branch on the transport at relpath."""
 
1137
        repo = self.make_repository(relpath, format=format)
 
1138
        return repo.bzrdir.create_branch()
 
1139
 
 
1140
    def make_bzrdir(self, relpath, format=None):
 
1141
        try:
 
1142
            url = self.get_url(relpath)
 
1143
            mutter('relpath %r => url %r', relpath, url)
 
1144
            segments = url.split('/')
 
1145
            if segments and segments[-1] not in ('', '.'):
 
1146
                parent = '/'.join(segments[:-1])
 
1147
                t = get_transport(parent)
 
1148
                try:
 
1149
                    t.mkdir(segments[-1])
 
1150
                except errors.FileExists:
 
1151
                    pass
 
1152
            if format is None:
 
1153
                format=bzrlib.bzrdir.BzrDirFormat.get_default_format()
 
1154
            # FIXME: make this use a single transport someday. RBC 20060418
 
1155
            return format.initialize_on_transport(get_transport(relpath))
 
1156
        except errors.UninitializableFormat:
 
1157
            raise TestSkipped("Format %s is not initializable." % format)
 
1158
 
 
1159
    def make_repository(self, relpath, shared=False, format=None):
 
1160
        """Create a repository on our default transport at relpath."""
 
1161
        made_control = self.make_bzrdir(relpath, format=format)
 
1162
        return made_control.create_repository(shared=shared)
 
1163
 
 
1164
    def make_branch_and_tree(self, relpath, format=None):
 
1165
        """Create a branch on the transport and a tree locally.
 
1166
 
 
1167
        Returns the tree.
 
1168
        """
 
1169
        # TODO: always use the local disk path for the working tree,
 
1170
        # this obviously requires a format that supports branch references
 
1171
        # so check for that by checking bzrdir.BzrDirFormat.get_default_format()
 
1172
        # RBC 20060208
 
1173
        b = self.make_branch(relpath, format=format)
 
1174
        try:
 
1175
            return b.bzrdir.create_workingtree()
 
1176
        except errors.NotLocalUrl:
 
1177
            # new formats - catch No tree error and create
 
1178
            # a branch reference and a checkout.
 
1179
            # old formats at that point - raise TestSkipped.
 
1180
            # TODO: rbc 20060208
 
1181
            return WorkingTreeFormat2().initialize(bzrdir.BzrDir.open(relpath))
 
1182
 
 
1183
    def assertIsDirectory(self, relpath, transport):
 
1184
        """Assert that relpath within transport is a directory.
 
1185
 
 
1186
        This may not be possible on all transports; in that case it propagates
 
1187
        a TransportNotPossible.
 
1188
        """
 
1189
        try:
 
1190
            mode = transport.stat(relpath).st_mode
 
1191
        except errors.NoSuchFile:
 
1192
            self.fail("path %s is not a directory; no such file"
 
1193
                      % (relpath))
 
1194
        if not stat.S_ISDIR(mode):
 
1195
            self.fail("path %s is not a directory; has mode %#o"
 
1196
                      % (relpath, mode))
 
1197
 
 
1198
 
 
1199
class ChrootedTestCase(TestCaseWithTransport):
 
1200
    """A support class that provides readonly urls outside the local namespace.
 
1201
 
 
1202
    This is done by checking if self.transport_server is a MemoryServer. if it
 
1203
    is then we are chrooted already, if it is not then an HttpServer is used
 
1204
    for readonly urls.
 
1205
 
 
1206
    TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
 
1207
                       be used without needed to redo it when a different 
 
1208
                       subclass is in use ?
 
1209
    """
 
1210
 
 
1211
    def setUp(self):
 
1212
        super(ChrootedTestCase, self).setUp()
 
1213
        if not self.transport_server == bzrlib.transport.memory.MemoryServer:
 
1214
            self.transport_readonly_server = bzrlib.transport.http.HttpServer
 
1215
 
 
1216
 
 
1217
def filter_suite_by_re(suite, pattern):
 
1218
    result = TestUtil.TestSuite()
 
1219
    filter_re = re.compile(pattern)
 
1220
    for test in iter_suite_tests(suite):
 
1221
        if filter_re.search(test.id()):
 
1222
            result.addTest(test)
 
1223
    return result
 
1224
 
 
1225
 
 
1226
def run_suite(suite, name='test', verbose=False, pattern=".*",
 
1227
              stop_on_failure=False, keep_output=False,
 
1228
              transport=None, lsprof_timed=None, bench_history=None):
 
1229
    TestCaseInTempDir._TEST_NAME = name
 
1230
    TestCase._gather_lsprof_in_benchmarks = lsprof_timed
 
1231
    if verbose:
 
1232
        verbosity = 2
 
1233
        pb = None
 
1234
    else:
 
1235
        verbosity = 1
 
1236
        pb = progress.ProgressBar()
 
1237
    runner = TextTestRunner(stream=sys.stdout,
 
1238
                            descriptions=0,
 
1239
                            verbosity=verbosity,
 
1240
                            keep_output=keep_output,
 
1241
                            pb=pb,
 
1242
                            bench_history=bench_history)
 
1243
    runner.stop_on_failure=stop_on_failure
 
1244
    if pattern != '.*':
 
1245
        suite = filter_suite_by_re(suite, pattern)
 
1246
    result = runner.run(suite)
 
1247
    return result.wasSuccessful()
 
1248
 
 
1249
 
 
1250
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
 
1251
             keep_output=False,
 
1252
             transport=None,
 
1253
             test_suite_factory=None,
 
1254
             lsprof_timed=None,
 
1255
             bench_history=None):
 
1256
    """Run the whole test suite under the enhanced runner"""
 
1257
    # XXX: Very ugly way to do this...
 
1258
    # Disable warning about old formats because we don't want it to disturb
 
1259
    # any blackbox tests.
 
1260
    from bzrlib import repository
 
1261
    repository._deprecation_warning_done = True
 
1262
 
 
1263
    global default_transport
 
1264
    if transport is None:
 
1265
        transport = default_transport
 
1266
    old_transport = default_transport
 
1267
    default_transport = transport
 
1268
    try:
 
1269
        if test_suite_factory is None:
 
1270
            suite = test_suite()
 
1271
        else:
 
1272
            suite = test_suite_factory()
 
1273
        return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
 
1274
                     stop_on_failure=stop_on_failure, keep_output=keep_output,
 
1275
                     transport=transport,
 
1276
                     lsprof_timed=lsprof_timed,
 
1277
                     bench_history=bench_history)
 
1278
    finally:
 
1279
        default_transport = old_transport
 
1280
 
 
1281
 
 
1282
def test_suite():
 
1283
    """Build and return TestSuite for the whole of bzrlib.
 
1284
    
 
1285
    This function can be replaced if you need to change the default test
 
1286
    suite on a global basis, but it is not encouraged.
 
1287
    """
 
1288
    testmod_names = [
 
1289
                   'bzrlib.tests.test_ancestry',
 
1290
                   'bzrlib.tests.test_api',
 
1291
                   'bzrlib.tests.test_atomicfile',
 
1292
                   'bzrlib.tests.test_bad_files',
 
1293
                   'bzrlib.tests.test_branch',
 
1294
                   'bzrlib.tests.test_bundle',
 
1295
                   'bzrlib.tests.test_bzrdir',
 
1296
                   'bzrlib.tests.test_command',
 
1297
                   'bzrlib.tests.test_commit',
 
1298
                   'bzrlib.tests.test_commit_merge',
 
1299
                   'bzrlib.tests.test_config',
 
1300
                   'bzrlib.tests.test_conflicts',
 
1301
                   'bzrlib.tests.test_decorators',
 
1302
                   'bzrlib.tests.test_diff',
 
1303
                   'bzrlib.tests.test_doc_generate',
 
1304
                   'bzrlib.tests.test_errors',
 
1305
                   'bzrlib.tests.test_escaped_store',
 
1306
                   'bzrlib.tests.test_fetch',
 
1307
                   'bzrlib.tests.test_gpg',
 
1308
                   'bzrlib.tests.test_graph',
 
1309
                   'bzrlib.tests.test_hashcache',
 
1310
                   'bzrlib.tests.test_http',
 
1311
                   'bzrlib.tests.test_http_response',
 
1312
                   'bzrlib.tests.test_identitymap',
 
1313
                   'bzrlib.tests.test_ignores',
 
1314
                   'bzrlib.tests.test_inv',
 
1315
                   'bzrlib.tests.test_knit',
 
1316
                   'bzrlib.tests.test_lockdir',
 
1317
                   'bzrlib.tests.test_lockable_files',
 
1318
                   'bzrlib.tests.test_log',
 
1319
                   'bzrlib.tests.test_merge',
 
1320
                   'bzrlib.tests.test_merge3',
 
1321
                   'bzrlib.tests.test_merge_core',
 
1322
                   'bzrlib.tests.test_missing',
 
1323
                   'bzrlib.tests.test_msgeditor',
 
1324
                   'bzrlib.tests.test_nonascii',
 
1325
                   'bzrlib.tests.test_options',
 
1326
                   'bzrlib.tests.test_osutils',
 
1327
                   'bzrlib.tests.test_patch',
 
1328
                   'bzrlib.tests.test_patches',
 
1329
                   'bzrlib.tests.test_permissions',
 
1330
                   'bzrlib.tests.test_plugins',
 
1331
                   'bzrlib.tests.test_progress',
 
1332
                   'bzrlib.tests.test_reconcile',
 
1333
                   'bzrlib.tests.test_repository',
 
1334
                   'bzrlib.tests.test_revision',
 
1335
                   'bzrlib.tests.test_revisionnamespaces',
 
1336
                   'bzrlib.tests.test_revisiontree',
 
1337
                   'bzrlib.tests.test_rio',
 
1338
                   'bzrlib.tests.test_sampler',
 
1339
                   'bzrlib.tests.test_selftest',
 
1340
                   'bzrlib.tests.test_setup',
 
1341
                   'bzrlib.tests.test_sftp_transport',
 
1342
                   'bzrlib.tests.test_smart_add',
 
1343
                   'bzrlib.tests.test_source',
 
1344
                   'bzrlib.tests.test_status',
 
1345
                   'bzrlib.tests.test_store',
 
1346
                   'bzrlib.tests.test_symbol_versioning',
 
1347
                   'bzrlib.tests.test_testament',
 
1348
                   'bzrlib.tests.test_textfile',
 
1349
                   'bzrlib.tests.test_textmerge',
 
1350
                   'bzrlib.tests.test_trace',
 
1351
                   'bzrlib.tests.test_transactions',
 
1352
                   'bzrlib.tests.test_transform',
 
1353
                   'bzrlib.tests.test_transport',
 
1354
                   'bzrlib.tests.test_tree',
 
1355
                   'bzrlib.tests.test_tsort',
 
1356
                   'bzrlib.tests.test_tuned_gzip',
 
1357
                   'bzrlib.tests.test_ui',
 
1358
                   'bzrlib.tests.test_upgrade',
 
1359
                   'bzrlib.tests.test_urlutils',
 
1360
                   'bzrlib.tests.test_versionedfile',
 
1361
                   'bzrlib.tests.test_weave',
 
1362
                   'bzrlib.tests.test_whitebox',
 
1363
                   'bzrlib.tests.test_workingtree',
 
1364
                   'bzrlib.tests.test_xml',
 
1365
                   ]
 
1366
    test_transport_implementations = [
 
1367
        'bzrlib.tests.test_transport_implementations',
 
1368
        'bzrlib.tests.test_read_bundle',
 
1369
        ]
 
1370
    suite = TestUtil.TestSuite()
 
1371
    loader = TestUtil.TestLoader()
 
1372
    suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
 
1373
    from bzrlib.transport import TransportTestProviderAdapter
 
1374
    adapter = TransportTestProviderAdapter()
 
1375
    adapt_modules(test_transport_implementations, adapter, loader, suite)
 
1376
    for package in packages_to_test():
 
1377
        suite.addTest(package.test_suite())
 
1378
    for m in MODULES_TO_TEST:
 
1379
        suite.addTest(loader.loadTestsFromModule(m))
 
1380
    for m in MODULES_TO_DOCTEST:
 
1381
        suite.addTest(doctest.DocTestSuite(m))
 
1382
    for name, plugin in bzrlib.plugin.all_plugins().items():
 
1383
        if getattr(plugin, 'test_suite', None) is not None:
 
1384
            suite.addTest(plugin.test_suite())
 
1385
    return suite
 
1386
 
 
1387
 
 
1388
def adapt_modules(mods_list, adapter, loader, suite):
 
1389
    """Adapt the modules in mods_list using adapter and add to suite."""
 
1390
    for test in iter_suite_tests(loader.loadTestsFromModuleNames(mods_list)):
 
1391
        suite.addTests(adapter.adapt(test))