/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/__init__.py

  • Committer: John Arbash Meinel
  • Date: 2006-08-15 04:53:15 UTC
  • mto: This revision was merged to the branch mainline in revision 1923.
  • Revision ID: john@arbash-meinel.com-20060815045315-05183d622115ea71
NEWS

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