1
# Copyright (C) 2005 by Canonical Ltd
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
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.
18
30
from cStringIO import StringIO
36
from pprint import pformat
40
from subprocess import Popen, PIPE
29
58
import bzrlib.commands
59
import bzrlib.timestamp
61
import bzrlib.inventory
62
import bzrlib.iterablefile
67
# lsprof not available
69
from bzrlib.merge import merge_inner
73
from bzrlib.revision import common_ancestor
75
from bzrlib import symbol_versioning
30
76
import bzrlib.trace
32
from bzrlib.selftest import TestUtil
33
from bzrlib.selftest.TestUtil import TestLoader, TestSuite
77
from bzrlib.transport import get_transport
78
import bzrlib.transport
79
from bzrlib.transport.local import LocalURLServer
80
from bzrlib.transport.memory import MemoryServer
81
from bzrlib.transport.readonly import ReadonlyServer
82
from bzrlib.trace import mutter, note
83
from bzrlib.tests import TestUtil
84
from bzrlib.tests.HttpServer import HttpServer
85
from bzrlib.tests.TestUtil import (
89
from bzrlib.tests.treeshape import build_tree_contents
90
from bzrlib.workingtree import WorkingTree, WorkingTreeFormat2
92
default_transport = LocalURLServer
36
94
MODULES_TO_TEST = []
37
MODULES_TO_DOCTEST = []
39
from logging import debug, warning, error
43
class EarlyStoppingTestResultAdapter(object):
44
"""An adapter for TestResult to stop at the first first failure or error"""
46
def __init__(self, result):
49
def addError(self, test, err):
50
self._result.addError(test, err)
53
def addFailure(self, test, err):
54
self._result.addFailure(test, err)
57
def __getattr__(self, name):
58
return getattr(self._result, name)
60
def __setattr__(self, name, value):
62
object.__setattr__(self, name, value)
63
return setattr(self._result, name, value)
66
class _MyResult(unittest._TextTestResult):
70
No special behaviour for now.
95
MODULES_TO_DOCTEST = [
107
NUMBERED_DIRS = False # dirs kind for TestCaseInTempDir (numbered or named)
110
def packages_to_test():
111
"""Return a list of packages to test.
113
The packages are not globally imported so that import failures are
114
triggered when running selftest, not when importing the command.
117
import bzrlib.tests.blackbox
118
import bzrlib.tests.branch_implementations
119
import bzrlib.tests.bzrdir_implementations
120
import bzrlib.tests.interrepository_implementations
121
import bzrlib.tests.interversionedfile_implementations
122
import bzrlib.tests.intertree_implementations
123
import bzrlib.tests.repository_implementations
124
import bzrlib.tests.revisionstore_implementations
125
import bzrlib.tests.tree_implementations
126
import bzrlib.tests.workingtree_implementations
129
bzrlib.tests.blackbox,
130
bzrlib.tests.branch_implementations,
131
bzrlib.tests.bzrdir_implementations,
132
bzrlib.tests.interrepository_implementations,
133
bzrlib.tests.interversionedfile_implementations,
134
bzrlib.tests.intertree_implementations,
135
bzrlib.tests.repository_implementations,
136
bzrlib.tests.revisionstore_implementations,
137
bzrlib.tests.tree_implementations,
138
bzrlib.tests.workingtree_implementations,
142
class ExtendedTestResult(unittest._TextTestResult):
143
"""Accepts, reports and accumulates the results of running tests.
145
Compared to this unittest version this class adds support for profiling,
146
benchmarking, stopping as soon as a test fails, and skipping tests.
147
There are further-specialized subclasses for different types of display.
152
def __init__(self, stream, descriptions, verbosity,
156
"""Construct new TestResult.
158
:param bench_history: Optionally, a writable file object to accumulate
161
unittest._TextTestResult.__init__(self, stream, descriptions, verbosity)
162
if bench_history is not None:
163
from bzrlib.version import _get_bzr_source_tree
164
src_tree = _get_bzr_source_tree()
167
revision_id = src_tree.get_parent_ids()[0]
169
# XXX: if this is a brand new tree, do the same as if there
173
# XXX: If there's no branch, what should we do?
175
bench_history.write("--date %s %s\n" % (time.time(), revision_id))
176
self._bench_history = bench_history
177
self.ui = ui.ui_factory
178
self.num_tests = num_tests
180
self.failure_count = 0
183
self._overall_start_time = time.time()
185
def extractBenchmarkTime(self, testCase):
186
"""Add a benchmark time for the current test case."""
187
self._benchmarkTime = getattr(testCase, "_benchtime", None)
189
def _elapsedTestTimeString(self):
190
"""Return a time string for the overall time the current test has taken."""
191
return self._formatTime(time.time() - self._start_time)
193
def _testTimeString(self):
194
if self._benchmarkTime is not None:
196
self._formatTime(self._benchmarkTime),
197
self._elapsedTestTimeString())
199
return " %s" % self._elapsedTestTimeString()
201
def _formatTime(self, seconds):
202
"""Format seconds as milliseconds with leading spaces."""
203
# some benchmarks can take thousands of seconds to run, so we need 8
205
return "%8dms" % (1000 * seconds)
207
def _shortened_test_description(self, test):
209
what = re.sub(r'^bzrlib\.(tests|benchmarks)\.', '', what)
73
212
def startTest(self, test):
74
213
unittest.TestResult.startTest(self, test)
75
# TODO: Maybe show test.shortDescription somewhere?
76
what = test.shortDescription() or test.id()
78
self.stream.write('%-70.70s' % what)
214
self.report_test_start(test)
215
test.number = self.count
216
self._recordTestStartTime()
218
def _recordTestStartTime(self):
219
"""Record that a test has started."""
220
self._start_time = time.time()
81
222
def addError(self, test, err):
82
super(_MyResult, self).addError(test, err)
223
if isinstance(err[1], TestSkipped):
224
return self.addSkipped(test, err)
225
unittest.TestResult.addError(self, test, err)
226
# We can only do this if we have one of our TestCases, not if
228
setKeepLogfile = getattr(test, 'setKeepLogfile', None)
229
if setKeepLogfile is not None:
231
self.extractBenchmarkTime(test)
232
self.report_error(test, err)
85
236
def addFailure(self, test, err):
86
super(_MyResult, self).addFailure(test, err)
237
unittest.TestResult.addFailure(self, test, err)
238
# We can only do this if we have one of our TestCases, not if
240
setKeepLogfile = getattr(test, 'setKeepLogfile', None)
241
if setKeepLogfile is not None:
243
self.extractBenchmarkTime(test)
244
self.report_failure(test, err)
89
248
def addSuccess(self, test):
91
self.stream.writeln('OK')
93
self.stream.write('~')
249
self.extractBenchmarkTime(test)
250
if self._bench_history is not None:
251
if self._benchmarkTime is not None:
252
self._bench_history.write("%s %s\n" % (
253
self._formatTime(self._benchmarkTime),
255
self.report_success(test)
95
256
unittest.TestResult.addSuccess(self, test)
258
def addSkipped(self, test, skip_excinfo):
259
self.extractBenchmarkTime(test)
260
self.report_skip(test, skip_excinfo)
261
# seems best to treat this as success from point-of-view of unittest
262
# -- it actually does nothing so it barely matters :)
265
except KeyboardInterrupt:
268
self.addError(test, test.__exc_info())
270
unittest.TestResult.addSuccess(self, test)
97
272
def printErrorList(self, flavour, errors):
98
273
for test, err in errors:
99
274
self.stream.writeln(self.separator1)
100
self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
101
if hasattr(test, '_get_log'):
102
self.stream.writeln()
103
self.stream.writeln('log from this test:')
275
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
276
if getattr(test, '_get_log', None) is not None:
278
print >>self.stream, \
279
('vvvv[log from %s]' % test.id()).ljust(78,'-')
104
280
print >>self.stream, test._get_log()
281
print >>self.stream, \
282
('^^^^[log from %s]' % test.id()).ljust(78,'-')
105
283
self.stream.writeln(self.separator2)
106
284
self.stream.writeln("%s" % err)
109
class TextTestRunner(unittest.TextTestRunner):
111
def _makeResult(self):
112
result = _MyResult(self.stream, self.descriptions, self.verbosity)
113
return EarlyStoppingTestResultAdapter(result)
289
def report_cleaning_up(self):
292
def report_success(self, test):
296
class TextTestResult(ExtendedTestResult):
297
"""Displays progress and results of tests in text form"""
299
def __init__(self, *args, **kw):
300
ExtendedTestResult.__init__(self, *args, **kw)
301
self.pb = self.ui.nested_progress_bar()
302
self.pb.show_pct = False
303
self.pb.show_spinner = False
304
self.pb.show_eta = False,
305
self.pb.show_count = False
306
self.pb.show_bar = False
308
def report_starting(self):
309
self.pb.update('[test 0/%d] starting...' % (self.num_tests))
311
def _progress_prefix_text(self):
312
a = '[%d' % self.count
313
if self.num_tests is not None:
314
a +='/%d' % self.num_tests
315
a += ' in %ds' % (time.time() - self._overall_start_time)
317
a += ', %d errors' % self.error_count
318
if self.failure_count:
319
a += ', %d failed' % self.failure_count
321
a += ', %d skipped' % self.skip_count
325
def report_test_start(self, test):
328
self._progress_prefix_text()
330
+ self._shortened_test_description(test))
332
def _test_description(self, test):
334
return '#%d %s' % (self.count,
335
self._shortened_test_description(test))
337
return self._shortened_test_description(test)
339
def report_error(self, test, err):
340
self.error_count += 1
341
self.pb.note('ERROR: %s\n %s\n',
342
self._test_description(test),
346
def report_failure(self, test, err):
347
self.failure_count += 1
348
self.pb.note('FAIL: %s\n %s\n',
349
self._test_description(test),
353
def report_skip(self, test, skip_excinfo):
356
# at the moment these are mostly not things we can fix
357
# and so they just produce stipple; use the verbose reporter
360
# show test and reason for skip
361
self.pb.note('SKIP: %s\n %s\n',
362
self._shortened_test_description(test),
365
# since the class name was left behind in the still-visible
367
self.pb.note('SKIP: %s', skip_excinfo[1])
369
def report_cleaning_up(self):
370
self.pb.update('cleaning up...')
376
class VerboseTestResult(ExtendedTestResult):
377
"""Produce long output, with one line per test run plus times"""
379
def _ellipsize_to_right(self, a_string, final_width):
380
"""Truncate and pad a string, keeping the right hand side"""
381
if len(a_string) > final_width:
382
result = '...' + a_string[3-final_width:]
385
return result.ljust(final_width)
387
def report_starting(self):
388
self.stream.write('running %d tests...\n' % self.num_tests)
390
def report_test_start(self, test):
392
name = self._shortened_test_description(test)
393
# width needs space for 6 char status, plus 1 for slash, plus 2 10-char
394
# numbers, plus a trailing blank
395
# when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on space
397
self.stream.write('%5d ' % self.count)
398
self.stream.write(self._ellipsize_to_right(name,
399
osutils.terminal_width()-36))
401
self.stream.write(self._ellipsize_to_right(name,
402
osutils.terminal_width()-30))
405
def _error_summary(self, err):
409
return '%s%s' % (indent, err[1])
411
def report_error(self, test, err):
412
self.error_count += 1
413
self.stream.writeln('ERROR %s\n%s'
414
% (self._testTimeString(),
415
self._error_summary(err)))
417
def report_failure(self, test, err):
418
self.failure_count += 1
419
self.stream.writeln(' FAIL %s\n%s'
420
% (self._testTimeString(),
421
self._error_summary(err)))
423
def report_success(self, test):
424
self.stream.writeln(' OK %s' % self._testTimeString())
425
for bench_called, stats in getattr(test, '_benchcalls', []):
427
self.stream.write(' ' * 6)
428
self.stream.writeln('LSProf output for %s(%s, %s)' % bench_called)
429
stats.pprint(file=self.stream)
432
def report_skip(self, test, skip_excinfo):
434
self.stream.writeln(' SKIP %s\n%s'
435
% (self._testTimeString(),
436
self._error_summary(skip_excinfo)))
439
class TextTestRunner(object):
440
stop_on_failure = False
448
self.stream = unittest._WritelnDecorator(stream)
449
self.descriptions = descriptions
450
self.verbosity = verbosity
451
self.keep_output = keep_output
452
self._bench_history = bench_history
455
"Run the given test case or test suite."
456
startTime = time.time()
457
if self.verbosity == 1:
458
result_class = TextTestResult
459
elif self.verbosity >= 2:
460
result_class = VerboseTestResult
461
result = result_class(self.stream,
464
bench_history=self._bench_history,
465
num_tests=test.countTestCases(),
467
result.stop_early = self.stop_on_failure
468
result.report_starting()
470
stopTime = time.time()
471
timeTaken = stopTime - startTime
473
self.stream.writeln(result.separator2)
474
run = result.testsRun
475
self.stream.writeln("Ran %d test%s in %.3fs" %
476
(run, run != 1 and "s" or "", timeTaken))
477
self.stream.writeln()
478
if not result.wasSuccessful():
479
self.stream.write("FAILED (")
480
failed, errored = map(len, (result.failures, result.errors))
482
self.stream.write("failures=%d" % failed)
484
if failed: self.stream.write(", ")
485
self.stream.write("errors=%d" % errored)
486
self.stream.writeln(")")
488
self.stream.writeln("OK")
489
if result.skip_count > 0:
490
skipped = result.skip_count
491
self.stream.writeln('%d test%s skipped' %
492
(skipped, skipped != 1 and "s" or ""))
493
result.report_cleaning_up()
494
# This is still a little bogus,
495
# but only a little. Folk not using our testrunner will
496
# have to delete their temp directories themselves.
497
test_root = TestCaseWithMemoryTransport.TEST_ROOT
498
if result.wasSuccessful() or not self.keep_output:
499
if test_root is not None:
500
# If LANG=C we probably have created some bogus paths
501
# which rmtree(unicode) will fail to delete
502
# so make sure we are using rmtree(str) to delete everything
503
# except on win32, where rmtree(str) will fail
504
# since it doesn't have the property of byte-stream paths
505
# (they are either ascii or mbcs)
506
if sys.platform == 'win32':
507
# make sure we are using the unicode win32 api
508
test_root = unicode(test_root)
510
test_root = test_root.encode(
511
sys.getfilesystemencoding())
513
osutils.rmtree(test_root)
515
if sys.platform == 'win32' and e.errno == errno.EACCES:
516
print >>sys.stderr, ('Permission denied: '
517
'unable to remove testing dir '
518
'%s' % os.path.basename(test_root))
522
note("Failed tests working directories are in '%s'\n", test_root)
523
TestCaseWithMemoryTransport.TEST_ROOT = None
116
528
def iter_suite_tests(suite):
143
646
Error and debug log messages are redirected from their usual
144
647
location into a temporary file, the contents of which can be
145
retrieved by _get_log().
648
retrieved by _get_log(). We use a real OS file, not an in-memory object,
649
so that it can also capture file IO. When the test completes this file
650
is read into memory and removed from disk.
147
652
There are also convenience functions to invoke bzr's command-line
148
routine, and to build and check bzr trees."""
653
routine, and to build and check bzr trees.
655
In addition to the usual method of overriding tearDown(), this class also
656
allows subclasses to register functions into the _cleanups list, which is
657
run in order as the object is torn down. It's less likely this will be
658
accidentally overlooked.
661
_log_file_name = None
663
_keep_log_file = False
664
# record lsprof data when performing benchmark calls.
665
_gather_lsprof_in_benchmarks = False
667
def __init__(self, methodName='testMethod'):
668
super(TestCase, self).__init__(methodName)
153
672
unittest.TestCase.setUp(self)
673
self._cleanEnvironment()
154
674
bzrlib.trace.disable_default_logging()
155
self._enable_file_logging()
158
def _enable_file_logging(self):
677
self._benchcalls = []
678
self._benchtime = None
679
# prevent hooks affecting tests
680
self._preserved_hooks = bzrlib.branch.Branch.hooks
681
self.addCleanup(self._restoreHooks)
682
# this list of hooks must be kept in sync with the defaults
684
bzrlib.branch.Branch.hooks = bzrlib.branch.BranchHooks()
686
def _silenceUI(self):
687
"""Turn off UI for duration of test"""
688
# by default the UI is off; tests can turn it on if they want it.
689
saved = ui.ui_factory
691
ui.ui_factory = saved
692
ui.ui_factory = ui.SilentUIFactory()
693
self.addCleanup(_restore)
695
def _ndiff_strings(self, a, b):
696
"""Return ndiff between two strings containing lines.
698
A trailing newline is added if missing to make the strings
700
if b and b[-1] != '\n':
702
if a and a[-1] != '\n':
704
difflines = difflib.ndiff(a.splitlines(True),
706
linejunk=lambda x: False,
707
charjunk=lambda x: False)
708
return ''.join(difflines)
710
def assertEqual(self, a, b, message=''):
715
raise AssertionError("%snot equal:\na = %s\nb = %s\n"
717
pformat(a, indent=4), pformat(b, indent=4)))
719
assertEquals = assertEqual
721
def assertEqualDiff(self, a, b, message=None):
722
"""Assert two texts are equal, if not raise an exception.
724
This is intended for use with multi-line strings where it can
725
be hard to find the differences by eye.
727
# TODO: perhaps override assertEquals to call this for strings?
731
message = "texts not equal:\n"
732
raise AssertionError(message +
733
self._ndiff_strings(a, b))
735
def assertEqualMode(self, mode, mode_test):
736
self.assertEqual(mode, mode_test,
737
'mode mismatch %o != %o' % (mode, mode_test))
739
def assertStartsWith(self, s, prefix):
740
if not s.startswith(prefix):
741
raise AssertionError('string %r does not start with %r' % (s, prefix))
743
def assertEndsWith(self, s, suffix):
744
"""Asserts that s ends with suffix."""
745
if not s.endswith(suffix):
746
raise AssertionError('string %r does not end with %r' % (s, suffix))
748
def assertContainsRe(self, haystack, needle_re):
749
"""Assert that a contains something matching a regular expression."""
750
if not re.search(needle_re, haystack):
751
raise AssertionError('pattern "%r" not found in "%r"'
752
% (needle_re, haystack))
754
def assertNotContainsRe(self, haystack, needle_re):
755
"""Assert that a does not match a regular expression"""
756
if re.search(needle_re, haystack):
757
raise AssertionError('pattern "%s" found in "%s"'
758
% (needle_re, haystack))
760
def assertSubset(self, sublist, superlist):
761
"""Assert that every entry in sublist is present in superlist."""
763
for entry in sublist:
764
if entry not in superlist:
765
missing.append(entry)
767
raise AssertionError("value(s) %r not present in container %r" %
768
(missing, superlist))
770
def assertListRaises(self, excClass, func, *args, **kwargs):
771
"""Fail unless excClass is raised when the iterator from func is used.
773
Many functions can return generators this makes sure
774
to wrap them in a list() call to make sure the whole generator
775
is run, and that the proper exception is raised.
778
list(func(*args, **kwargs))
782
if getattr(excClass,'__name__', None) is not None:
783
excName = excClass.__name__
785
excName = str(excClass)
786
raise self.failureException, "%s not raised" % excName
788
def assertIs(self, left, right, message=None):
789
if not (left is right):
790
if message is not None:
791
raise AssertionError(message)
793
raise AssertionError("%r is not %r." % (left, right))
795
def assertIsNot(self, left, right, message=None):
797
if message is not None:
798
raise AssertionError(message)
800
raise AssertionError("%r is %r." % (left, right))
802
def assertTransportMode(self, transport, path, mode):
803
"""Fail if a path does not have mode mode.
805
If modes are not supported on this transport, the assertion is ignored.
807
if not transport._can_roundtrip_unix_modebits():
809
path_stat = transport.stat(path)
810
actual_mode = stat.S_IMODE(path_stat.st_mode)
811
self.assertEqual(mode, actual_mode,
812
'mode of %r incorrect (%o != %o)' % (path, mode, actual_mode))
814
def assertIsInstance(self, obj, kls):
815
"""Fail if obj is not an instance of kls"""
816
if not isinstance(obj, kls):
817
self.fail("%r is an instance of %s rather than %s" % (
818
obj, obj.__class__, kls))
820
def _capture_warnings(self, a_callable, *args, **kwargs):
821
"""A helper for callDeprecated and applyDeprecated.
823
:param a_callable: A callable to call.
824
:param args: The positional arguments for the callable
825
:param kwargs: The keyword arguments for the callable
826
:return: A tuple (warnings, result). result is the result of calling
827
a_callable(*args, **kwargs).
830
def capture_warnings(msg, cls=None, stacklevel=None):
831
# we've hooked into a deprecation specific callpath,
832
# only deprecations should getting sent via it.
833
self.assertEqual(cls, DeprecationWarning)
834
local_warnings.append(msg)
835
original_warning_method = symbol_versioning.warn
836
symbol_versioning.set_warning_method(capture_warnings)
838
result = a_callable(*args, **kwargs)
840
symbol_versioning.set_warning_method(original_warning_method)
841
return (local_warnings, result)
843
def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
844
"""Call a deprecated callable without warning the user.
846
:param deprecation_format: The deprecation format that the callable
847
should have been deprecated with. This is the same type as the
848
parameter to deprecated_method/deprecated_function. If the
849
callable is not deprecated with this format, an assertion error
851
:param a_callable: A callable to call. This may be a bound method or
852
a regular function. It will be called with *args and **kwargs.
853
:param args: The positional arguments for the callable
854
:param kwargs: The keyword arguments for the callable
855
:return: The result of a_callable(*args, **kwargs)
857
call_warnings, result = self._capture_warnings(a_callable,
859
expected_first_warning = symbol_versioning.deprecation_string(
860
a_callable, deprecation_format)
861
if len(call_warnings) == 0:
862
self.fail("No deprecation warning generated by call to %s" %
864
self.assertEqual(expected_first_warning, call_warnings[0])
867
def callDeprecated(self, expected, callable, *args, **kwargs):
868
"""Assert that a callable is deprecated in a particular way.
870
This is a very precise test for unusual requirements. The
871
applyDeprecated helper function is probably more suited for most tests
872
as it allows you to simply specify the deprecation format being used
873
and will ensure that that is issued for the function being called.
875
:param expected: a list of the deprecation warnings expected, in order
876
:param callable: The callable to call
877
:param args: The positional arguments for the callable
878
:param kwargs: The keyword arguments for the callable
880
call_warnings, result = self._capture_warnings(callable,
882
self.assertEqual(expected, call_warnings)
885
def _startLogFile(self):
886
"""Send bzr and test log messages to a temporary file.
888
The file is removed as the test is torn down.
159
890
fileno, name = tempfile.mkstemp(suffix='.log', prefix='testbzr')
161
891
self._log_file = os.fdopen(fileno, 'w+')
163
hdlr = logging.StreamHandler(self._log_file)
164
hdlr.setLevel(logging.DEBUG)
165
hdlr.setFormatter(logging.Formatter('%(levelname)8s %(message)s'))
166
logging.getLogger('').addHandler(hdlr)
167
logging.getLogger('').setLevel(logging.DEBUG)
168
self._log_hdlr = hdlr
169
debug('opened log file %s', name)
892
self._log_nonce = bzrlib.trace.enable_test_log(self._log_file)
171
893
self._log_file_name = name
174
logging.getLogger('').removeHandler(self._log_hdlr)
175
bzrlib.trace.enable_default_logging()
176
logging.debug('%s teardown', self.id())
894
self.addCleanup(self._finishLogFile)
896
def _finishLogFile(self):
897
"""Finished with the log file.
899
Close the file and delete it, unless setKeepLogfile was called.
901
if self._log_file is None:
903
bzrlib.trace.disable_test_log(self._log_nonce)
177
904
self._log_file.close()
905
self._log_file = None
906
if not self._keep_log_file:
907
os.remove(self._log_file_name)
908
self._log_file_name = None
910
def setKeepLogfile(self):
911
"""Make the logfile not be deleted when _finishLogFile is called."""
912
self._keep_log_file = True
914
def addCleanup(self, callable):
915
"""Arrange to run a callable when this case is torn down.
917
Callables are run in the reverse of the order they are registered,
918
ie last-in first-out.
920
if callable in self._cleanups:
921
raise ValueError("cleanup function %r already registered on %s"
923
self._cleanups.append(callable)
925
def _cleanEnvironment(self):
927
'BZR_HOME': None, # Don't inherit BZR_HOME to all the tests.
929
'APPDATA': None, # bzr now use Win32 API and don't rely on APPDATA
931
'BZREMAIL': None, # may still be present in the environment
933
'BZR_PROGRESS_BAR': None,
943
# Nobody cares about these ones AFAIK. So far at
944
# least. If you do (care), please update this comment
950
self.addCleanup(self._restoreEnvironment)
951
for name, value in new_env.iteritems():
952
self._captureVar(name, value)
954
def _captureVar(self, name, newvalue):
955
"""Set an environment variable, and reset it when finished."""
956
self.__old_env[name] = osutils.set_or_unset_env(name, newvalue)
958
def _restoreEnvironment(self):
959
for name, value in self.__old_env.iteritems():
960
osutils.set_or_unset_env(name, value)
962
def _restoreHooks(self):
963
bzrlib.branch.Branch.hooks = self._preserved_hooks
178
967
unittest.TestCase.tearDown(self)
969
def time(self, callable, *args, **kwargs):
970
"""Run callable and accrue the time it takes to the benchmark time.
972
If lsprofiling is enabled (i.e. by --lsprof-time to bzr selftest) then
973
this will cause lsprofile statistics to be gathered and stored in
976
if self._benchtime is None:
980
if not self._gather_lsprof_in_benchmarks:
981
return callable(*args, **kwargs)
983
# record this benchmark
984
ret, stats = bzrlib.lsprof.profile(callable, *args, **kwargs)
986
self._benchcalls.append(((callable, args, kwargs), stats))
989
self._benchtime += time.time() - start
991
def _runCleanups(self):
992
"""Run registered cleanup functions.
994
This should only be called from TestCase.tearDown.
996
# TODO: Perhaps this should keep running cleanups even if
998
for cleanup_fn in reversed(self._cleanups):
180
1001
def log(self, *args):
184
"""Return as a string the log for this test"""
185
return open(self._log_file_name).read()
188
def capture(self, cmd):
1004
def _get_log(self, keep_log_file=False):
1005
"""Return as a string the log for this test. If the file is still
1006
on disk and keep_log_file=False, delete the log file and store the
1007
content in self._log_contents."""
1008
# flush the log file, to get all content
1010
bzrlib.trace._trace_file.flush()
1011
if self._log_contents:
1012
return self._log_contents
1013
if self._log_file_name is not None:
1014
logfile = open(self._log_file_name)
1016
log_contents = logfile.read()
1019
if not keep_log_file:
1020
self._log_contents = log_contents
1022
os.remove(self._log_file_name)
1024
if sys.platform == 'win32' and e.errno == errno.EACCES:
1025
print >>sys.stderr, ('Unable to delete log file '
1026
' %r' % self._log_file_name)
1031
return "DELETED log file to reduce memory footprint"
1033
def capture(self, cmd, retcode=0):
189
1034
"""Shortcut that splits cmd into words, runs, and returns stdout"""
190
return self.run_bzr_captured(cmd.split())[0]
1035
return self.run_bzr_captured(cmd.split(), retcode=retcode)[0]
192
def run_bzr_captured(self, argv, retcode=0):
193
"""Invoke bzr and return (result, stdout, stderr).
1037
def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None,
1039
"""Invoke bzr and return (stdout, stderr).
195
1041
Useful for code that wants to check the contents of the
196
1042
output, the way error messages are presented, etc.
243
1115
This sends the stdout/stderr results into the test's log,
244
1116
where it may be useful for debugging. See also run_captured.
1118
:param stdin: A string to be used as stdin for the command.
1119
:param retcode: The status code the command should return
1120
:param working_dir: The directory to run the command in
246
1122
retcode = kwargs.pop('retcode', 0)
247
return self.run_bzr_captured(args, retcode)
1123
encoding = kwargs.pop('encoding', None)
1124
stdin = kwargs.pop('stdin', None)
1125
working_dir = kwargs.pop('working_dir', None)
1126
return self.run_bzr_captured(args, retcode=retcode, encoding=encoding,
1127
stdin=stdin, working_dir=working_dir)
1129
def run_bzr_decode(self, *args, **kwargs):
1130
if 'encoding' in kwargs:
1131
encoding = kwargs['encoding']
1133
encoding = bzrlib.user_encoding
1134
return self.run_bzr(*args, **kwargs)[0].decode(encoding)
1136
def run_bzr_error(self, error_regexes, *args, **kwargs):
1137
"""Run bzr, and check that stderr contains the supplied regexes
1139
:param error_regexes: Sequence of regular expressions which
1140
must each be found in the error output. The relative ordering
1142
:param args: command-line arguments for bzr
1143
:param kwargs: Keyword arguments which are interpreted by run_bzr
1144
This function changes the default value of retcode to be 3,
1145
since in most cases this is run when you expect bzr to fail.
1146
:return: (out, err) The actual output of running the command (in case you
1147
want to do more inspection)
1150
# Make sure that commit is failing because there is nothing to do
1151
self.run_bzr_error(['no changes to commit'],
1152
'commit', '-m', 'my commit comment')
1153
# Make sure --strict is handling an unknown file, rather than
1154
# giving us the 'nothing to do' error
1155
self.build_tree(['unknown'])
1156
self.run_bzr_error(['Commit refused because there are unknown files'],
1157
'commit', '--strict', '-m', 'my commit comment')
1159
kwargs.setdefault('retcode', 3)
1160
out, err = self.run_bzr(*args, **kwargs)
1161
for regex in error_regexes:
1162
self.assertContainsRe(err, regex)
1165
def run_bzr_subprocess(self, *args, **kwargs):
1166
"""Run bzr in a subprocess for testing.
1168
This starts a new Python interpreter and runs bzr in there.
1169
This should only be used for tests that have a justifiable need for
1170
this isolation: e.g. they are testing startup time, or signal
1171
handling, or early startup code, etc. Subprocess code can't be
1172
profiled or debugged so easily.
1174
:param retcode: The status code that is expected. Defaults to 0. If
1175
None is supplied, the status code is not checked.
1176
:param env_changes: A dictionary which lists changes to environment
1177
variables. A value of None will unset the env variable.
1178
The values must be strings. The change will only occur in the
1179
child, so you don't need to fix the environment after running.
1180
:param universal_newlines: Convert CRLF => LF
1181
:param allow_plugins: By default the subprocess is run with
1182
--no-plugins to ensure test reproducibility. Also, it is possible
1183
for system-wide plugins to create unexpected output on stderr,
1184
which can cause unnecessary test failures.
1186
env_changes = kwargs.get('env_changes', {})
1187
working_dir = kwargs.get('working_dir', None)
1188
allow_plugins = kwargs.get('allow_plugins', False)
1189
process = self.start_bzr_subprocess(args, env_changes=env_changes,
1190
working_dir=working_dir,
1191
allow_plugins=allow_plugins)
1192
# We distinguish between retcode=None and retcode not passed.
1193
supplied_retcode = kwargs.get('retcode', 0)
1194
return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
1195
universal_newlines=kwargs.get('universal_newlines', False),
1198
def start_bzr_subprocess(self, process_args, env_changes=None,
1199
skip_if_plan_to_signal=False,
1201
allow_plugins=False):
1202
"""Start bzr in a subprocess for testing.
1204
This starts a new Python interpreter and runs bzr in there.
1205
This should only be used for tests that have a justifiable need for
1206
this isolation: e.g. they are testing startup time, or signal
1207
handling, or early startup code, etc. Subprocess code can't be
1208
profiled or debugged so easily.
1210
:param process_args: a list of arguments to pass to the bzr executable,
1211
for example `['--version']`.
1212
:param env_changes: A dictionary which lists changes to environment
1213
variables. A value of None will unset the env variable.
1214
The values must be strings. The change will only occur in the
1215
child, so you don't need to fix the environment after running.
1216
:param skip_if_plan_to_signal: raise TestSkipped when true and os.kill
1218
:param allow_plugins: If False (default) pass --no-plugins to bzr.
1220
:returns: Popen object for the started process.
1222
if skip_if_plan_to_signal:
1223
if not getattr(os, 'kill', None):
1224
raise TestSkipped("os.kill not available.")
1226
if env_changes is None:
1230
def cleanup_environment():
1231
for env_var, value in env_changes.iteritems():
1232
old_env[env_var] = osutils.set_or_unset_env(env_var, value)
1234
def restore_environment():
1235
for env_var, value in old_env.iteritems():
1236
osutils.set_or_unset_env(env_var, value)
1238
bzr_path = self.get_bzr_path()
1241
if working_dir is not None:
1242
cwd = osutils.getcwd()
1243
os.chdir(working_dir)
1246
# win32 subprocess doesn't support preexec_fn
1247
# so we will avoid using it on all platforms, just to
1248
# make sure the code path is used, and we don't break on win32
1249
cleanup_environment()
1250
command = [sys.executable, bzr_path]
1251
if not allow_plugins:
1252
command.append('--no-plugins')
1253
command.extend(process_args)
1254
process = self._popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
1256
restore_environment()
1262
def _popen(self, *args, **kwargs):
1263
"""Place a call to Popen.
1265
Allows tests to override this method to intercept the calls made to
1266
Popen for introspection.
1268
return Popen(*args, **kwargs)
1270
def get_bzr_path(self):
1271
"""Return the path of the 'bzr' executable for this test suite."""
1272
bzr_path = os.path.dirname(os.path.dirname(bzrlib.__file__))+'/bzr'
1273
if not os.path.isfile(bzr_path):
1274
# We are probably installed. Assume sys.argv is the right file
1275
bzr_path = sys.argv[0]
1278
def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
1279
universal_newlines=False, process_args=None):
1280
"""Finish the execution of process.
1282
:param process: the Popen object returned from start_bzr_subprocess.
1283
:param retcode: The status code that is expected. Defaults to 0. If
1284
None is supplied, the status code is not checked.
1285
:param send_signal: an optional signal to send to the process.
1286
:param universal_newlines: Convert CRLF => LF
1287
:returns: (stdout, stderr)
1289
if send_signal is not None:
1290
os.kill(process.pid, send_signal)
1291
out, err = process.communicate()
1293
if universal_newlines:
1294
out = out.replace('\r\n', '\n')
1295
err = err.replace('\r\n', '\n')
1297
if retcode is not None and retcode != process.returncode:
1298
if process_args is None:
1299
process_args = "(unknown args)"
1300
mutter('Output of bzr %s:\n%s', process_args, out)
1301
mutter('Error for bzr %s:\n%s', process_args, err)
1302
self.fail('Command bzr %s failed with retcode %s != %s'
1303
% (process_args, retcode, process.returncode))
249
1306
def check_inventory_shape(self, inv, shape):
250
1307
"""Compare an inventory to a list of expected names.
298
1355
sys.stderr = real_stderr
299
1356
sys.stdin = real_stdin
1358
@symbol_versioning.deprecated_method(symbol_versioning.zero_eleven)
1359
def merge(self, branch_from, wt_to):
1360
"""A helper for tests to do a ui-less merge.
1362
This should move to the main library when someone has time to integrate
1365
# minimal ui-less merge.
1366
wt_to.branch.fetch(branch_from)
1367
base_rev = common_ancestor(branch_from.last_revision(),
1368
wt_to.branch.last_revision(),
1369
wt_to.branch.repository)
1370
merge_inner(wt_to.branch, branch_from.basis_tree(),
1371
wt_to.branch.repository.revision_tree(base_rev),
1373
wt_to.add_parent_tree_id(branch_from.last_revision())
302
1376
BzrTestBase = TestCase
1379
class TestCaseWithMemoryTransport(TestCase):
1380
"""Common test class for tests that do not need disk resources.
1382
Tests that need disk resources should derive from TestCaseWithTransport.
1384
TestCaseWithMemoryTransport sets the TEST_ROOT variable for all bzr tests.
1386
For TestCaseWithMemoryTransport the test_home_dir is set to the name of
1387
a directory which does not exist. This serves to help ensure test isolation
1388
is preserved. test_dir is set to the TEST_ROOT, as is cwd, because they
1389
must exist. However, TestCaseWithMemoryTransport does not offer local
1390
file defaults for the transport in tests, nor does it obey the command line
1391
override, so tests that accidentally write to the common directory should
1399
def __init__(self, methodName='runTest'):
1400
# allow test parameterisation after test construction and before test
1401
# execution. Variables that the parameteriser sets need to be
1402
# ones that are not set by setUp, or setUp will trash them.
1403
super(TestCaseWithMemoryTransport, self).__init__(methodName)
1404
self.transport_server = default_transport
1405
self.transport_readonly_server = None
1407
def get_transport(self):
1408
"""Return a writeable transport for the test scratch space"""
1409
t = get_transport(self.get_url())
1410
self.assertFalse(t.is_readonly())
1413
def get_readonly_transport(self):
1414
"""Return a readonly transport for the test scratch space
1416
This can be used to test that operations which should only need
1417
readonly access in fact do not try to write.
1419
t = get_transport(self.get_readonly_url())
1420
self.assertTrue(t.is_readonly())
1423
def create_transport_readonly_server(self):
1424
"""Create a transport server from class defined at init.
1426
This is mostly a hook for daughter classes.
1428
return self.transport_readonly_server()
1430
def get_readonly_server(self):
1431
"""Get the server instance for the readonly transport
1433
This is useful for some tests with specific servers to do diagnostics.
1435
if self.__readonly_server is None:
1436
if self.transport_readonly_server is None:
1437
# readonly decorator requested
1438
# bring up the server
1440
self.__readonly_server = ReadonlyServer()
1441
self.__readonly_server.setUp(self.__server)
1443
self.__readonly_server = self.create_transport_readonly_server()
1444
self.__readonly_server.setUp()
1445
self.addCleanup(self.__readonly_server.tearDown)
1446
return self.__readonly_server
1448
def get_readonly_url(self, relpath=None):
1449
"""Get a URL for the readonly transport.
1451
This will either be backed by '.' or a decorator to the transport
1452
used by self.get_url()
1453
relpath provides for clients to get a path relative to the base url.
1454
These should only be downwards relative, not upwards.
1456
base = self.get_readonly_server().get_url()
1457
if relpath is not None:
1458
if not base.endswith('/'):
1460
base = base + relpath
1463
def get_server(self):
1464
"""Get the read/write server instance.
1466
This is useful for some tests with specific servers that need
1469
For TestCaseWithMemoryTransport this is always a MemoryServer, and there
1470
is no means to override it.
1472
if self.__server is None:
1473
self.__server = MemoryServer()
1474
self.__server.setUp()
1475
self.addCleanup(self.__server.tearDown)
1476
return self.__server
1478
def get_url(self, relpath=None):
1479
"""Get a URL (or maybe a path) for the readwrite transport.
1481
This will either be backed by '.' or to an equivalent non-file based
1483
relpath provides for clients to get a path relative to the base url.
1484
These should only be downwards relative, not upwards.
1486
base = self.get_server().get_url()
1487
if relpath is not None and relpath != '.':
1488
if not base.endswith('/'):
1490
# XXX: Really base should be a url; we did after all call
1491
# get_url()! But sometimes it's just a path (from
1492
# LocalAbspathServer), and it'd be wrong to append urlescaped data
1493
# to a non-escaped local path.
1494
if base.startswith('./') or base.startswith('/'):
1497
base += urlutils.escape(relpath)
1500
def _make_test_root(self):
1501
if TestCaseWithMemoryTransport.TEST_ROOT is not None:
1505
root = u'test%04d.tmp' % i
1509
if e.errno == errno.EEXIST:
1514
# successfully created
1515
TestCaseWithMemoryTransport.TEST_ROOT = osutils.abspath(root)
1517
# make a fake bzr directory there to prevent any tests propagating
1518
# up onto the source directory's real branch
1519
bzrdir.BzrDir.create_standalone_workingtree(
1520
TestCaseWithMemoryTransport.TEST_ROOT)
1522
def makeAndChdirToTestDir(self):
1523
"""Create a temporary directories for this one test.
1525
This must set self.test_home_dir and self.test_dir and chdir to
1528
For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
1530
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
1531
self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
1532
self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
1534
def make_branch(self, relpath, format=None):
1535
"""Create a branch on the transport at relpath."""
1536
repo = self.make_repository(relpath, format=format)
1537
return repo.bzrdir.create_branch()
1539
def make_bzrdir(self, relpath, format=None):
1541
# might be a relative or absolute path
1542
maybe_a_url = self.get_url(relpath)
1543
segments = maybe_a_url.rsplit('/', 1)
1544
t = get_transport(maybe_a_url)
1545
if len(segments) > 1 and segments[-1] not in ('', '.'):
1548
except errors.FileExists:
1552
if isinstance(format, basestring):
1553
format = bzrdir.format_registry.make_bzrdir(format)
1554
return format.initialize_on_transport(t)
1555
except errors.UninitializableFormat:
1556
raise TestSkipped("Format %s is not initializable." % format)
1558
def make_repository(self, relpath, shared=False, format=None):
1559
"""Create a repository on our default transport at relpath."""
1560
made_control = self.make_bzrdir(relpath, format=format)
1561
return made_control.create_repository(shared=shared)
1563
def make_branch_and_memory_tree(self, relpath, format=None):
1564
"""Create a branch on the default transport and a MemoryTree for it."""
1565
b = self.make_branch(relpath, format=format)
1566
return memorytree.MemoryTree.create_on_branch(b)
1568
def overrideEnvironmentForTesting(self):
1569
os.environ['HOME'] = self.test_home_dir
1570
os.environ['BZR_HOME'] = self.test_home_dir
1573
super(TestCaseWithMemoryTransport, self).setUp()
1574
self._make_test_root()
1575
_currentdir = os.getcwdu()
1576
def _leaveDirectory():
1577
os.chdir(_currentdir)
1578
self.addCleanup(_leaveDirectory)
1579
self.makeAndChdirToTestDir()
1580
self.overrideEnvironmentForTesting()
1581
self.__readonly_server = None
1582
self.__server = None
305
class TestCaseInTempDir(TestCase):
1585
class TestCaseInTempDir(TestCaseWithMemoryTransport):
306
1586
"""Derived class that runs a test within a temporary directory.
308
1588
This is useful for tests that need to create a branch, etc.
327
1605
self.log("actually: %r" % contents)
328
1606
self.fail("contents of %s not as expected" % filename)
330
def _make_test_root(self):
331
if TestCaseInTempDir.TEST_ROOT is not None:
1608
def makeAndChdirToTestDir(self):
1609
"""See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
1611
For TestCaseInTempDir we create a temporary directory based on the test
1612
name and then create two subdirs - test and home under it.
1614
if NUMBERED_DIRS: # strongly recommended on Windows
1615
# due the path length limitation (260 chars)
1616
candidate_dir = '%s/%dK/%05d' % (self.TEST_ROOT,
1617
int(self.number/1000),
1619
os.makedirs(candidate_dir)
1620
self.test_home_dir = candidate_dir + '/home'
1621
os.mkdir(self.test_home_dir)
1622
self.test_dir = candidate_dir + '/work'
1623
os.mkdir(self.test_dir)
1624
os.chdir(self.test_dir)
1625
# put name of test inside
1626
f = file(candidate_dir + '/name', 'w')
1631
# shorten the name, to avoid test failures due to path length
1632
short_id = self.id().replace('bzrlib.tests.', '') \
1633
.replace('__main__.', '')[-100:]
1634
# it's possible the same test class is run several times for
1635
# parameterized tests, so make sure the names don't collide.
335
root = 'test%04d.tmp' % i
339
if e.errno == errno.EEXIST:
344
# successfully created
345
TestCaseInTempDir.TEST_ROOT = os.path.abspath(root)
347
# make a fake bzr directory there to prevent any tests propagating
348
# up onto the source directory's real branch
349
os.mkdir(os.path.join(TestCaseInTempDir.TEST_ROOT, '.bzr'))
352
super(TestCaseInTempDir, self).setUp()
353
self._make_test_root()
354
self._currentdir = os.getcwdu()
355
short_id = self.id().replace('bzrlib.selftest.', '') \
356
.replace('__main__.', '')
357
self.test_dir = os.path.join(self.TEST_ROOT, short_id)
358
os.mkdir(self.test_dir)
359
os.chdir(self.test_dir)
362
os.chdir(self._currentdir)
363
super(TestCaseInTempDir, self).tearDown()
365
def build_tree(self, shape):
1639
candidate_dir = '%s/%s.%d' % (self.TEST_ROOT, short_id, i)
1641
candidate_dir = '%s/%s' % (self.TEST_ROOT, short_id)
1642
if os.path.exists(candidate_dir):
1646
os.mkdir(candidate_dir)
1647
self.test_home_dir = candidate_dir + '/home'
1648
os.mkdir(self.test_home_dir)
1649
self.test_dir = candidate_dir + '/work'
1650
os.mkdir(self.test_dir)
1651
os.chdir(self.test_dir)
1654
def build_tree(self, shape, line_endings='binary', transport=None):
366
1655
"""Build a test tree according to a pattern.
368
1657
shape is a sequence of file specifications. If the final
369
1658
character is '/', a directory is created.
1660
This assumes that all the elements in the tree being built are new.
371
1662
This doesn't add anything to a branch.
1663
:param line_endings: Either 'binary' or 'native'
1664
in binary mode, exact contents are written
1665
in native mode, the line endings match the
1666
default platform endings.
1668
:param transport: A transport to write to, for building trees on
1669
VFS's. If the transport is readonly or None,
1670
"." is opened automatically.
373
# XXX: It's OK to just create them using forward slashes on windows?
1672
# It's OK to just create them using forward slashes on windows.
1673
if transport is None or transport.is_readonly():
1674
transport = get_transport(".")
374
1675
for name in shape:
375
assert isinstance(name, basestring)
1676
self.assert_(isinstance(name, basestring))
376
1677
if name[-1] == '/':
1678
transport.mkdir(urlutils.escape(name[:-1]))
380
print >>f, "contents of", name
1680
if line_endings == 'binary':
1682
elif line_endings == 'native':
1685
raise errors.BzrError(
1686
'Invalid line ending request %r' % line_endings)
1687
content = "contents of %s%s" % (name.encode('utf-8'), end)
1688
transport.put_bytes_non_atomic(urlutils.escape(name), content)
1690
def build_tree_contents(self, shape):
1691
build_tree_contents(shape)
1693
def assertFileEqual(self, content, path):
1694
"""Fail if path does not contain 'content'."""
1695
self.failUnlessExists(path)
1696
# TODO: jam 20060427 Shouldn't this be 'rb'?
1697
self.assertEqualDiff(content, open(path, 'r').read())
383
1699
def failUnlessExists(self, path):
384
1700
"""Fail unless path, which may be abs or relative, exists."""
385
self.failUnless(os.path.exists(path))
388
class MetaTestLog(TestCase):
389
def test_logging(self):
390
"""Test logs are captured when a test fails."""
391
logging.info('an info message')
392
warning('something looks dodgy...')
393
logging.debug('hello, test is running')
1701
self.failUnless(osutils.lexists(path),path+" does not exist")
1703
def failIfExists(self, path):
1704
"""Fail if path, which may be abs or relative, exists."""
1705
self.failIf(osutils.lexists(path),path+" exists")
1708
class TestCaseWithTransport(TestCaseInTempDir):
1709
"""A test case that provides get_url and get_readonly_url facilities.
1711
These back onto two transport servers, one for readonly access and one for
1714
If no explicit class is provided for readonly access, a
1715
ReadonlyTransportDecorator is used instead which allows the use of non disk
1716
based read write transports.
1718
If an explicit class is provided for readonly access, that server and the
1719
readwrite one must both define get_url() as resolving to os.getcwd().
1722
def create_transport_server(self):
1723
"""Create a transport server from class defined at init.
1725
This is mostly a hook for daughter classes.
1727
return self.transport_server()
1729
def get_server(self):
1730
"""See TestCaseWithMemoryTransport.
1732
This is useful for some tests with specific servers that need
1735
if self.__server is None:
1736
self.__server = self.create_transport_server()
1737
self.__server.setUp()
1738
self.addCleanup(self.__server.tearDown)
1739
return self.__server
1741
def make_branch_and_tree(self, relpath, format=None):
1742
"""Create a branch on the transport and a tree locally.
1744
If the transport is not a LocalTransport, the Tree can't be created on
1745
the transport. In that case the working tree is created in the local
1746
directory, and the returned tree's branch and repository will also be
1749
This will fail if the original default transport for this test
1750
case wasn't backed by the working directory, as the branch won't
1751
be on disk for us to open it.
1753
:param format: The BzrDirFormat.
1754
:returns: the WorkingTree.
1756
# TODO: always use the local disk path for the working tree,
1757
# this obviously requires a format that supports branch references
1758
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
1760
b = self.make_branch(relpath, format=format)
1762
return b.bzrdir.create_workingtree()
1763
except errors.NotLocalUrl:
1764
# We can only make working trees locally at the moment. If the
1765
# transport can't support them, then reopen the branch on a local
1766
# transport, and create the working tree there.
1768
# Possibly we should instead keep
1769
# the non-disk-backed branch and create a local checkout?
1770
bd = bzrdir.BzrDir.open(relpath)
1771
return bd.create_workingtree()
1773
def assertIsDirectory(self, relpath, transport):
1774
"""Assert that relpath within transport is a directory.
1776
This may not be possible on all transports; in that case it propagates
1777
a TransportNotPossible.
1780
mode = transport.stat(relpath).st_mode
1781
except errors.NoSuchFile:
1782
self.fail("path %s is not a directory; no such file"
1784
if not stat.S_ISDIR(mode):
1785
self.fail("path %s is not a directory; has mode %#o"
1788
def assertTreesEqual(self, left, right):
1789
"""Check that left and right have the same content and properties."""
1790
# we use a tree delta to check for equality of the content, and we
1791
# manually check for equality of other things such as the parents list.
1792
self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
1793
differences = left.changes_from(right)
1794
self.assertFalse(differences.has_changed(),
1795
"Trees %r and %r are different: %r" % (left, right, differences))
1798
super(TestCaseWithTransport, self).setUp()
1799
self.__server = None
1802
class ChrootedTestCase(TestCaseWithTransport):
1803
"""A support class that provides readonly urls outside the local namespace.
1805
This is done by checking if self.transport_server is a MemoryServer. if it
1806
is then we are chrooted already, if it is not then an HttpServer is used
1809
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
1810
be used without needed to redo it when a different
1811
subclass is in use ?
1815
super(ChrootedTestCase, self).setUp()
1816
if not self.transport_server == MemoryServer:
1817
self.transport_readonly_server = HttpServer
397
1820
def filter_suite_by_re(suite, pattern):
398
1821
result = TestUtil.TestSuite()
399
1822
filter_re = re.compile(pattern)
400
1823
for test in iter_suite_tests(suite):
401
if filter_re.match(test.id()):
1824
if filter_re.search(test.id()):
402
1825
result.addTest(test)
406
def filter_suite_by_names(suite, wanted_names):
407
"""Return a new suite containing only selected tests.
409
Names are considered to match if any name is a substring of the
410
fully-qualified test id (i.e. the class ."""
1829
def sort_suite_by_re(suite, pattern):
1832
filter_re = re.compile(pattern)
412
1833
for test in iter_suite_tests(suite):
414
for p in wanted_names:
415
if this_id.find(p) != -1:
420
def run_suite(suite, name='test', verbose=False, pattern=".*", testnames=None):
421
TestCaseInTempDir._TEST_NAME = name
1834
if filter_re.search(test.id()):
1838
return TestUtil.TestSuite(first + second)
1841
def run_suite(suite, name='test', verbose=False, pattern=".*",
1842
stop_on_failure=False, keep_output=False,
1843
transport=None, lsprof_timed=None, bench_history=None,
1844
matching_tests_first=None,
1845
numbered_dirs=False):
1846
global NUMBERED_DIRS
1847
NUMBERED_DIRS = bool(numbered_dirs)
1849
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
426
1854
runner = TextTestRunner(stream=sys.stdout,
430
suite = filter_suite_by_names(suite, testnames)
1856
verbosity=verbosity,
1857
keep_output=keep_output,
1858
bench_history=bench_history)
1859
runner.stop_on_failure=stop_on_failure
431
1860
if pattern != '.*':
432
suite = filter_suite_by_re(suite, pattern)
1861
if matching_tests_first:
1862
suite = sort_suite_by_re(suite, pattern)
1864
suite = filter_suite_by_re(suite, pattern)
433
1865
result = runner.run(suite)
434
# This is still a little bogus,
435
# but only a little. Folk not using our testrunner will
436
# have to delete their temp directories themselves.
437
if result.wasSuccessful():
438
if TestCaseInTempDir.TEST_ROOT is not None:
439
shutil.rmtree(TestCaseInTempDir.TEST_ROOT)
441
print "Failed tests working directories are in '%s'\n" % TestCaseInTempDir.TEST_ROOT
442
1866
return result.wasSuccessful()
445
def selftest(verbose=False, pattern=".*", testnames=None):
1869
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
1872
test_suite_factory=None,
1875
matching_tests_first=None,
1876
numbered_dirs=False):
446
1877
"""Run the whole test suite under the enhanced runner"""
447
return run_suite(test_suite(), 'testbzr', verbose=verbose, pattern=pattern,
1878
# XXX: Very ugly way to do this...
1879
# Disable warning about old formats because we don't want it to disturb
1880
# any blackbox tests.
1881
from bzrlib import repository
1882
repository._deprecation_warning_done = True
1884
global default_transport
1885
if transport is None:
1886
transport = default_transport
1887
old_transport = default_transport
1888
default_transport = transport
1890
if test_suite_factory is None:
1891
suite = test_suite()
1893
suite = test_suite_factory()
1894
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
1895
stop_on_failure=stop_on_failure, keep_output=keep_output,
1896
transport=transport,
1897
lsprof_timed=lsprof_timed,
1898
bench_history=bench_history,
1899
matching_tests_first=matching_tests_first,
1900
numbered_dirs=numbered_dirs)
1902
default_transport = old_transport
451
1905
def test_suite():
452
"""Build and return TestSuite for the whole program."""
453
import bzrlib.store, bzrlib.inventory, bzrlib.branch
454
import bzrlib.osutils, bzrlib.merge3, bzrlib.plugin
455
from doctest import DocTestSuite
457
global MODULES_TO_TEST, MODULES_TO_DOCTEST
460
['bzrlib.selftest.MetaTestLog',
461
'bzrlib.selftest.testinv',
462
'bzrlib.selftest.test_ancestry',
463
'bzrlib.selftest.test_commit',
464
'bzrlib.selftest.test_commit_merge',
465
'bzrlib.selftest.versioning',
466
'bzrlib.selftest.testmerge3',
467
'bzrlib.selftest.testmerge',
468
'bzrlib.selftest.testhashcache',
469
'bzrlib.selftest.teststatus',
470
'bzrlib.selftest.testlog',
471
'bzrlib.selftest.testrevisionnamespaces',
472
'bzrlib.selftest.testbranch',
473
'bzrlib.selftest.testrevision',
474
'bzrlib.selftest.test_revision_info',
475
'bzrlib.selftest.test_merge_core',
476
'bzrlib.selftest.test_smart_add',
477
'bzrlib.selftest.test_bad_files',
478
'bzrlib.selftest.testdiff',
479
'bzrlib.selftest.test_parent',
480
'bzrlib.selftest.test_xml',
481
'bzrlib.selftest.test_weave',
482
'bzrlib.selftest.testfetch',
483
'bzrlib.selftest.whitebox',
484
'bzrlib.selftest.teststore',
485
'bzrlib.selftest.blackbox',
486
'bzrlib.selftest.testsampler',
487
'bzrlib.selftest.testtransport',
488
'bzrlib.selftest.testgraph',
489
'bzrlib.selftest.testworkingtree',
490
'bzrlib.selftest.test_upgrade',
491
'bzrlib.selftest.test_conflicts',
1906
"""Build and return TestSuite for the whole of bzrlib.
1908
This function can be replaced if you need to change the default test
1909
suite on a global basis, but it is not encouraged.
1912
'bzrlib.tests.test_ancestry',
1913
'bzrlib.tests.test_annotate',
1914
'bzrlib.tests.test_api',
1915
'bzrlib.tests.test_atomicfile',
1916
'bzrlib.tests.test_bad_files',
1917
'bzrlib.tests.test_branch',
1918
'bzrlib.tests.test_bundle',
1919
'bzrlib.tests.test_bzrdir',
1920
'bzrlib.tests.test_cache_utf8',
1921
'bzrlib.tests.test_commands',
1922
'bzrlib.tests.test_commit',
1923
'bzrlib.tests.test_commit_merge',
1924
'bzrlib.tests.test_config',
1925
'bzrlib.tests.test_conflicts',
1926
'bzrlib.tests.test_decorators',
1927
'bzrlib.tests.test_delta',
1928
'bzrlib.tests.test_diff',
1929
'bzrlib.tests.test_dirstate',
1930
'bzrlib.tests.test_doc_generate',
1931
'bzrlib.tests.test_errors',
1932
'bzrlib.tests.test_escaped_store',
1933
'bzrlib.tests.test_extract',
1934
'bzrlib.tests.test_fetch',
1935
'bzrlib.tests.test_ftp_transport',
1936
'bzrlib.tests.test_generate_docs',
1937
'bzrlib.tests.test_generate_ids',
1938
'bzrlib.tests.test_globbing',
1939
'bzrlib.tests.test_gpg',
1940
'bzrlib.tests.test_graph',
1941
'bzrlib.tests.test_hashcache',
1942
'bzrlib.tests.test_http',
1943
'bzrlib.tests.test_http_response',
1944
'bzrlib.tests.test_https_ca_bundle',
1945
'bzrlib.tests.test_identitymap',
1946
'bzrlib.tests.test_ignores',
1947
'bzrlib.tests.test_inv',
1948
'bzrlib.tests.test_knit',
1949
'bzrlib.tests.test_lazy_import',
1950
'bzrlib.tests.test_lazy_regex',
1951
'bzrlib.tests.test_lockdir',
1952
'bzrlib.tests.test_lockable_files',
1953
'bzrlib.tests.test_log',
1954
'bzrlib.tests.test_memorytree',
1955
'bzrlib.tests.test_merge',
1956
'bzrlib.tests.test_merge3',
1957
'bzrlib.tests.test_merge_core',
1958
'bzrlib.tests.test_merge_directive',
1959
'bzrlib.tests.test_missing',
1960
'bzrlib.tests.test_msgeditor',
1961
'bzrlib.tests.test_nonascii',
1962
'bzrlib.tests.test_options',
1963
'bzrlib.tests.test_osutils',
1964
'bzrlib.tests.test_osutils_encodings',
1965
'bzrlib.tests.test_patch',
1966
'bzrlib.tests.test_patches',
1967
'bzrlib.tests.test_permissions',
1968
'bzrlib.tests.test_plugins',
1969
'bzrlib.tests.test_progress',
1970
'bzrlib.tests.test_reconcile',
1971
'bzrlib.tests.test_registry',
1972
'bzrlib.tests.test_repository',
1973
'bzrlib.tests.test_revert',
1974
'bzrlib.tests.test_revision',
1975
'bzrlib.tests.test_revisionnamespaces',
1976
'bzrlib.tests.test_revisiontree',
1977
'bzrlib.tests.test_rio',
1978
'bzrlib.tests.test_sampler',
1979
'bzrlib.tests.test_selftest',
1980
'bzrlib.tests.test_setup',
1981
'bzrlib.tests.test_sftp_transport',
1982
'bzrlib.tests.test_smart_add',
1983
'bzrlib.tests.test_smart_transport',
1984
'bzrlib.tests.test_source',
1985
'bzrlib.tests.test_ssh_transport',
1986
'bzrlib.tests.test_status',
1987
'bzrlib.tests.test_store',
1988
'bzrlib.tests.test_subsume',
1989
'bzrlib.tests.test_symbol_versioning',
1990
'bzrlib.tests.test_tag',
1991
'bzrlib.tests.test_testament',
1992
'bzrlib.tests.test_textfile',
1993
'bzrlib.tests.test_textmerge',
1994
'bzrlib.tests.test_timestamp',
1995
'bzrlib.tests.test_trace',
1996
'bzrlib.tests.test_transactions',
1997
'bzrlib.tests.test_transform',
1998
'bzrlib.tests.test_transport',
1999
'bzrlib.tests.test_tree',
2000
'bzrlib.tests.test_treebuilder',
2001
'bzrlib.tests.test_tsort',
2002
'bzrlib.tests.test_tuned_gzip',
2003
'bzrlib.tests.test_ui',
2004
'bzrlib.tests.test_upgrade',
2005
'bzrlib.tests.test_urlutils',
2006
'bzrlib.tests.test_versionedfile',
2007
'bzrlib.tests.test_version',
2008
'bzrlib.tests.test_version_info',
2009
'bzrlib.tests.test_weave',
2010
'bzrlib.tests.test_whitebox',
2011
'bzrlib.tests.test_workingtree',
2012
'bzrlib.tests.test_workingtree_4',
2013
'bzrlib.tests.test_wsgi',
2014
'bzrlib.tests.test_xml',
494
for m in (bzrlib.store, bzrlib.inventory, bzrlib.branch,
495
bzrlib.osutils, bzrlib.commands, bzrlib.merge3):
496
if m not in MODULES_TO_DOCTEST:
497
MODULES_TO_DOCTEST.append(m)
499
TestCase.BZRPATH = os.path.join(os.path.realpath(os.path.dirname(bzrlib.__path__[0])), 'bzr')
500
print '%-30s %s' % ('bzr binary', TestCase.BZRPATH)
503
suite.addTest(TestLoader().loadTestsFromNames(testmod_names))
2016
test_transport_implementations = [
2017
'bzrlib.tests.test_transport_implementations',
2018
'bzrlib.tests.test_read_bundle',
2020
suite = TestUtil.TestSuite()
2021
loader = TestUtil.TestLoader()
2022
suite.addTest(loader.loadTestsFromModuleNames(testmod_names))
2023
from bzrlib.transport import TransportTestProviderAdapter
2024
adapter = TransportTestProviderAdapter()
2025
adapt_modules(test_transport_implementations, adapter, loader, suite)
2026
for package in packages_to_test():
2027
suite.addTest(package.test_suite())
504
2028
for m in MODULES_TO_TEST:
505
suite.addTest(TestLoader().loadTestsFromModule(m))
506
for m in (MODULES_TO_DOCTEST):
507
suite.addTest(DocTestSuite(m))
508
for p in bzrlib.plugin.all_plugins:
509
if hasattr(p, 'test_suite'):
510
suite.addTest(p.test_suite())
2029
suite.addTest(loader.loadTestsFromModule(m))
2030
for m in MODULES_TO_DOCTEST:
2032
suite.addTest(doctest.DocTestSuite(m))
2033
except ValueError, e:
2034
print '**failed to get doctest for: %s\n%s' %(m,e)
2036
for name, plugin in bzrlib.plugin.all_plugins().items():
2037
if getattr(plugin, 'test_suite', None) is not None:
2038
default_encoding = sys.getdefaultencoding()
2040
plugin_suite = plugin.test_suite()
2041
except ImportError, e:
2042
bzrlib.trace.warning(
2043
'Unable to test plugin "%s": %s', name, e)
2045
suite.addTest(plugin_suite)
2046
if default_encoding != sys.getdefaultencoding():
2047
bzrlib.trace.warning(
2048
'Plugin "%s" tried to reset default encoding to: %s', name,
2049
sys.getdefaultencoding())
2051
sys.setdefaultencoding(default_encoding)
2055
def adapt_modules(mods_list, adapter, loader, suite):
2056
"""Adapt the modules in mods_list using adapter and add to suite."""
2057
for test in iter_suite_tests(loader.loadTestsFromModuleNames(mods_list)):
2058
suite.addTests(adapter.adapt(test))
2061
def clean_selftest_output(root=None, quiet=False):
2062
"""Remove all selftest output directories from root directory.
2064
:param root: root directory for clean
2065
(if ommitted or None then clean current directory).
2066
:param quiet: suppress report about deleting directories
2071
re_dir = re.compile(r'''test\d\d\d\d\.tmp''')
2074
for i in os.listdir(root):
2075
if os.path.isdir(i) and re_dir.match(i):
2077
print 'delete directory:', i