1
# Copyright (C) 2005, 2006 by Canonical Ltd
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.
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.
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
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)
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.
30
from cStringIO import StringIO
44
import bzrlib.bzrdir as bzrdir
45
import bzrlib.commands
46
import bzrlib.errors as errors
47
import bzrlib.inventory
48
import bzrlib.iterablefile
50
from bzrlib.merge import merge_inner
53
import bzrlib.osutils as osutils
55
import bzrlib.progress as progress
56
from bzrlib.revision import common_ancestor
59
from bzrlib.transport import urlescape, get_transport
60
import bzrlib.transport
61
from bzrlib.transport.local import LocalRelpathServer
62
from bzrlib.transport.readonly import ReadonlyServer
63
from bzrlib.trace import mutter
64
from bzrlib.tests.TestUtil import TestLoader, TestSuite
65
from bzrlib.tests.treeshape import build_tree_contents
66
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
68
default_transport = LocalRelpathServer
71
MODULES_TO_DOCTEST = [
83
def packages_to_test():
84
"""Return a list of packages to test.
86
The packages are not globally imported so that import failures are
87
triggered when running selftest, not when importing the command.
90
import bzrlib.tests.blackbox
91
import bzrlib.tests.branch_implementations
92
import bzrlib.tests.bzrdir_implementations
93
import bzrlib.tests.interrepository_implementations
94
import bzrlib.tests.interversionedfile_implementations
95
import bzrlib.tests.repository_implementations
96
import bzrlib.tests.revisionstore_implementations
97
import bzrlib.tests.workingtree_implementations
100
bzrlib.tests.blackbox,
101
bzrlib.tests.branch_implementations,
102
bzrlib.tests.bzrdir_implementations,
103
bzrlib.tests.interrepository_implementations,
104
bzrlib.tests.interversionedfile_implementations,
105
bzrlib.tests.repository_implementations,
106
bzrlib.tests.revisionstore_implementations,
107
bzrlib.tests.workingtree_implementations,
111
class _MyResult(unittest._TextTestResult):
112
"""Custom TestResult.
114
Shows output in a different format, including displaying runtime for tests.
118
def __init__(self, stream, descriptions, verbosity, pb=None):
119
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
122
def _elapsedTime(self):
123
return "%5dms" % (1000 * (time.time() - self._start_time))
125
def _ellipsise_unimportant_words(self, a_string, final_width,
127
"""Add ellipsese (sp?) for overly long strings.
129
:param keep_start: If true preserve the start of a_string rather
133
if len(a_string) > final_width:
134
result = a_string[:final_width-3] + '...'
138
if len(a_string) > final_width:
139
result = '...' + a_string[3-final_width:]
142
return result.ljust(final_width)
144
def startTest(self, test):
145
unittest.TestResult.startTest(self, test)
146
# In a short description, the important words are in
147
# the beginning, but in an id, the important words are
149
SHOW_DESCRIPTIONS = False
151
if not self.showAll and self.dots and self.pb is not None:
154
final_width = osutils.terminal_width()
155
final_width = final_width - 15
157
if SHOW_DESCRIPTIONS:
158
what = test.shortDescription()
160
what = self._ellipsise_unimportant_words(what, final_width, keep_start=True)
163
if what.startswith('bzrlib.tests.'):
165
what = self._ellipsise_unimportant_words(what, final_width)
167
self.stream.write(what)
168
elif self.dots and self.pb is not None:
169
self.pb.update(what, self.testsRun - 1, None)
171
self._start_time = time.time()
173
def addError(self, test, err):
174
if isinstance(err[1], TestSkipped):
175
return self.addSkipped(test, err)
176
unittest.TestResult.addError(self, test, err)
178
self.stream.writeln("ERROR %s" % self._elapsedTime())
179
elif self.dots and self.pb is None:
180
self.stream.write('E')
182
self.pb.update(self._ellipsise_unimportant_words('ERROR', 13), self.testsRun, None)
187
def addFailure(self, test, err):
188
unittest.TestResult.addFailure(self, test, err)
190
self.stream.writeln(" FAIL %s" % self._elapsedTime())
191
elif self.dots and self.pb is None:
192
self.stream.write('F')
194
self.pb.update(self._ellipsise_unimportant_words('FAIL', 13), self.testsRun, None)
199
def addSuccess(self, test):
201
self.stream.writeln(' OK %s' % self._elapsedTime())
202
elif self.dots and self.pb is None:
203
self.stream.write('~')
205
self.pb.update(self._ellipsise_unimportant_words('OK', 13), self.testsRun, None)
207
unittest.TestResult.addSuccess(self, test)
209
def addSkipped(self, test, skip_excinfo):
211
print >>self.stream, ' SKIP %s' % self._elapsedTime()
212
print >>self.stream, ' %s' % skip_excinfo[1]
213
elif self.dots and self.pb is None:
214
self.stream.write('S')
216
self.pb.update(self._ellipsise_unimportant_words('SKIP', 13), self.testsRun, None)
218
# seems best to treat this as success from point-of-view of unittest
219
# -- it actually does nothing so it barely matters :)
220
unittest.TestResult.addSuccess(self, test)
222
def printErrorList(self, flavour, errors):
223
for test, err in errors:
224
self.stream.writeln(self.separator1)
225
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
226
if getattr(test, '_get_log', None) is not None:
228
print >>self.stream, \
229
('vvvv[log from %s]' % test.id()).ljust(78,'-')
230
print >>self.stream, test._get_log()
231
print >>self.stream, \
232
('^^^^[log from %s]' % test.id()).ljust(78,'-')
233
self.stream.writeln(self.separator2)
234
self.stream.writeln("%s" % err)
237
class TextTestRunner(object):
238
stop_on_failure = False
246
self.stream = unittest._WritelnDecorator(stream)
247
self.descriptions = descriptions
248
self.verbosity = verbosity
249
self.keep_output = keep_output
252
def _makeResult(self):
253
result = _MyResult(self.stream,
257
result.stop_early = self.stop_on_failure
261
"Run the given test case or test suite."
262
result = self._makeResult()
263
startTime = time.time()
264
if self.pb is not None:
265
self.pb.update('Running tests', 0, test.countTestCases())
267
stopTime = time.time()
268
timeTaken = stopTime - startTime
270
self.stream.writeln(result.separator2)
271
run = result.testsRun
272
self.stream.writeln("Ran %d test%s in %.3fs" %
273
(run, run != 1 and "s" or "", timeTaken))
274
self.stream.writeln()
275
if not result.wasSuccessful():
276
self.stream.write("FAILED (")
277
failed, errored = map(len, (result.failures, result.errors))
279
self.stream.write("failures=%d" % failed)
281
if failed: self.stream.write(", ")
282
self.stream.write("errors=%d" % errored)
283
self.stream.writeln(")")
285
self.stream.writeln("OK")
286
if self.pb is not None:
287
self.pb.update('Cleaning up', 0, 1)
288
# This is still a little bogus,
289
# but only a little. Folk not using our testrunner will
290
# have to delete their temp directories themselves.
291
test_root = TestCaseInTempDir.TEST_ROOT
292
if result.wasSuccessful() or not self.keep_output:
293
if test_root is not None:
294
osutils.rmtree(test_root)
296
if self.pb is not None:
297
self.pb.note("Failed tests working directories are in '%s'\n",
301
"Failed tests working directories are in '%s'\n" %
303
TestCaseInTempDir.TEST_ROOT = None
304
if self.pb is not None:
309
def iter_suite_tests(suite):
310
"""Return all tests in a suite, recursing through nested suites"""
311
for item in suite._tests:
312
if isinstance(item, unittest.TestCase):
314
elif isinstance(item, unittest.TestSuite):
315
for r in iter_suite_tests(item):
318
raise Exception('unknown object %r inside test suite %r'
322
class TestSkipped(Exception):
323
"""Indicates that a test was intentionally skipped, rather than failing."""
327
class CommandFailed(Exception):
330
class TestCase(unittest.TestCase):
331
"""Base class for bzr unit tests.
333
Tests that need access to disk resources should subclass
334
TestCaseInTempDir not TestCase.
336
Error and debug log messages are redirected from their usual
337
location into a temporary file, the contents of which can be
338
retrieved by _get_log(). We use a real OS file, not an in-memory object,
339
so that it can also capture file IO. When the test completes this file
340
is read into memory and removed from disk.
342
There are also convenience functions to invoke bzr's command-line
343
routine, and to build and check bzr trees.
345
In addition to the usual method of overriding tearDown(), this class also
346
allows subclasses to register functions into the _cleanups list, which is
347
run in order as the object is torn down. It's less likely this will be
348
accidentally overlooked.
351
_log_file_name = None
354
def __init__(self, methodName='testMethod'):
355
super(TestCase, self).__init__(methodName)
359
unittest.TestCase.setUp(self)
360
self._cleanEnvironment()
361
bzrlib.trace.disable_default_logging()
364
def _ndiff_strings(self, a, b):
365
"""Return ndiff between two strings containing lines.
367
A trailing newline is added if missing to make the strings
369
if b and b[-1] != '\n':
371
if a and a[-1] != '\n':
373
difflines = difflib.ndiff(a.splitlines(True),
375
linejunk=lambda x: False,
376
charjunk=lambda x: False)
377
return ''.join(difflines)
379
def assertEqualDiff(self, a, b, message=None):
380
"""Assert two texts are equal, if not raise an exception.
382
This is intended for use with multi-line strings where it can
383
be hard to find the differences by eye.
385
# TODO: perhaps override assertEquals to call this for strings?
389
message = "texts not equal:\n"
390
raise AssertionError(message +
391
self._ndiff_strings(a, b))
393
def assertEqualMode(self, mode, mode_test):
394
self.assertEqual(mode, mode_test,
395
'mode mismatch %o != %o' % (mode, mode_test))
397
def assertStartsWith(self, s, prefix):
398
if not s.startswith(prefix):
399
raise AssertionError('string %r does not start with %r' % (s, prefix))
401
def assertEndsWith(self, s, suffix):
402
"""Asserts that s ends with suffix."""
403
if not s.endswith(suffix):
404
raise AssertionError('string %r does not end with %r' % (s, suffix))
406
def assertContainsRe(self, haystack, needle_re):
407
"""Assert that a contains something matching a regular expression."""
408
if not re.search(needle_re, haystack):
409
raise AssertionError('pattern "%s" not found in "%s"'
410
% (needle_re, haystack))
412
def assertSubset(self, sublist, superlist):
413
"""Assert that every entry in sublist is present in superlist."""
415
for entry in sublist:
416
if entry not in superlist:
417
missing.append(entry)
419
raise AssertionError("value(s) %r not present in container %r" %
420
(missing, superlist))
422
def assertIs(self, left, right):
423
if not (left is right):
424
raise AssertionError("%r is not %r." % (left, right))
426
def assertTransportMode(self, transport, path, mode):
427
"""Fail if a path does not have mode mode.
429
If modes are not supported on this transport, the assertion is ignored.
431
if not transport._can_roundtrip_unix_modebits():
433
path_stat = transport.stat(path)
434
actual_mode = stat.S_IMODE(path_stat.st_mode)
435
self.assertEqual(mode, actual_mode,
436
'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
438
def assertIsInstance(self, obj, kls):
439
"""Fail if obj is not an instance of kls"""
440
if not isinstance(obj, kls):
441
self.fail("%r is an instance of %s rather than %s" % (
442
obj, obj.__class__, kls))
444
def _startLogFile(self):
445
"""Send bzr and test log messages to a temporary file.
447
The file is removed as the test is torn down.
449
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
450
encoder, decoder, stream_reader, stream_writer = codecs.lookup('UTF-8')
451
self._log_file = stream_writer(os.fdopen(fileno, 'w+'))
452
self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
453
self._log_file_name = name
454
self.addCleanup(self._finishLogFile)
456
def _finishLogFile(self):
457
"""Finished with the log file.
459
Read contents into memory, close, and delete.
461
bzrlib.trace.disable_test_log(self._log_nonce)
462
self._log_file.seek(0)
463
self._log_contents = self._log_file.read()
464
self._log_file.close()
465
os.remove(self._log_file_name)
466
self._log_file = self._log_file_name = None
468
def addCleanup(self, callable):
469
"""Arrange to run a callable when this case is torn down.
471
Callables are run in the reverse of the order they are registered,
472
ie last-in first-out.
474
if callable in self._cleanups:
475
raise ValueError("cleanup function %r already registered on %s"
477
self._cleanups.append(callable)
479
def _cleanEnvironment(self):
482
'APPDATA': os.getcwd(),
487
self.addCleanup(self._restoreEnvironment)
488
for name, value in new_env.iteritems():
489
self._captureVar(name, value)
492
def _captureVar(self, name, newvalue):
493
"""Set an environment variable, preparing it to be reset when finished."""
494
self.__old_env[name] = os.environ.get(name, None)
496
if name in os.environ:
499
os.environ[name] = newvalue
502
def _restoreVar(name, value):
504
if name in os.environ:
507
os.environ[name] = value
509
def _restoreEnvironment(self):
510
for name, value in self.__old_env.iteritems():
511
self._restoreVar(name, value)
515
unittest.TestCase.tearDown(self)
517
def _runCleanups(self):
518
"""Run registered cleanup functions.
520
This should only be called from TestCase.tearDown.
522
# TODO: Perhaps this should keep running cleanups even if
524
for cleanup_fn in reversed(self._cleanups):
527
def log(self, *args):
531
"""Return as a string the log for this test"""
532
if self._log_file_name:
533
return open(self._log_file_name).read()
535
return self._log_contents
536
# TODO: Delete the log after it's been read in
538
def capture(self, cmd, retcode=0):
539
"""Shortcut that splits cmd into words, runs, and returns stdout"""
540
return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
542
def run_bzr_captured(self, argv, retcode=0, stdin=None):
543
"""Invoke bzr and return (stdout, stderr).
545
Useful for code that wants to check the contents of the
546
output, the way error messages are presented, etc.
548
This should be the main method for tests that want to exercise the
549
overall behavior of the bzr application (rather than a unit test
550
or a functional test of the library.)
552
Much of the old code runs bzr by forking a new copy of Python, but
553
that is slower, harder to debug, and generally not necessary.
555
This runs bzr through the interface that catches and reports
556
errors, and with logging set to something approximating the
557
default, so that error reporting can be checked.
559
argv -- arguments to invoke bzr
560
retcode -- expected return code, or None for don't-care.
561
:param stdin: A string to be used as stdin for the command.
563
if stdin is not None:
564
stdin = StringIO(stdin)
567
self.log('run bzr: %s', ' '.join(argv))
568
# FIXME: don't call into logging here
569
handler = logging.StreamHandler(stderr)
570
handler.setFormatter(bzrlib.trace.QuietFormatter())
571
handler.setLevel(logging.INFO)
572
logger = logging.getLogger('')
573
logger.addHandler(handler)
574
old_ui_factory = bzrlib.ui.ui_factory
575
bzrlib.ui.ui_factory = bzrlib.tests.blackbox.TestUIFactory(
578
bzrlib.ui.ui_factory.stdin = stdin
580
result = self.apply_redirected(stdin, stdout, stderr,
581
bzrlib.commands.run_bzr_catch_errors,
584
logger.removeHandler(handler)
585
bzrlib.ui.ui_factory = old_ui_factory
586
out = stdout.getvalue()
587
err = stderr.getvalue()
589
self.log('output:\n%s', out)
591
self.log('errors:\n%s', err)
592
if retcode is not None:
593
self.assertEquals(result, retcode)
596
def run_bzr(self, *args, **kwargs):
597
"""Invoke bzr, as if it were run from the command line.
599
This should be the main method for tests that want to exercise the
600
overall behavior of the bzr application (rather than a unit test
601
or a functional test of the library.)
603
This sends the stdout/stderr results into the test's log,
604
where it may be useful for debugging. See also run_captured.
606
:param stdin: A string to be used as stdin for the command.
608
retcode = kwargs.pop('retcode', 0)
609
stdin = kwargs.pop('stdin', None)
610
return self.run_bzr_captured(args, retcode, stdin)
612
def check_inventory_shape(self, inv, shape):
613
"""Compare an inventory to a list of expected names.
615
Fail if they are not precisely equal.
618
shape = list(shape) # copy
619
for path, ie in inv.entries():
620
name = path.replace('\\', '/')
628
self.fail("expected paths not found in inventory: %r" % shape)
630
self.fail("unexpected paths found in inventory: %r" % extras)
632
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
633
a_callable=None, *args, **kwargs):
634
"""Call callable with redirected std io pipes.
636
Returns the return code."""
637
if not callable(a_callable):
638
raise ValueError("a_callable must be callable.")
642
if getattr(self, "_log_file", None) is not None:
643
stdout = self._log_file
647
if getattr(self, "_log_file", None is not None):
648
stderr = self._log_file
651
real_stdin = sys.stdin
652
real_stdout = sys.stdout
653
real_stderr = sys.stderr
658
return a_callable(*args, **kwargs)
660
sys.stdout = real_stdout
661
sys.stderr = real_stderr
662
sys.stdin = real_stdin
664
def merge(self, branch_from, wt_to):
665
"""A helper for tests to do a ui-less merge.
667
This should move to the main library when someone has time to integrate
670
# minimal ui-less merge.
671
wt_to.branch.fetch(branch_from)
672
base_rev = common_ancestor(branch_from.last_revision(),
673
wt_to.branch.last_revision(),
674
wt_to.branch.repository)
675
merge_inner(wt_to.branch, branch_from.basis_tree(),
676
wt_to.branch.repository.revision_tree(base_rev),
678
wt_to.add_pending_merge(branch_from.last_revision())
681
BzrTestBase = TestCase
684
class TestCaseInTempDir(TestCase):
685
"""Derived class that runs a test within a temporary directory.
687
This is useful for tests that need to create a branch, etc.
689
The directory is created in a slightly complex way: for each
690
Python invocation, a new temporary top-level directory is created.
691
All test cases create their own directory within that. If the
692
tests complete successfully, the directory is removed.
694
InTempDir is an old alias for FunctionalTestCase.
699
OVERRIDE_PYTHON = 'python'
701
def check_file_contents(self, filename, expect):
702
self.log("check contents of file %s" % filename)
703
contents = file(filename, 'r').read()
704
if contents != expect:
705
self.log("expected: %r" % expect)
706
self.log("actually: %r" % contents)
707
self.fail("contents of %s not as expected" % filename)
709
def _make_test_root(self):
710
if TestCaseInTempDir.TEST_ROOT is not None:
714
root = u'test%04d.tmp' % i
718
if e.errno == errno.EEXIST:
723
# successfully created
724
TestCaseInTempDir.TEST_ROOT = osutils.abspath(root)
726
# make a fake bzr directory there to prevent any tests propagating
727
# up onto the source directory's real branch
728
bzrdir.BzrDir.create_standalone_workingtree(TestCaseInTempDir.TEST_ROOT)
731
super(TestCaseInTempDir, self).setUp()
732
self._make_test_root()
733
_currentdir = os.getcwdu()
734
# shorten the name, to avoid test failures due to path length
735
short_id = self.id().replace('bzrlib.tests.', '') \
736
.replace('__main__.', '')[-100:]
737
# it's possible the same test class is run several times for
738
# parameterized tests, so make sure the names don't collide.
742
candidate_dir = '%s/%s.%d' % (self.TEST_ROOT, short_id, i)
744
candidate_dir = '%s/%s' % (self.TEST_ROOT, short_id)
745
if os.path.exists(candidate_dir):
749
self.test_dir = candidate_dir
750
os.mkdir(self.test_dir)
751
os.chdir(self.test_dir)
753
os.environ['HOME'] = self.test_dir
754
os.environ['APPDATA'] = self.test_dir
755
def _leaveDirectory():
756
os.chdir(_currentdir)
757
self.addCleanup(_leaveDirectory)
759
def build_tree(self, shape, line_endings='native', transport=None):
760
"""Build a test tree according to a pattern.
762
shape is a sequence of file specifications. If the final
763
character is '/', a directory is created.
765
This doesn't add anything to a branch.
766
:param line_endings: Either 'binary' or 'native'
767
in binary mode, exact contents are written
768
in native mode, the line endings match the
769
default platform endings.
771
:param transport: A transport to write to, for building trees on
772
VFS's. If the transport is readonly or None,
773
"." is opened automatically.
775
# XXX: It's OK to just create them using forward slashes on windows?
776
if transport is None or transport.is_readonly():
777
transport = get_transport(".")
779
self.assert_(isinstance(name, basestring))
781
transport.mkdir(urlescape(name[:-1]))
783
if line_endings == 'binary':
785
elif line_endings == 'native':
788
raise errors.BzrError('Invalid line ending request %r' % (line_endings,))
789
content = "contents of %s%s" % (name, end)
790
transport.put(urlescape(name), StringIO(content))
792
def build_tree_contents(self, shape):
793
build_tree_contents(shape)
795
def failUnlessExists(self, path):
796
"""Fail unless path, which may be abs or relative, exists."""
797
self.failUnless(osutils.lexists(path))
799
def failIfExists(self, path):
800
"""Fail if path, which may be abs or relative, exists."""
801
self.failIf(osutils.lexists(path))
803
def assertFileEqual(self, content, path):
804
"""Fail if path does not contain 'content'."""
805
self.failUnless(osutils.lexists(path))
806
self.assertEqualDiff(content, open(path, 'r').read())
809
class TestCaseWithTransport(TestCaseInTempDir):
810
"""A test case that provides get_url and get_readonly_url facilities.
812
These back onto two transport servers, one for readonly access and one for
815
If no explicit class is provided for readonly access, a
816
ReadonlyTransportDecorator is used instead which allows the use of non disk
817
based read write transports.
819
If an explicit class is provided for readonly access, that server and the
820
readwrite one must both define get_url() as resolving to os.getcwd().
823
def __init__(self, methodName='testMethod'):
824
super(TestCaseWithTransport, self).__init__(methodName)
825
self.__readonly_server = None
827
self.transport_server = default_transport
828
self.transport_readonly_server = None
830
def get_readonly_url(self, relpath=None):
831
"""Get a URL for the readonly transport.
833
This will either be backed by '.' or a decorator to the transport
834
used by self.get_url()
835
relpath provides for clients to get a path relative to the base url.
836
These should only be downwards relative, not upwards.
838
base = self.get_readonly_server().get_url()
839
if relpath is not None:
840
if not base.endswith('/'):
842
base = base + relpath
845
def get_readonly_server(self):
846
"""Get the server instance for the readonly transport
848
This is useful for some tests with specific servers to do diagnostics.
850
if self.__readonly_server is None:
851
if self.transport_readonly_server is None:
852
# readonly decorator requested
853
# bring up the server
855
self.__readonly_server = ReadonlyServer()
856
self.__readonly_server.setUp(self.__server)
858
self.__readonly_server = self.transport_readonly_server()
859
self.__readonly_server.setUp()
860
self.addCleanup(self.__readonly_server.tearDown)
861
return self.__readonly_server
863
def get_server(self):
864
"""Get the read/write server instance.
866
This is useful for some tests with specific servers that need
869
if self.__server is None:
870
self.__server = self.transport_server()
871
self.__server.setUp()
872
self.addCleanup(self.__server.tearDown)
875
def get_url(self, relpath=None):
876
"""Get a URL for the readwrite transport.
878
This will either be backed by '.' or to an equivalent non-file based
880
relpath provides for clients to get a path relative to the base url.
881
These should only be downwards relative, not upwards.
883
base = self.get_server().get_url()
884
if relpath is not None and relpath != '.':
885
if not base.endswith('/'):
887
base = base + relpath
890
def get_transport(self):
891
"""Return a writeable transport for the test scratch space"""
892
t = get_transport(self.get_url())
893
self.assertFalse(t.is_readonly())
896
def get_readonly_transport(self):
897
"""Return a readonly transport for the test scratch space
899
This can be used to test that operations which should only need
900
readonly access in fact do not try to write.
902
t = get_transport(self.get_readonly_url())
903
self.assertTrue(t.is_readonly())
906
def make_branch(self, relpath, format=None):
907
"""Create a branch on the transport at relpath."""
908
repo = self.make_repository(relpath, format=format)
909
return repo.bzrdir.create_branch()
911
def make_bzrdir(self, relpath, format=None):
913
url = self.get_url(relpath)
914
segments = relpath.split('/')
915
if segments and segments[-1] not in ('', '.'):
916
parent = self.get_url('/'.join(segments[:-1]))
917
t = get_transport(parent)
919
t.mkdir(segments[-1])
920
except errors.FileExists:
923
format=bzrlib.bzrdir.BzrDirFormat.get_default_format()
924
# FIXME: make this use a single transport someday. RBC 20060418
925
return format.initialize_on_transport(get_transport(relpath))
926
except errors.UninitializableFormat:
927
raise TestSkipped("Format %s is not initializable." % format)
929
def make_repository(self, relpath, shared=False, format=None):
930
"""Create a repository on our default transport at relpath."""
931
made_control = self.make_bzrdir(relpath, format=format)
932
return made_control.create_repository(shared=shared)
934
def make_branch_and_tree(self, relpath, format=None):
935
"""Create a branch on the transport and a tree locally.
939
# TODO: always use the local disk path for the working tree,
940
# this obviously requires a format that supports branch references
941
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
943
b = self.make_branch(relpath, format=format)
945
return b.bzrdir.create_workingtree()
946
except errors.NotLocalUrl:
947
# new formats - catch No tree error and create
948
# a branch reference and a checkout.
949
# old formats at that point - raise TestSkipped.
951
return WorkingTreeFormat2().initialize(bzrdir.BzrDir.open(relpath))
953
def assertIsDirectory(self, relpath, transport):
954
"""Assert that relpath within transport is a directory.
956
This may not be possible on all transports; in that case it propagates
957
a TransportNotPossible.
960
mode = transport.stat(relpath).st_mode
961
except errors.NoSuchFile:
962
self.fail("path %s is not a directory; no such file"
964
if not stat.S_ISDIR(mode):
965
self.fail("path %s is not a directory; has mode %#o"
969
class ChrootedTestCase(TestCaseWithTransport):
970
"""A support class that provides readonly urls outside the local namespace.
972
This is done by checking if self.transport_server is a MemoryServer. if it
973
is then we are chrooted already, if it is not then an HttpServer is used
976
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
977
be used without needed to redo it when a different
982
super(ChrootedTestCase, self).setUp()
983
if not self.transport_server == bzrlib.transport.memory.MemoryServer:
984
self.transport_readonly_server = bzrlib.transport.http.HttpServer
987
def filter_suite_by_re(suite, pattern):
989
filter_re = re.compile(pattern)
990
for test in iter_suite_tests(suite):
991
if filter_re.search(test.id()):
996
def run_suite(suite, name='test', verbose=False, pattern=".*",
997
stop_on_failure=False, keep_output=False,
999
TestCaseInTempDir._TEST_NAME = name
1005
pb = progress.ProgressBar()
1006
runner = TextTestRunner(stream=sys.stdout,
1008
verbosity=verbosity,
1009
keep_output=keep_output,
1011
runner.stop_on_failure=stop_on_failure
1013
suite = filter_suite_by_re(suite, pattern)
1014
result = runner.run(suite)
1015
return result.wasSuccessful()
1018
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
1021
test_suite_factory=None):
1022
"""Run the whole test suite under the enhanced runner"""
1023
global default_transport
1024
if transport is None:
1025
transport = default_transport
1026
old_transport = default_transport
1027
default_transport = transport
1029
if test_suite_factory is None:
1030
suite = test_suite()
1032
suite = test_suite_factory()
1033
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
1034
stop_on_failure=stop_on_failure, keep_output=keep_output,
1035
transport=transport)
1037
default_transport = old_transport
1040
def benchmark_suite():
1041
"""Build and return a TestSuite which contains benchmark tests only."""
1046
"""Build and return TestSuite for the whole of bzrlib.
1048
This function can be replaced if you need to change the default test
1049
suite on a global basis, but it is not encouraged.
1051
from doctest import DocTestSuite
1053
global MODULES_TO_DOCTEST
1056
'bzrlib.tests.test_ancestry',
1057
'bzrlib.tests.test_api',
1058
'bzrlib.tests.test_bad_files',
1059
'bzrlib.tests.test_branch',
1060
'bzrlib.tests.test_bzrdir',
1061
'bzrlib.tests.test_command',
1062
'bzrlib.tests.test_commit',
1063
'bzrlib.tests.test_commit_merge',
1064
'bzrlib.tests.test_config',
1065
'bzrlib.tests.test_conflicts',
1066
'bzrlib.tests.test_decorators',
1067
'bzrlib.tests.test_diff',
1068
'bzrlib.tests.test_doc_generate',
1069
'bzrlib.tests.test_errors',
1070
'bzrlib.tests.test_escaped_store',
1071
'bzrlib.tests.test_fetch',
1072
'bzrlib.tests.test_gpg',
1073
'bzrlib.tests.test_graph',
1074
'bzrlib.tests.test_hashcache',
1075
'bzrlib.tests.test_http',
1076
'bzrlib.tests.test_identitymap',
1077
'bzrlib.tests.test_inv',
1078
'bzrlib.tests.test_knit',
1079
'bzrlib.tests.test_lockdir',
1080
'bzrlib.tests.test_lockable_files',
1081
'bzrlib.tests.test_log',
1082
'bzrlib.tests.test_merge',
1083
'bzrlib.tests.test_merge3',
1084
'bzrlib.tests.test_merge_core',
1085
'bzrlib.tests.test_missing',
1086
'bzrlib.tests.test_msgeditor',
1087
'bzrlib.tests.test_nonascii',
1088
'bzrlib.tests.test_options',
1089
'bzrlib.tests.test_osutils',
1090
'bzrlib.tests.test_patch',
1091
'bzrlib.tests.test_permissions',
1092
'bzrlib.tests.test_plugins',
1093
'bzrlib.tests.test_progress',
1094
'bzrlib.tests.test_reconcile',
1095
'bzrlib.tests.test_repository',
1096
'bzrlib.tests.test_revision',
1097
'bzrlib.tests.test_revisionnamespaces',
1098
'bzrlib.tests.test_revprops',
1099
'bzrlib.tests.test_rio',
1100
'bzrlib.tests.test_sampler',
1101
'bzrlib.tests.test_selftest',
1102
'bzrlib.tests.test_setup',
1103
'bzrlib.tests.test_sftp_transport',
1104
'bzrlib.tests.test_smart_add',
1105
'bzrlib.tests.test_source',
1106
'bzrlib.tests.test_store',
1107
'bzrlib.tests.test_symbol_versioning',
1108
'bzrlib.tests.test_testament',
1109
'bzrlib.tests.test_textfile',
1110
'bzrlib.tests.test_textmerge',
1111
'bzrlib.tests.test_trace',
1112
'bzrlib.tests.test_transactions',
1113
'bzrlib.tests.test_transform',
1114
'bzrlib.tests.test_transport',
1115
'bzrlib.tests.test_tsort',
1116
'bzrlib.tests.test_tuned_gzip',
1117
'bzrlib.tests.test_ui',
1118
'bzrlib.tests.test_upgrade',
1119
'bzrlib.tests.test_versionedfile',
1120
'bzrlib.tests.test_weave',
1121
'bzrlib.tests.test_whitebox',
1122
'bzrlib.tests.test_workingtree',
1123
'bzrlib.tests.test_xml',
1125
test_transport_implementations = [
1126
'bzrlib.tests.test_transport_implementations']
1129
# python2.4's TestLoader.loadTestsFromNames gives very poor
1130
# errors if it fails to load a named module - no indication of what's
1131
# actually wrong, just "no such module". We should probably override that
1132
# class, but for the moment just load them ourselves. (mbp 20051202)
1133
loader = TestLoader()
1134
from bzrlib.transport import TransportTestProviderAdapter
1135
adapter = TransportTestProviderAdapter()
1136
adapt_modules(test_transport_implementations, adapter, loader, suite)
1137
for mod_name in testmod_names:
1138
mod = _load_module_by_name(mod_name)
1139
suite.addTest(loader.loadTestsFromModule(mod))
1140
for package in packages_to_test():
1141
suite.addTest(package.test_suite())
1142
for m in MODULES_TO_TEST:
1143
suite.addTest(loader.loadTestsFromModule(m))
1144
for m in (MODULES_TO_DOCTEST):
1145
suite.addTest(DocTestSuite(m))
1146
for name, plugin in bzrlib.plugin.all_plugins().items():
1147
if getattr(plugin, 'test_suite', None) is not None:
1148
suite.addTest(plugin.test_suite())
1152
def adapt_modules(mods_list, adapter, loader, suite):
1153
"""Adapt the modules in mods_list using adapter and add to suite."""
1154
for mod_name in mods_list:
1155
mod = _load_module_by_name(mod_name)
1156
for test in iter_suite_tests(loader.loadTestsFromModule(mod)):
1157
suite.addTests(adapter.adapt(test))
1160
def _load_module_by_name(mod_name):
1161
parts = mod_name.split('.')
1162
module = __import__(mod_name)
1164
# for historical reasons python returns the top-level module even though
1165
# it loads the submodule; we need to walk down to get the one we want.
1167
module = getattr(module, parts.pop(0))