/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-09-13 02:51:49 UTC
  • mto: This revision was merged to the branch mainline in revision 2071.
  • Revision ID: john@arbash-meinel.com-20060913025149-ecee20a9ca6fc4a6
lazy_import AtomicFile

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