1
# Copyright (C) 2005-2013, 2015, 2016 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Testing framework extensions"""
19
from __future__ import absolute_import
21
# NOTE: Some classes in here use camelCaseNaming() rather than
22
# underscore_naming(). That's for consistency with unittest; it's not the
23
# general style of breezy. Please continue that consistency when adding e.g.
24
# new assertFoo() methods.
54
# nb: check this before importing anything else from within it
55
_testtools_version = getattr(testtools, '__version__', ())
56
if _testtools_version < (0, 9, 5):
57
raise ImportError("need at least testtools 0.9.5: %s is %r"
58
% (testtools.__file__, _testtools_version))
59
from testtools import content
66
commands as _mod_commands,
76
plugin as _mod_plugin,
83
transport as _mod_transport,
89
# lsprof not available
91
from ..sixish import (
96
from ..smart import client, request
97
from ..transport import (
101
from ..tests import (
108
from ..tests.features import _CompatabilityThunkFeature
110
# Mark this python module as being part of the implementation
111
# of unittest: this gives us better tracebacks where the last
112
# shown frame is the test code, not our assertXYZ.
115
default_transport = test_server.LocalURLServer
118
_unitialized_attr = object()
119
"""A sentinel needed to act as a default value in a method signature."""
122
# Subunit result codes, defined here to prevent a hard dependency on subunit.
126
# These are intentionally brought into this namespace. That way plugins, etc
127
# can just "from breezy.tests import TestCase, TestLoader, etc"
128
TestSuite = TestUtil.TestSuite
129
TestLoader = TestUtil.TestLoader
131
# Tests should run in a clean and clearly defined environment. The goal is to
132
# keep them isolated from the running environment as mush as possible. The test
133
# framework ensures the variables defined below are set (or deleted if the
134
# value is None) before a test is run and reset to their original value after
135
# the test is run. Generally if some code depends on an environment variable,
136
# the tests should start without this variable in the environment. There are a
137
# few exceptions but you shouldn't violate this rule lightly.
141
'XDG_CONFIG_HOME': None,
142
# brz now uses the Win32 API and doesn't rely on APPDATA, but the
143
# tests do check our impls match APPDATA
144
'BRZ_EDITOR': None, # test_msgeditor manipulates this variable
148
'BZREMAIL': None, # may still be present in the environment
149
'EMAIL': 'jrandom@example.com', # set EMAIL as brz does not guess
150
'BRZ_PROGRESS_BAR': None,
151
# This should trap leaks to ~/.brz.log. This occurs when tests use TestCase
152
# as a base class instead of TestCaseInTempDir. Tests inheriting from
153
# TestCase should not use disk resources, BRZ_LOG is one.
154
'BRZ_LOG': '/you-should-use-TestCaseInTempDir-if-you-need-a-log-file',
155
'BRZ_PLUGIN_PATH': '-site',
156
'BRZ_DISABLE_PLUGINS': None,
157
'BRZ_PLUGINS_AT': None,
158
'BRZ_CONCURRENCY': None,
159
# Make sure that any text ui tests are consistent regardless of
160
# the environment the test case is run in; you may want tests that
161
# test other combinations. 'dumb' is a reasonable guess for tests
162
# going to a pipe or a BytesIO.
168
'SSH_AUTH_SOCK': None,
178
# Nobody cares about ftp_proxy, FTP_PROXY AFAIK. So far at
179
# least. If you do (care), please update this comment
183
'BZR_REMOTE_PATH': None,
184
# Generally speaking, we don't want apport reporting on crashes in
185
# the test envirnoment unless we're specifically testing apport,
186
# so that it doesn't leak into the real system environment. We
187
# use an env var so it propagates to subprocesses.
188
'APPORT_DISABLE': '1',
192
def override_os_environ(test, env=None):
193
"""Modify os.environ keeping a copy.
195
:param test: A test instance
197
:param env: A dict containing variable definitions to be installed
200
env = isolated_environ
201
test._original_os_environ = dict(**os.environ)
203
osutils.set_or_unset_env(var, env[var])
204
if var not in test._original_os_environ:
205
# The var is new, add it with a value of None, so
206
# restore_os_environ will delete it
207
test._original_os_environ[var] = None
210
def restore_os_environ(test):
211
"""Restore os.environ to its original state.
213
:param test: A test instance previously passed to override_os_environ.
215
for var, value in test._original_os_environ.items():
216
# Restore the original value (or delete it if the value has been set to
217
# None in override_os_environ).
218
osutils.set_or_unset_env(var, value)
221
def _clear__type_equality_funcs(test):
222
"""Cleanup bound methods stored on TestCase instances
224
Clear the dict breaking a few (mostly) harmless cycles in the affected
225
unittests released with Python 2.6 and initial Python 2.7 versions.
227
For a few revisions between Python 2.7.1 and Python 2.7.2 that annoyingly
228
shipped in Oneiric, an object with no clear method was used, hence the
229
extra complications, see bug 809048 for details.
231
type_equality_funcs = getattr(test, "_type_equality_funcs", None)
232
if type_equality_funcs is not None:
233
tef_clear = getattr(type_equality_funcs, "clear", None)
234
if tef_clear is None:
235
tef_instance_dict = getattr(type_equality_funcs, "__dict__", None)
236
if tef_instance_dict is not None:
237
tef_clear = tef_instance_dict.clear
238
if tef_clear is not None:
242
class ExtendedTestResult(testtools.TextTestResult):
243
"""Accepts, reports and accumulates the results of running tests.
245
Compared to the unittest version this class adds support for
246
profiling, benchmarking, stopping as soon as a test fails, and
247
skipping tests. There are further-specialized subclasses for
248
different types of display.
250
When a test finishes, in whatever way, it calls one of the addSuccess,
251
addFailure or addError methods. These in turn may redirect to a more
252
specific case for the special test results supported by our extended
255
Note that just one of these objects is fed the results from many tests.
260
def __init__(self, stream, descriptions, verbosity,
264
"""Construct new TestResult.
266
:param bench_history: Optionally, a writable file object to accumulate
269
testtools.TextTestResult.__init__(self, stream)
270
if bench_history is not None:
271
from breezy.version import _get_bzr_source_tree
272
src_tree = _get_bzr_source_tree()
275
revision_id = src_tree.get_parent_ids()[0]
277
# XXX: if this is a brand new tree, do the same as if there
281
# XXX: If there's no branch, what should we do?
283
bench_history.write("--date %s %s\n" % (time.time(), revision_id))
284
self._bench_history = bench_history
285
self.ui = ui.ui_factory
288
self.failure_count = 0
289
self.known_failure_count = 0
291
self.not_applicable_count = 0
292
self.unsupported = {}
294
self._overall_start_time = time.time()
295
self._strict = strict
296
self._first_thread_leaker_id = None
297
self._tests_leaking_threads_count = 0
298
self._traceback_from_test = None
300
def stopTestRun(self):
303
stopTime = time.time()
304
timeTaken = stopTime - self.startTime
305
# GZ 2010-07-19: Seems testtools has no printErrors method, and though
306
# the parent class method is similar have to duplicate
307
self._show_list('ERROR', self.errors)
308
self._show_list('FAIL', self.failures)
309
self.stream.write(self.sep2)
310
self.stream.write("%s %d test%s in %.3fs\n\n" % (actionTaken,
311
run, run != 1 and "s" or "", timeTaken))
312
if not self.wasSuccessful():
313
self.stream.write("FAILED (")
314
failed, errored = map(len, (self.failures, self.errors))
316
self.stream.write("failures=%d" % failed)
318
if failed: self.stream.write(", ")
319
self.stream.write("errors=%d" % errored)
320
if self.known_failure_count:
321
if failed or errored: self.stream.write(", ")
322
self.stream.write("known_failure_count=%d" %
323
self.known_failure_count)
324
self.stream.write(")\n")
326
if self.known_failure_count:
327
self.stream.write("OK (known_failures=%d)\n" %
328
self.known_failure_count)
330
self.stream.write("OK\n")
331
if self.skip_count > 0:
332
skipped = self.skip_count
333
self.stream.write('%d test%s skipped\n' %
334
(skipped, skipped != 1 and "s" or ""))
336
for feature, count in sorted(self.unsupported.items()):
337
self.stream.write("Missing feature '%s' skipped %d tests.\n" %
340
ok = self.wasStrictlySuccessful()
342
ok = self.wasSuccessful()
343
if self._first_thread_leaker_id:
345
'%s is leaking threads among %d leaking tests.\n' % (
346
self._first_thread_leaker_id,
347
self._tests_leaking_threads_count))
348
# We don't report the main thread as an active one.
350
'%d non-main threads were left active in the end.\n'
351
% (len(self._active_threads) - 1))
353
def getDescription(self, test):
356
def _extractBenchmarkTime(self, testCase, details=None):
357
"""Add a benchmark time for the current test case."""
358
if details and 'benchtime' in details:
359
return float(''.join(details['benchtime'].iter_bytes()))
360
return getattr(testCase, "_benchtime", None)
362
def _delta_to_float(self, a_timedelta, precision):
363
# This calls ceiling to ensure that the most pessimistic view of time
364
# taken is shown (rather than leaving it to the Python %f operator
365
# to decide whether to round/floor/ceiling. This was added when we
366
# had pyp3 test failures that suggest a floor was happening.
367
shift = 10 ** precision
368
return math.ceil((a_timedelta.days * 86400.0 + a_timedelta.seconds +
369
a_timedelta.microseconds / 1000000.0) * shift) / shift
371
def _elapsedTestTimeString(self):
372
"""Return a time string for the overall time the current test has taken."""
373
return self._formatTime(self._delta_to_float(
374
self._now() - self._start_datetime, 3))
376
def _testTimeString(self, testCase):
377
benchmark_time = self._extractBenchmarkTime(testCase)
378
if benchmark_time is not None:
379
return self._formatTime(benchmark_time) + "*"
381
return self._elapsedTestTimeString()
383
def _formatTime(self, seconds):
384
"""Format seconds as milliseconds with leading spaces."""
385
# some benchmarks can take thousands of seconds to run, so we need 8
387
return "%8dms" % (1000 * seconds)
389
def _shortened_test_description(self, test):
391
what = re.sub(r'^breezy\.tests\.', '', what)
394
# GZ 2010-10-04: Cloned tests may end up harmlessly calling this method
395
# multiple times in a row, because the handler is added for
396
# each test but the container list is shared between cases.
397
# See lp:498869 lp:625574 and lp:637725 for background.
398
def _record_traceback_from_test(self, exc_info):
399
"""Store the traceback from passed exc_info tuple till"""
400
self._traceback_from_test = exc_info[2]
402
def startTest(self, test):
403
super(ExtendedTestResult, self).startTest(test)
407
self.report_test_start(test)
408
test.number = self.count
409
self._recordTestStartTime()
410
# Make testtools cases give us the real traceback on failure
411
addOnException = getattr(test, "addOnException", None)
412
if addOnException is not None:
413
addOnException(self._record_traceback_from_test)
414
# Only check for thread leaks on breezy derived test cases
415
if isinstance(test, TestCase):
416
test.addCleanup(self._check_leaked_threads, test)
418
def stopTest(self, test):
419
super(ExtendedTestResult, self).stopTest(test)
420
# Manually break cycles, means touching various private things but hey
421
getDetails = getattr(test, "getDetails", None)
422
if getDetails is not None:
424
_clear__type_equality_funcs(test)
425
self._traceback_from_test = None
427
def startTests(self):
428
self.report_tests_starting()
429
self._active_threads = threading.enumerate()
431
def _check_leaked_threads(self, test):
432
"""See if any threads have leaked since last call
434
A sample of live threads is stored in the _active_threads attribute,
435
when this method runs it compares the current live threads and any not
436
in the previous sample are treated as having leaked.
438
now_active_threads = set(threading.enumerate())
439
threads_leaked = now_active_threads.difference(self._active_threads)
441
self._report_thread_leak(test, threads_leaked, now_active_threads)
442
self._tests_leaking_threads_count += 1
443
if self._first_thread_leaker_id is None:
444
self._first_thread_leaker_id = test.id()
445
self._active_threads = now_active_threads
447
def _recordTestStartTime(self):
448
"""Record that a test has started."""
449
self._start_datetime = self._now()
451
def addError(self, test, err):
452
"""Tell result that test finished with an error.
454
Called from the TestCase run() method when the test
455
fails with an unexpected error.
457
self._post_mortem(self._traceback_from_test)
458
super(ExtendedTestResult, self).addError(test, err)
459
self.error_count += 1
460
self.report_error(test, err)
464
def addFailure(self, test, err):
465
"""Tell result that test failed.
467
Called from the TestCase run() method when the test
468
fails because e.g. an assert() method failed.
470
self._post_mortem(self._traceback_from_test)
471
super(ExtendedTestResult, self).addFailure(test, err)
472
self.failure_count += 1
473
self.report_failure(test, err)
477
def addSuccess(self, test, details=None):
478
"""Tell result that test completed successfully.
480
Called from the TestCase run()
482
if self._bench_history is not None:
483
benchmark_time = self._extractBenchmarkTime(test, details)
484
if benchmark_time is not None:
485
self._bench_history.write("%s %s\n" % (
486
self._formatTime(benchmark_time),
488
self.report_success(test)
489
super(ExtendedTestResult, self).addSuccess(test)
490
test._log_contents = ''
492
def addExpectedFailure(self, test, err):
493
self.known_failure_count += 1
494
self.report_known_failure(test, err)
496
def addUnexpectedSuccess(self, test, details=None):
497
"""Tell result the test unexpectedly passed, counting as a failure
499
When the minimum version of testtools required becomes 0.9.8 this
500
can be updated to use the new handling there.
502
super(ExtendedTestResult, self).addFailure(test, details=details)
503
self.failure_count += 1
504
self.report_unexpected_success(test,
505
"".join(details["reason"].iter_text()))
509
def addNotSupported(self, test, feature):
510
"""The test will not be run because of a missing feature.
512
# this can be called in two different ways: it may be that the
513
# test started running, and then raised (through requireFeature)
514
# UnavailableFeature. Alternatively this method can be called
515
# while probing for features before running the test code proper; in
516
# that case we will see startTest and stopTest, but the test will
517
# never actually run.
518
self.unsupported.setdefault(str(feature), 0)
519
self.unsupported[str(feature)] += 1
520
self.report_unsupported(test, feature)
522
def addSkip(self, test, reason):
523
"""A test has not run for 'reason'."""
525
self.report_skip(test, reason)
527
def addNotApplicable(self, test, reason):
528
self.not_applicable_count += 1
529
self.report_not_applicable(test, reason)
531
def _count_stored_tests(self):
532
"""Count of tests instances kept alive due to not succeeding"""
533
return self.error_count + self.failure_count + self.known_failure_count
535
def _post_mortem(self, tb=None):
536
"""Start a PDB post mortem session."""
537
if os.environ.get('BRZ_TEST_PDB', None):
541
def progress(self, offset, whence):
542
"""The test is adjusting the count of tests to run."""
543
if whence == SUBUNIT_SEEK_SET:
544
self.num_tests = offset
545
elif whence == SUBUNIT_SEEK_CUR:
546
self.num_tests += offset
548
raise errors.BzrError("Unknown whence %r" % whence)
550
def report_tests_starting(self):
551
"""Display information before the test run begins"""
552
if getattr(sys, 'frozen', None) is None:
553
bzr_path = osutils.realpath(sys.argv[0])
555
bzr_path = sys.executable
557
'brz selftest: %s\n' % (bzr_path,))
560
breezy.__path__[0],))
562
' bzr-%s python-%s %s\n' % (
563
breezy.version_string,
564
breezy._format_version_tuple(sys.version_info),
565
platform.platform(aliased=1),
567
self.stream.write('\n')
569
def report_test_start(self, test):
570
"""Display information on the test just about to be run"""
572
def _report_thread_leak(self, test, leaked_threads, active_threads):
573
"""Display information on a test that leaked one or more threads"""
574
# GZ 2010-09-09: A leak summary reported separately from the general
575
# thread debugging would be nice. Tests under subunit
576
# need something not using stream, perhaps adding a
577
# testtools details object would be fitting.
578
if 'threads' in selftest_debug_flags:
579
self.stream.write('%s is leaking, active is now %d\n' %
580
(test.id(), len(active_threads)))
582
def startTestRun(self):
583
self.startTime = time.time()
585
def report_success(self, test):
588
def wasStrictlySuccessful(self):
589
if self.unsupported or self.known_failure_count:
591
return self.wasSuccessful()
594
class TextTestResult(ExtendedTestResult):
595
"""Displays progress and results of tests in text form"""
597
def __init__(self, stream, descriptions, verbosity,
602
ExtendedTestResult.__init__(self, stream, descriptions, verbosity,
603
bench_history, strict)
604
# We no longer pass them around, but just rely on the UIFactory stack
607
warnings.warn("Passing pb to TextTestResult is deprecated")
608
self.pb = self.ui.nested_progress_bar()
609
self.pb.show_pct = False
610
self.pb.show_spinner = False
611
self.pb.show_eta = False,
612
self.pb.show_count = False
613
self.pb.show_bar = False
614
self.pb.update_latency = 0
615
self.pb.show_transport_activity = False
617
def stopTestRun(self):
618
# called when the tests that are going to run have run
621
super(TextTestResult, self).stopTestRun()
623
def report_tests_starting(self):
624
super(TextTestResult, self).report_tests_starting()
625
self.pb.update('[test 0/%d] Starting' % (self.num_tests))
627
def _progress_prefix_text(self):
628
# the longer this text, the less space we have to show the test
630
a = '[%d' % self.count # total that have been run
631
# tests skipped as known not to be relevant are not important enough
633
## if self.skip_count:
634
## a += ', %d skip' % self.skip_count
635
## if self.known_failure_count:
636
## a += '+%dX' % self.known_failure_count
638
a +='/%d' % self.num_tests
640
runtime = time.time() - self._overall_start_time
642
a += '%dm%ds' % (runtime / 60, runtime % 60)
645
total_fail_count = self.error_count + self.failure_count
647
a += ', %d failed' % total_fail_count
648
# if self.unsupported:
649
# a += ', %d missing' % len(self.unsupported)
653
def report_test_start(self, test):
655
self._progress_prefix_text()
657
+ self._shortened_test_description(test))
659
def _test_description(self, test):
660
return self._shortened_test_description(test)
662
def report_error(self, test, err):
663
self.stream.write('ERROR: %s\n %s\n' % (
664
self._test_description(test),
668
def report_failure(self, test, err):
669
self.stream.write('FAIL: %s\n %s\n' % (
670
self._test_description(test),
674
def report_known_failure(self, test, err):
677
def report_unexpected_success(self, test, reason):
678
self.stream.write('FAIL: %s\n %s: %s\n' % (
679
self._test_description(test),
680
"Unexpected success. Should have failed",
684
def report_skip(self, test, reason):
687
def report_not_applicable(self, test, reason):
690
def report_unsupported(self, test, feature):
691
"""test cannot be run because feature is missing."""
694
class VerboseTestResult(ExtendedTestResult):
695
"""Produce long output, with one line per test run plus times"""
697
def _ellipsize_to_right(self, a_string, final_width):
698
"""Truncate and pad a string, keeping the right hand side"""
699
if len(a_string) > final_width:
700
result = '...' + a_string[3-final_width:]
703
return result.ljust(final_width)
705
def report_tests_starting(self):
706
self.stream.write('running %d tests...\n' % self.num_tests)
707
super(VerboseTestResult, self).report_tests_starting()
709
def report_test_start(self, test):
710
name = self._shortened_test_description(test)
711
width = osutils.terminal_width()
712
if width is not None:
713
# width needs space for 6 char status, plus 1 for slash, plus an
714
# 11-char time string, plus a trailing blank
715
# when NUMBERED_DIRS: plus 5 chars on test number, plus 1 char on
717
self.stream.write(self._ellipsize_to_right(name, width-18))
719
self.stream.write(name)
722
def _error_summary(self, err):
724
return '%s%s' % (indent, err[1])
726
def report_error(self, test, err):
727
self.stream.write('ERROR %s\n%s\n'
728
% (self._testTimeString(test),
729
self._error_summary(err)))
731
def report_failure(self, test, err):
732
self.stream.write(' FAIL %s\n%s\n'
733
% (self._testTimeString(test),
734
self._error_summary(err)))
736
def report_known_failure(self, test, err):
737
self.stream.write('XFAIL %s\n%s\n'
738
% (self._testTimeString(test),
739
self._error_summary(err)))
741
def report_unexpected_success(self, test, reason):
742
self.stream.write(' FAIL %s\n%s: %s\n'
743
% (self._testTimeString(test),
744
"Unexpected success. Should have failed",
747
def report_success(self, test):
748
self.stream.write(' OK %s\n' % self._testTimeString(test))
749
for bench_called, stats in getattr(test, '_benchcalls', []):
750
self.stream.write('LSProf output for %s(%s, %s)\n' % bench_called)
751
stats.pprint(file=self.stream)
752
# flush the stream so that we get smooth output. This verbose mode is
753
# used to show the output in PQM.
756
def report_skip(self, test, reason):
757
self.stream.write(' SKIP %s\n%s\n'
758
% (self._testTimeString(test), reason))
760
def report_not_applicable(self, test, reason):
761
self.stream.write(' N/A %s\n %s\n'
762
% (self._testTimeString(test), reason))
764
def report_unsupported(self, test, feature):
765
"""test cannot be run because feature is missing."""
766
self.stream.write("NODEP %s\n The feature '%s' is not available.\n"
767
%(self._testTimeString(test), feature))
770
class TextTestRunner(object):
771
stop_on_failure = False
779
result_decorators=None,
781
"""Create a TextTestRunner.
783
:param result_decorators: An optional list of decorators to apply
784
to the result object being used by the runner. Decorators are
785
applied left to right - the first element in the list is the
788
# stream may know claim to know to write unicode strings, but in older
789
# pythons this goes sufficiently wrong that it is a bad idea. (
790
# specifically a built in file with encoding 'UTF-8' will still try
791
# to encode using ascii.
792
new_encoding = osutils.get_terminal_encoding()
793
codec = codecs.lookup(new_encoding)
794
if isinstance(codec, tuple):
798
encode = codec.encode
799
# GZ 2010-09-08: Really we don't want to be writing arbitrary bytes,
800
# so should swap to the plain codecs.StreamWriter
801
stream = osutils.UnicodeOrBytesToBytesWriter(encode, stream,
803
stream.encoding = new_encoding
805
self.descriptions = descriptions
806
self.verbosity = verbosity
807
self._bench_history = bench_history
808
self._strict = strict
809
self._result_decorators = result_decorators or []
812
"Run the given test case or test suite."
813
if self.verbosity == 1:
814
result_class = TextTestResult
815
elif self.verbosity >= 2:
816
result_class = VerboseTestResult
817
original_result = result_class(self.stream,
820
bench_history=self._bench_history,
823
# Signal to result objects that look at stop early policy to stop,
824
original_result.stop_early = self.stop_on_failure
825
result = original_result
826
for decorator in self._result_decorators:
827
result = decorator(result)
828
result.stop_early = self.stop_on_failure
829
result.startTestRun()
834
# higher level code uses our extended protocol to determine
835
# what exit code to give.
836
return original_result
839
def iter_suite_tests(suite):
840
"""Return all tests in a suite, recursing through nested suites"""
841
if isinstance(suite, unittest.TestCase):
843
elif isinstance(suite, unittest.TestSuite):
845
for r in iter_suite_tests(item):
848
raise Exception('unknown type %r for object %r'
849
% (type(suite), suite))
852
TestSkipped = testtools.testcase.TestSkipped
855
class TestNotApplicable(TestSkipped):
856
"""A test is not applicable to the situation where it was run.
858
This is only normally raised by parameterized tests, if they find that
859
the instance they're constructed upon does not support one aspect
864
# traceback._some_str fails to format exceptions that have the default
865
# __str__ which does an implicit ascii conversion. However, repr() on those
866
# objects works, for all that its not quite what the doctor may have ordered.
867
def _clever_some_str(value):
872
return repr(value).replace('\\n', '\n')
874
return '<unprintable %s object>' % type(value).__name__
876
traceback._some_str = _clever_some_str
879
# deprecated - use self.knownFailure(), or self.expectFailure.
880
KnownFailure = testtools.testcase._ExpectedFailure
883
class UnavailableFeature(Exception):
884
"""A feature required for this test was not available.
886
This can be considered a specialised form of SkippedTest.
888
The feature should be used to construct the exception.
892
class StringIOWrapper(ui_testing.BytesIOWithEncoding):
894
@symbol_versioning.deprecated_method(
895
symbol_versioning.deprecated_in((3, 0)))
896
def __init__(self, s=None):
897
super(StringIOWrapper, self).__init__(s)
900
TestUIFactory = ui_testing.TestUIFactory
903
def isolated_doctest_setUp(test):
904
override_os_environ(test)
905
test._orig_ui_factory = ui.ui_factory
906
ui.ui_factory = ui.SilentUIFactory()
909
def isolated_doctest_tearDown(test):
910
restore_os_environ(test)
911
ui.ui_factory = test._orig_ui_factory
914
def IsolatedDocTestSuite(*args, **kwargs):
915
"""Overrides doctest.DocTestSuite to handle isolation.
917
The method is really a factory and users are expected to use it as such.
920
kwargs['setUp'] = isolated_doctest_setUp
921
kwargs['tearDown'] = isolated_doctest_tearDown
922
return doctest.DocTestSuite(*args, **kwargs)
925
class TestCase(testtools.TestCase):
926
"""Base class for brz unit tests.
928
Tests that need access to disk resources should subclass
929
TestCaseInTempDir not TestCase.
931
Error and debug log messages are redirected from their usual
932
location into a temporary file, the contents of which can be
933
retrieved by _get_log(). We use a real OS file, not an in-memory object,
934
so that it can also capture file IO. When the test completes this file
935
is read into memory and removed from disk.
937
There are also convenience functions to invoke bzr's command-line
938
routine, and to build and check brz trees.
940
In addition to the usual method of overriding tearDown(), this class also
941
allows subclasses to register cleanup functions via addCleanup, which are
942
run in order as the object is torn down. It's less likely this will be
943
accidentally overlooked.
947
# record lsprof data when performing benchmark calls.
948
_gather_lsprof_in_benchmarks = False
950
def __init__(self, methodName='testMethod'):
951
super(TestCase, self).__init__(methodName)
952
self._directory_isolation = True
953
self.exception_handlers.insert(0,
954
(UnavailableFeature, self._do_unsupported_or_skip))
955
self.exception_handlers.insert(0,
956
(TestNotApplicable, self._do_not_applicable))
959
super(TestCase, self).setUp()
961
# At this point we're still accessing the config files in $BRZ_HOME (as
962
# set by the user running selftest).
963
timeout = config.GlobalStack().get('selftest.timeout')
965
timeout_fixture = fixtures.TimeoutFixture(timeout)
966
timeout_fixture.setUp()
967
self.addCleanup(timeout_fixture.cleanUp)
969
for feature in getattr(self, '_test_needs_features', []):
970
self.requireFeature(feature)
971
self._cleanEnvironment()
973
if breezy.global_state is not None:
974
self.overrideAttr(breezy.global_state, 'cmdline_overrides',
975
config.CommandLineStore())
979
self._benchcalls = []
980
self._benchtime = None
982
self._track_transports()
984
self._clear_debug_flags()
985
# Isolate global verbosity level, to make sure it's reproducible
986
# between tests. We should get rid of this altogether: bug 656694. --
988
self.overrideAttr(breezy.trace, '_verbosity_level', 0)
989
self._log_files = set()
990
# Each key in the ``_counters`` dict holds a value for a different
991
# counter. When the test ends, addDetail() should be used to output the
992
# counter values. This happens in install_counter_hook().
994
if 'config_stats' in selftest_debug_flags:
995
self._install_config_stats_hooks()
996
# Do not use i18n for tests (unless the test reverses this)
1002
# The sys preserved stdin/stdout should allow blackbox tests debugging
1003
pdb.Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__
1004
).set_trace(sys._getframe().f_back)
1006
def discardDetail(self, name):
1007
"""Extend the addDetail, getDetails api so we can remove a detail.
1009
eg. brz always adds the 'log' detail at startup, but we don't want to
1010
include it for skipped, xfail, etc tests.
1012
It is safe to call this for a detail that doesn't exist, in case this
1013
gets called multiple times.
1015
# We cheat. details is stored in __details which means we shouldn't
1016
# touch it. but getDetails() returns the dict directly, so we can
1018
details = self.getDetails()
1022
def install_counter_hook(self, hooks, name, counter_name=None):
1023
"""Install a counting hook.
1025
Any hook can be counted as long as it doesn't need to return a value.
1027
:param hooks: Where the hook should be installed.
1029
:param name: The hook name that will be counted.
1031
:param counter_name: The counter identifier in ``_counters``, defaults
1034
_counters = self._counters # Avoid closing over self
1035
if counter_name is None:
1037
if counter_name in _counters:
1038
raise AssertionError('%s is already used as a counter name'
1040
_counters[counter_name] = 0
1041
self.addDetail(counter_name, content.Content(content.UTF8_TEXT,
1042
lambda: ['%d' % (_counters[counter_name],)]))
1043
def increment_counter(*args, **kwargs):
1044
_counters[counter_name] += 1
1045
label = 'count %s calls' % (counter_name,)
1046
hooks.install_named_hook(name, increment_counter, label)
1047
self.addCleanup(hooks.uninstall_named_hook, name, label)
1049
def _install_config_stats_hooks(self):
1050
"""Install config hooks to count hook calls.
1053
for hook_name in ('get', 'set', 'remove', 'load', 'save'):
1054
self.install_counter_hook(config.ConfigHooks, hook_name,
1055
'config.%s' % (hook_name,))
1057
# The OldConfigHooks are private and need special handling to protect
1058
# against recursive tests (tests that run other tests), so we just do
1059
# manually what registering them into _builtin_known_hooks will provide
1061
self.overrideAttr(config, 'OldConfigHooks', config._OldConfigHooks())
1062
for hook_name in ('get', 'set', 'remove', 'load', 'save'):
1063
self.install_counter_hook(config.OldConfigHooks, hook_name,
1064
'old_config.%s' % (hook_name,))
1066
def _clear_debug_flags(self):
1067
"""Prevent externally set debug flags affecting tests.
1069
Tests that want to use debug flags can just set them in the
1070
debug_flags set during setup/teardown.
1072
# Start with a copy of the current debug flags we can safely modify.
1073
self.overrideAttr(debug, 'debug_flags', set(debug.debug_flags))
1074
if 'allow_debug' not in selftest_debug_flags:
1075
debug.debug_flags.clear()
1076
if 'disable_lock_checks' not in selftest_debug_flags:
1077
debug.debug_flags.add('strict_locks')
1079
def _clear_hooks(self):
1080
# prevent hooks affecting tests
1081
known_hooks = hooks.known_hooks
1082
self._preserved_hooks = {}
1083
for key, (parent, name) in known_hooks.iter_parent_objects():
1084
current_hooks = getattr(parent, name)
1085
self._preserved_hooks[parent] = (name, current_hooks)
1086
self._preserved_lazy_hooks = hooks._lazy_hooks
1087
hooks._lazy_hooks = {}
1088
self.addCleanup(self._restoreHooks)
1089
for key, (parent, name) in known_hooks.iter_parent_objects():
1090
factory = known_hooks.get(key)
1091
setattr(parent, name, factory())
1092
# this hook should always be installed
1093
request._install_hook()
1095
def disable_directory_isolation(self):
1096
"""Turn off directory isolation checks."""
1097
self._directory_isolation = False
1099
def enable_directory_isolation(self):
1100
"""Enable directory isolation checks."""
1101
self._directory_isolation = True
1103
def _silenceUI(self):
1104
"""Turn off UI for duration of test"""
1105
# by default the UI is off; tests can turn it on if they want it.
1106
self.overrideAttr(ui, 'ui_factory', ui.SilentUIFactory())
1108
def _check_locks(self):
1109
"""Check that all lock take/release actions have been paired."""
1110
# We always check for mismatched locks. If a mismatch is found, we
1111
# fail unless -Edisable_lock_checks is supplied to selftest, in which
1112
# case we just print a warning.
1114
acquired_locks = [lock for action, lock in self._lock_actions
1115
if action == 'acquired']
1116
released_locks = [lock for action, lock in self._lock_actions
1117
if action == 'released']
1118
broken_locks = [lock for action, lock in self._lock_actions
1119
if action == 'broken']
1120
# trivially, given the tests for lock acquistion and release, if we
1121
# have as many in each list, it should be ok. Some lock tests also
1122
# break some locks on purpose and should be taken into account by
1123
# considering that breaking a lock is just a dirty way of releasing it.
1124
if len(acquired_locks) != (len(released_locks) + len(broken_locks)):
1126
'Different number of acquired and '
1127
'released or broken locks.\n'
1131
(acquired_locks, released_locks, broken_locks))
1132
if not self._lock_check_thorough:
1133
# Rather than fail, just warn
1134
print("Broken test %s: %s" % (self, message))
1138
def _track_locks(self):
1139
"""Track lock activity during tests."""
1140
self._lock_actions = []
1141
if 'disable_lock_checks' in selftest_debug_flags:
1142
self._lock_check_thorough = False
1144
self._lock_check_thorough = True
1146
self.addCleanup(self._check_locks)
1147
_mod_lock.Lock.hooks.install_named_hook('lock_acquired',
1148
self._lock_acquired, None)
1149
_mod_lock.Lock.hooks.install_named_hook('lock_released',
1150
self._lock_released, None)
1151
_mod_lock.Lock.hooks.install_named_hook('lock_broken',
1152
self._lock_broken, None)
1154
def _lock_acquired(self, result):
1155
self._lock_actions.append(('acquired', result))
1157
def _lock_released(self, result):
1158
self._lock_actions.append(('released', result))
1160
def _lock_broken(self, result):
1161
self._lock_actions.append(('broken', result))
1163
def permit_dir(self, name):
1164
"""Permit a directory to be used by this test. See permit_url."""
1165
name_transport = _mod_transport.get_transport_from_path(name)
1166
self.permit_url(name)
1167
self.permit_url(name_transport.base)
1169
def permit_url(self, url):
1170
"""Declare that url is an ok url to use in this test.
1172
Do this for memory transports, temporary test directory etc.
1174
Do not do this for the current working directory, /tmp, or any other
1175
preexisting non isolated url.
1177
if not url.endswith('/'):
1179
self._bzr_selftest_roots.append(url)
1181
def permit_source_tree_branch_repo(self):
1182
"""Permit the source tree brz is running from to be opened.
1184
Some code such as breezy.version attempts to read from the brz branch
1185
that brz is executing from (if any). This method permits that directory
1186
to be used in the test suite.
1188
path = self.get_source_path()
1189
self.record_directory_isolation()
1192
workingtree.WorkingTree.open(path)
1193
except (errors.NotBranchError, errors.NoWorkingTree):
1194
raise TestSkipped('Needs a working tree of brz sources')
1196
self.enable_directory_isolation()
1198
def _preopen_isolate_transport(self, transport):
1199
"""Check that all transport openings are done in the test work area."""
1200
while isinstance(transport, pathfilter.PathFilteringTransport):
1201
# Unwrap pathfiltered transports
1202
transport = transport.server.backing_transport.clone(
1203
transport._filter('.'))
1204
url = transport.base
1205
# ReadonlySmartTCPServer_for_testing decorates the backing transport
1206
# urls it is given by prepending readonly+. This is appropriate as the
1207
# client shouldn't know that the server is readonly (or not readonly).
1208
# We could register all servers twice, with readonly+ prepending, but
1209
# that makes for a long list; this is about the same but easier to
1211
if url.startswith('readonly+'):
1212
url = url[len('readonly+'):]
1213
self._preopen_isolate_url(url)
1215
def _preopen_isolate_url(self, url):
1216
if not self._directory_isolation:
1218
if self._directory_isolation == 'record':
1219
self._bzr_selftest_roots.append(url)
1221
# This prevents all transports, including e.g. sftp ones backed on disk
1222
# from working unless they are explicitly granted permission. We then
1223
# depend on the code that sets up test transports to check that they are
1224
# appropriately isolated and enable their use by calling
1225
# self.permit_transport()
1226
if not osutils.is_inside_any(self._bzr_selftest_roots, url):
1227
raise errors.BzrError("Attempt to escape test isolation: %r %r"
1228
% (url, self._bzr_selftest_roots))
1230
def record_directory_isolation(self):
1231
"""Gather accessed directories to permit later access.
1233
This is used for tests that access the branch brz is running from.
1235
self._directory_isolation = "record"
1237
def start_server(self, transport_server, backing_server=None):
1238
"""Start transport_server for this test.
1240
This starts the server, registers a cleanup for it and permits the
1241
server's urls to be used.
1243
if backing_server is None:
1244
transport_server.start_server()
1246
transport_server.start_server(backing_server)
1247
self.addCleanup(transport_server.stop_server)
1248
# Obtain a real transport because if the server supplies a password, it
1249
# will be hidden from the base on the client side.
1250
t = _mod_transport.get_transport_from_url(transport_server.get_url())
1251
# Some transport servers effectively chroot the backing transport;
1252
# others like SFTPServer don't - users of the transport can walk up the
1253
# transport to read the entire backing transport. This wouldn't matter
1254
# except that the workdir tests are given - and that they expect the
1255
# server's url to point at - is one directory under the safety net. So
1256
# Branch operations into the transport will attempt to walk up one
1257
# directory. Chrooting all servers would avoid this but also mean that
1258
# we wouldn't be testing directly against non-root urls. Alternatively
1259
# getting the test framework to start the server with a backing server
1260
# at the actual safety net directory would work too, but this then
1261
# means that the self.get_url/self.get_transport methods would need
1262
# to transform all their results. On balance its cleaner to handle it
1263
# here, and permit a higher url when we have one of these transports.
1264
if t.base.endswith('/work/'):
1265
# we have safety net/test root/work
1266
t = t.clone('../..')
1267
elif isinstance(transport_server,
1268
test_server.SmartTCPServer_for_testing):
1269
# The smart server adds a path similar to work, which is traversed
1270
# up from by the client. But the server is chrooted - the actual
1271
# backing transport is not escaped from, and VFS requests to the
1272
# root will error (because they try to escape the chroot).
1274
while t2.base != t.base:
1277
self.permit_url(t.base)
1279
def _track_transports(self):
1280
"""Install checks for transport usage."""
1281
# TestCase has no safe place it can write to.
1282
self._bzr_selftest_roots = []
1283
# Currently the easiest way to be sure that nothing is going on is to
1284
# hook into brz dir opening. This leaves a small window of error for
1285
# transport tests, but they are well known, and we can improve on this
1287
controldir.ControlDir.hooks.install_named_hook("pre_open",
1288
self._preopen_isolate_transport, "Check brz directories are safe.")
1290
def _ndiff_strings(self, a, b):
1291
"""Return ndiff between two strings containing lines.
1293
A trailing newline is added if missing to make the strings
1295
if b and b[-1] != '\n':
1297
if a and a[-1] != '\n':
1299
difflines = difflib.ndiff(a.splitlines(True),
1301
linejunk=lambda x: False,
1302
charjunk=lambda x: False)
1303
return ''.join(difflines)
1305
def assertEqual(self, a, b, message=''):
1309
except UnicodeError as e:
1310
# If we can't compare without getting a UnicodeError, then
1311
# obviously they are different
1312
trace.mutter('UnicodeError: %s', e)
1315
raise AssertionError("%snot equal:\na = %s\nb = %s\n"
1317
pprint.pformat(a), pprint.pformat(b)))
1319
# FIXME: This is deprecated in unittest2 but plugins may still use it so we
1320
# need a deprecation period for them -- vila 2016-02-01
1321
assertEquals = assertEqual
1323
def assertEqualDiff(self, a, b, message=None):
1324
"""Assert two texts are equal, if not raise an exception.
1326
This is intended for use with multi-line strings where it can
1327
be hard to find the differences by eye.
1329
# TODO: perhaps override assertEqual to call this for strings?
1333
message = "texts not equal:\n"
1335
message = 'first string is missing a final newline.\n'
1337
message = 'second string is missing a final newline.\n'
1338
raise AssertionError(message +
1339
self._ndiff_strings(a, b))
1341
def assertEqualMode(self, mode, mode_test):
1342
self.assertEqual(mode, mode_test,
1343
'mode mismatch %o != %o' % (mode, mode_test))
1345
def assertEqualStat(self, expected, actual):
1346
"""assert that expected and actual are the same stat result.
1348
:param expected: A stat result.
1349
:param actual: A stat result.
1350
:raises AssertionError: If the expected and actual stat values differ
1351
other than by atime.
1353
self.assertEqual(expected.st_size, actual.st_size,
1354
'st_size did not match')
1355
self.assertEqual(expected.st_mtime, actual.st_mtime,
1356
'st_mtime did not match')
1357
self.assertEqual(expected.st_ctime, actual.st_ctime,
1358
'st_ctime did not match')
1359
if sys.platform == 'win32':
1360
# On Win32 both 'dev' and 'ino' cannot be trusted. In python2.4 it
1361
# is 'dev' that varies, in python 2.5 (6?) it is st_ino that is
1362
# odd. We just force it to always be 0 to avoid any problems.
1363
self.assertEqual(0, expected.st_dev)
1364
self.assertEqual(0, actual.st_dev)
1365
self.assertEqual(0, expected.st_ino)
1366
self.assertEqual(0, actual.st_ino)
1368
self.assertEqual(expected.st_dev, actual.st_dev,
1369
'st_dev did not match')
1370
self.assertEqual(expected.st_ino, actual.st_ino,
1371
'st_ino did not match')
1372
self.assertEqual(expected.st_mode, actual.st_mode,
1373
'st_mode did not match')
1375
def assertLength(self, length, obj_with_len):
1376
"""Assert that obj_with_len is of length length."""
1377
if len(obj_with_len) != length:
1378
self.fail("Incorrect length: wanted %d, got %d for %r" % (
1379
length, len(obj_with_len), obj_with_len))
1381
def assertLogsError(self, exception_class, func, *args, **kwargs):
1382
"""Assert that `func(*args, **kwargs)` quietly logs a specific error.
1385
orig_log_exception_quietly = trace.log_exception_quietly
1388
orig_log_exception_quietly()
1389
captured.append(sys.exc_info()[1])
1390
trace.log_exception_quietly = capture
1391
func(*args, **kwargs)
1393
trace.log_exception_quietly = orig_log_exception_quietly
1394
self.assertLength(1, captured)
1396
self.assertIsInstance(err, exception_class)
1399
def assertPositive(self, val):
1400
"""Assert that val is greater than 0."""
1401
self.assertTrue(val > 0, 'expected a positive value, but got %s' % val)
1403
def assertNegative(self, val):
1404
"""Assert that val is less than 0."""
1405
self.assertTrue(val < 0, 'expected a negative value, but got %s' % val)
1407
def assertStartsWith(self, s, prefix):
1408
if not s.startswith(prefix):
1409
raise AssertionError('string %r does not start with %r' % (s, prefix))
1411
def assertEndsWith(self, s, suffix):
1412
"""Asserts that s ends with suffix."""
1413
if not s.endswith(suffix):
1414
raise AssertionError('string %r does not end with %r' % (s, suffix))
1416
def assertContainsRe(self, haystack, needle_re, flags=0):
1417
"""Assert that a contains something matching a regular expression."""
1418
if not re.search(needle_re, haystack, flags):
1419
if '\n' in haystack or len(haystack) > 60:
1420
# a long string, format it in a more readable way
1421
raise AssertionError(
1422
'pattern "%s" not found in\n"""\\\n%s"""\n'
1423
% (needle_re, haystack))
1425
raise AssertionError('pattern "%s" not found in "%s"'
1426
% (needle_re, haystack))
1428
def assertNotContainsRe(self, haystack, needle_re, flags=0):
1429
"""Assert that a does not match a regular expression"""
1430
if re.search(needle_re, haystack, flags):
1431
raise AssertionError('pattern "%s" found in "%s"'
1432
% (needle_re, haystack))
1434
def assertContainsString(self, haystack, needle):
1435
if haystack.find(needle) == -1:
1436
self.fail("string %r not found in '''%s'''" % (needle, haystack))
1438
def assertNotContainsString(self, haystack, needle):
1439
if haystack.find(needle) != -1:
1440
self.fail("string %r found in '''%s'''" % (needle, haystack))
1442
def assertSubset(self, sublist, superlist):
1443
"""Assert that every entry in sublist is present in superlist."""
1444
missing = set(sublist) - set(superlist)
1445
if len(missing) > 0:
1446
raise AssertionError("value(s) %r not present in container %r" %
1447
(missing, superlist))
1449
def assertListRaises(self, excClass, func, *args, **kwargs):
1450
"""Fail unless excClass is raised when the iterator from func is used.
1452
Many functions can return generators this makes sure
1453
to wrap them in a list() call to make sure the whole generator
1454
is run, and that the proper exception is raised.
1457
list(func(*args, **kwargs))
1458
except excClass as e:
1461
if getattr(excClass,'__name__', None) is not None:
1462
excName = excClass.__name__
1464
excName = str(excClass)
1465
raise self.failureException("%s not raised" % excName)
1467
def assertRaises(self, excClass, callableObj, *args, **kwargs):
1468
"""Assert that a callable raises a particular exception.
1470
:param excClass: As for the except statement, this may be either an
1471
exception class, or a tuple of classes.
1472
:param callableObj: A callable, will be passed ``*args`` and
1475
Returns the exception so that you can examine it.
1478
callableObj(*args, **kwargs)
1479
except excClass as e:
1482
if getattr(excClass,'__name__', None) is not None:
1483
excName = excClass.__name__
1486
excName = str(excClass)
1487
raise self.failureException("%s not raised" % excName)
1489
def assertIs(self, left, right, message=None):
1490
if not (left is right):
1491
if message is not None:
1492
raise AssertionError(message)
1494
raise AssertionError("%r is not %r." % (left, right))
1496
def assertIsNot(self, left, right, message=None):
1498
if message is not None:
1499
raise AssertionError(message)
1501
raise AssertionError("%r is %r." % (left, right))
1503
def assertTransportMode(self, transport, path, mode):
1504
"""Fail if a path does not have mode "mode".
1506
If modes are not supported on this transport, the assertion is ignored.
1508
if not transport._can_roundtrip_unix_modebits():
1510
path_stat = transport.stat(path)
1511
actual_mode = stat.S_IMODE(path_stat.st_mode)
1512
self.assertEqual(mode, actual_mode,
1513
'mode of %r incorrect (%s != %s)'
1514
% (path, oct(mode), oct(actual_mode)))
1516
def assertIsSameRealPath(self, path1, path2):
1517
"""Fail if path1 and path2 points to different files"""
1518
self.assertEqual(osutils.realpath(path1),
1519
osutils.realpath(path2),
1520
"apparent paths:\na = %s\nb = %s\n," % (path1, path2))
1522
def assertIsInstance(self, obj, kls, msg=None):
1523
"""Fail if obj is not an instance of kls
1525
:param msg: Supplementary message to show if the assertion fails.
1527
if not isinstance(obj, kls):
1528
m = "%r is an instance of %s rather than %s" % (
1529
obj, obj.__class__, kls)
1534
def assertFileEqual(self, content, path):
1535
"""Fail if path does not contain 'content'."""
1536
self.assertPathExists(path)
1537
f = file(path, 'rb')
1542
self.assertEqualDiff(content, s)
1544
def assertDocstring(self, expected_docstring, obj):
1545
"""Fail if obj does not have expected_docstring"""
1547
# With -OO the docstring should be None instead
1548
self.assertIs(obj.__doc__, None)
1550
self.assertEqual(expected_docstring, obj.__doc__)
1552
def assertPathExists(self, path):
1553
"""Fail unless path or paths, which may be abs or relative, exist."""
1554
if not isinstance(path, basestring):
1556
self.assertPathExists(p)
1558
self.assertTrue(osutils.lexists(path),
1559
path + " does not exist")
1561
def assertPathDoesNotExist(self, path):
1562
"""Fail if path or paths, which may be abs or relative, exist."""
1563
if not isinstance(path, basestring):
1565
self.assertPathDoesNotExist(p)
1567
self.assertFalse(osutils.lexists(path),
1570
def _capture_deprecation_warnings(self, a_callable, *args, **kwargs):
1571
"""A helper for callDeprecated and applyDeprecated.
1573
:param a_callable: A callable to call.
1574
:param args: The positional arguments for the callable
1575
:param kwargs: The keyword arguments for the callable
1576
:return: A tuple (warnings, result). result is the result of calling
1577
a_callable(``*args``, ``**kwargs``).
1580
def capture_warnings(msg, cls=None, stacklevel=None):
1581
# we've hooked into a deprecation specific callpath,
1582
# only deprecations should getting sent via it.
1583
self.assertEqual(cls, DeprecationWarning)
1584
local_warnings.append(msg)
1585
original_warning_method = symbol_versioning.warn
1586
symbol_versioning.set_warning_method(capture_warnings)
1588
result = a_callable(*args, **kwargs)
1590
symbol_versioning.set_warning_method(original_warning_method)
1591
return (local_warnings, result)
1593
def applyDeprecated(self, deprecation_format, a_callable, *args, **kwargs):
1594
"""Call a deprecated callable without warning the user.
1596
Note that this only captures warnings raised by symbol_versioning.warn,
1597
not other callers that go direct to the warning module.
1599
To test that a deprecated method raises an error, do something like
1600
this (remember that both assertRaises and applyDeprecated delays *args
1601
and **kwargs passing)::
1603
self.assertRaises(errors.ReservedId,
1604
self.applyDeprecated,
1605
deprecated_in((1, 5, 0)),
1609
:param deprecation_format: The deprecation format that the callable
1610
should have been deprecated with. This is the same type as the
1611
parameter to deprecated_method/deprecated_function. If the
1612
callable is not deprecated with this format, an assertion error
1614
:param a_callable: A callable to call. This may be a bound method or
1615
a regular function. It will be called with ``*args`` and
1617
:param args: The positional arguments for the callable
1618
:param kwargs: The keyword arguments for the callable
1619
:return: The result of a_callable(``*args``, ``**kwargs``)
1621
call_warnings, result = self._capture_deprecation_warnings(a_callable,
1623
expected_first_warning = symbol_versioning.deprecation_string(
1624
a_callable, deprecation_format)
1625
if len(call_warnings) == 0:
1626
self.fail("No deprecation warning generated by call to %s" %
1628
self.assertEqual(expected_first_warning, call_warnings[0])
1631
def callCatchWarnings(self, fn, *args, **kw):
1632
"""Call a callable that raises python warnings.
1634
The caller's responsible for examining the returned warnings.
1636
If the callable raises an exception, the exception is not
1637
caught and propagates up to the caller. In that case, the list
1638
of warnings is not available.
1640
:returns: ([warning_object, ...], fn_result)
1642
# XXX: This is not perfect, because it completely overrides the
1643
# warnings filters, and some code may depend on suppressing particular
1644
# warnings. It's the easiest way to insulate ourselves from -Werror,
1645
# though. -- Andrew, 20071062
1647
def _catcher(message, category, filename, lineno, file=None, line=None):
1648
# despite the name, 'message' is normally(?) a Warning subclass
1650
wlist.append(message)
1651
saved_showwarning = warnings.showwarning
1652
saved_filters = warnings.filters
1654
warnings.showwarning = _catcher
1655
warnings.filters = []
1656
result = fn(*args, **kw)
1658
warnings.showwarning = saved_showwarning
1659
warnings.filters = saved_filters
1660
return wlist, result
1662
def callDeprecated(self, expected, callable, *args, **kwargs):
1663
"""Assert that a callable is deprecated in a particular way.
1665
This is a very precise test for unusual requirements. The
1666
applyDeprecated helper function is probably more suited for most tests
1667
as it allows you to simply specify the deprecation format being used
1668
and will ensure that that is issued for the function being called.
1670
Note that this only captures warnings raised by symbol_versioning.warn,
1671
not other callers that go direct to the warning module. To catch
1672
general warnings, use callCatchWarnings.
1674
:param expected: a list of the deprecation warnings expected, in order
1675
:param callable: The callable to call
1676
:param args: The positional arguments for the callable
1677
:param kwargs: The keyword arguments for the callable
1679
call_warnings, result = self._capture_deprecation_warnings(callable,
1681
self.assertEqual(expected, call_warnings)
1684
def _startLogFile(self):
1685
"""Setup a in-memory target for bzr and testcase log messages"""
1686
pseudo_log_file = BytesIO()
1687
def _get_log_contents_for_weird_testtools_api():
1688
return [pseudo_log_file.getvalue().decode(
1689
"utf-8", "replace").encode("utf-8")]
1690
self.addDetail("log", content.Content(content.ContentType("text",
1691
"plain", {"charset": "utf8"}),
1692
_get_log_contents_for_weird_testtools_api))
1693
self._log_file = pseudo_log_file
1694
self._log_memento = trace.push_log_file(self._log_file)
1695
self.addCleanup(self._finishLogFile)
1697
def _finishLogFile(self):
1698
"""Flush and dereference the in-memory log for this testcase"""
1699
if trace._trace_file:
1700
# flush the log file, to get all content
1701
trace._trace_file.flush()
1702
trace.pop_log_file(self._log_memento)
1703
# The logging module now tracks references for cleanup so discard ours
1704
del self._log_memento
1706
def thisFailsStrictLockCheck(self):
1707
"""It is known that this test would fail with -Dstrict_locks.
1709
By default, all tests are run with strict lock checking unless
1710
-Edisable_lock_checks is supplied. However there are some tests which
1711
we know fail strict locks at this point that have not been fixed.
1712
They should call this function to disable the strict checking.
1714
This should be used sparingly, it is much better to fix the locking
1715
issues rather than papering over the problem by calling this function.
1717
debug.debug_flags.discard('strict_locks')
1719
def overrideAttr(self, obj, attr_name, new=_unitialized_attr):
1720
"""Overrides an object attribute restoring it after the test.
1722
:note: This should be used with discretion; you should think about
1723
whether it's better to make the code testable without monkey-patching.
1725
:param obj: The object that will be mutated.
1727
:param attr_name: The attribute name we want to preserve/override in
1730
:param new: The optional value we want to set the attribute to.
1732
:returns: The actual attr value.
1734
# The actual value is captured by the call below
1735
value = getattr(obj, attr_name, _unitialized_attr)
1736
if value is _unitialized_attr:
1737
# When the test completes, the attribute should not exist, but if
1738
# we aren't setting a value, we don't need to do anything.
1739
if new is not _unitialized_attr:
1740
self.addCleanup(delattr, obj, attr_name)
1742
self.addCleanup(setattr, obj, attr_name, value)
1743
if new is not _unitialized_attr:
1744
setattr(obj, attr_name, new)
1747
def overrideEnv(self, name, new):
1748
"""Set an environment variable, and reset it after the test.
1750
:param name: The environment variable name.
1752
:param new: The value to set the variable to. If None, the
1753
variable is deleted from the environment.
1755
:returns: The actual variable value.
1757
value = osutils.set_or_unset_env(name, new)
1758
self.addCleanup(osutils.set_or_unset_env, name, value)
1761
def recordCalls(self, obj, attr_name):
1762
"""Monkeypatch in a wrapper that will record calls.
1764
The monkeypatch is automatically removed when the test concludes.
1766
:param obj: The namespace holding the reference to be replaced;
1767
typically a module, class, or object.
1768
:param attr_name: A string for the name of the attribute to
1770
:returns: A list that will be extended with one item every time the
1771
function is called, with a tuple of (args, kwargs).
1775
def decorator(*args, **kwargs):
1776
calls.append((args, kwargs))
1777
return orig(*args, **kwargs)
1778
orig = self.overrideAttr(obj, attr_name, decorator)
1781
def _cleanEnvironment(self):
1782
for name, value in isolated_environ.items():
1783
self.overrideEnv(name, value)
1785
def _restoreHooks(self):
1786
for klass, (name, hooks) in self._preserved_hooks.items():
1787
setattr(klass, name, hooks)
1788
self._preserved_hooks.clear()
1789
breezy.hooks._lazy_hooks = self._preserved_lazy_hooks
1790
self._preserved_lazy_hooks.clear()
1792
def knownFailure(self, reason):
1793
"""Declare that this test fails for a known reason
1795
Tests that are known to fail should generally be using expectedFailure
1796
with an appropriate reverse assertion if a change could cause the test
1797
to start passing. Conversely if the test has no immediate prospect of
1798
succeeding then using skip is more suitable.
1800
When this method is called while an exception is being handled, that
1801
traceback will be used, otherwise a new exception will be thrown to
1802
provide one but won't be reported.
1804
self._add_reason(reason)
1806
exc_info = sys.exc_info()
1807
if exc_info != (None, None, None):
1808
self._report_traceback(exc_info)
1811
raise self.failureException(reason)
1812
except self.failureException:
1813
exc_info = sys.exc_info()
1814
# GZ 02-08-2011: Maybe cleanup this err.exc_info attribute too?
1815
raise testtools.testcase._ExpectedFailure(exc_info)
1819
def _suppress_log(self):
1820
"""Remove the log info from details."""
1821
self.discardDetail('log')
1823
def _do_skip(self, result, reason):
1824
self._suppress_log()
1825
addSkip = getattr(result, 'addSkip', None)
1826
if not callable(addSkip):
1827
result.addSuccess(result)
1829
addSkip(self, reason)
1832
def _do_known_failure(self, result, e):
1833
self._suppress_log()
1834
err = sys.exc_info()
1835
addExpectedFailure = getattr(result, 'addExpectedFailure', None)
1836
if addExpectedFailure is not None:
1837
addExpectedFailure(self, err)
1839
result.addSuccess(self)
1842
def _do_not_applicable(self, result, e):
1844
reason = 'No reason given'
1847
self._suppress_log ()
1848
addNotApplicable = getattr(result, 'addNotApplicable', None)
1849
if addNotApplicable is not None:
1850
result.addNotApplicable(self, reason)
1852
self._do_skip(result, reason)
1855
def _report_skip(self, result, err):
1856
"""Override the default _report_skip.
1858
We want to strip the 'log' detail. If we waint until _do_skip, it has
1859
already been formatted into the 'reason' string, and we can't pull it
1862
self._suppress_log()
1863
super(TestCase, self)._report_skip(self, result, err)
1866
def _report_expected_failure(self, result, err):
1869
See _report_skip for motivation.
1871
self._suppress_log()
1872
super(TestCase, self)._report_expected_failure(self, result, err)
1875
def _do_unsupported_or_skip(self, result, e):
1877
self._suppress_log()
1878
addNotSupported = getattr(result, 'addNotSupported', None)
1879
if addNotSupported is not None:
1880
result.addNotSupported(self, reason)
1882
self._do_skip(result, reason)
1884
def time(self, callable, *args, **kwargs):
1885
"""Run callable and accrue the time it takes to the benchmark time.
1887
If lsprofiling is enabled (i.e. by --lsprof-time to brz selftest) then
1888
this will cause lsprofile statistics to be gathered and stored in
1891
if self._benchtime is None:
1892
self.addDetail('benchtime', content.Content(content.ContentType(
1893
"text", "plain"), lambda:[str(self._benchtime)]))
1897
if not self._gather_lsprof_in_benchmarks:
1898
return callable(*args, **kwargs)
1900
# record this benchmark
1901
ret, stats = breezy.lsprof.profile(callable, *args, **kwargs)
1903
self._benchcalls.append(((callable, args, kwargs), stats))
1906
self._benchtime += time.time() - start
1908
def log(self, *args):
1912
"""Get a unicode string containing the log from breezy.trace.
1914
Undecodable characters are replaced.
1916
return u"".join(self.getDetails()['log'].iter_text())
1918
def requireFeature(self, feature):
1919
"""This test requires a specific feature is available.
1921
:raises UnavailableFeature: When feature is not available.
1923
if not feature.available():
1924
raise UnavailableFeature(feature)
1926
def _run_bzr_autosplit(self, args, retcode, encoding, stdin,
1928
"""Run bazaar command line, splitting up a string command line."""
1929
if isinstance(args, string_types):
1930
args = shlex.split(args)
1931
return self._run_bzr_core(args, retcode=retcode,
1932
encoding=encoding, stdin=stdin, working_dir=working_dir,
1935
def _run_bzr_core(self, args, retcode, encoding, stdin,
1937
# Clear chk_map page cache, because the contents are likely to mask
1939
chk_map.clear_cache()
1940
if encoding is None:
1941
encoding = osutils.get_user_encoding()
1943
self.log('run brz: %r', args)
1945
stdout = ui_testing.BytesIOWithEncoding()
1946
stderr = ui_testing.BytesIOWithEncoding()
1947
stdout.encoding = stderr.encoding = encoding
1949
# FIXME: don't call into logging here
1950
handler = trace.EncodedStreamHandler(
1951
stderr, errors="replace", level=logging.INFO)
1952
logger = logging.getLogger('')
1953
logger.addHandler(handler)
1955
self._last_cmd_stdout = codecs.getwriter(encoding)(stdout)
1956
self._last_cmd_stderr = codecs.getwriter(encoding)(stderr)
1958
old_ui_factory = ui.ui_factory
1959
ui.ui_factory = ui_testing.TestUIFactory(
1961
stdout=self._last_cmd_stdout,
1962
stderr=self._last_cmd_stderr)
1965
if working_dir is not None:
1966
cwd = osutils.getcwd()
1967
os.chdir(working_dir)
1970
result = self.apply_redirected(
1971
ui.ui_factory.stdin,
1973
_mod_commands.run_bzr_catch_user_errors,
1976
logger.removeHandler(handler)
1977
ui.ui_factory = old_ui_factory
1981
out = stdout.getvalue()
1982
err = stderr.getvalue()
1984
self.log('output:\n%r', out)
1986
self.log('errors:\n%r', err)
1987
if retcode is not None:
1988
self.assertEqual(retcode, result,
1989
message='Unexpected return code')
1990
return result, out, err
1992
def run_bzr(self, args, retcode=0, stdin=None, encoding=None,
1993
working_dir=None, error_regexes=[]):
1994
"""Invoke brz, as if it were run from the command line.
1996
The argument list should not include the brz program name - the
1997
first argument is normally the brz command. Arguments may be
1998
passed in three ways:
2000
1- A list of strings, eg ["commit", "a"]. This is recommended
2001
when the command contains whitespace or metacharacters, or
2002
is built up at run time.
2004
2- A single string, eg "add a". This is the most convenient
2005
for hardcoded commands.
2007
This runs brz through the interface that catches and reports
2008
errors, and with logging set to something approximating the
2009
default, so that error reporting can be checked.
2011
This should be the main method for tests that want to exercise the
2012
overall behavior of the brz application (rather than a unit test
2013
or a functional test of the library.)
2015
This sends the stdout/stderr results into the test's log,
2016
where it may be useful for debugging. See also run_captured.
2018
:keyword stdin: A string to be used as stdin for the command.
2019
:keyword retcode: The status code the command should return;
2021
:keyword working_dir: The directory to run the command in
2022
:keyword error_regexes: A list of expected error messages. If
2023
specified they must be seen in the error output of the command.
2025
retcode, out, err = self._run_bzr_autosplit(
2030
working_dir=working_dir,
2032
self.assertIsInstance(error_regexes, (list, tuple))
2033
for regex in error_regexes:
2034
self.assertContainsRe(err, regex)
2037
def run_bzr_error(self, error_regexes, *args, **kwargs):
2038
"""Run brz, and check that stderr contains the supplied regexes
2040
:param error_regexes: Sequence of regular expressions which
2041
must each be found in the error output. The relative ordering
2043
:param args: command-line arguments for brz
2044
:param kwargs: Keyword arguments which are interpreted by run_brz
2045
This function changes the default value of retcode to be 3,
2046
since in most cases this is run when you expect brz to fail.
2048
:return: (out, err) The actual output of running the command (in case
2049
you want to do more inspection)
2053
# Make sure that commit is failing because there is nothing to do
2054
self.run_bzr_error(['no changes to commit'],
2055
['commit', '-m', 'my commit comment'])
2056
# Make sure --strict is handling an unknown file, rather than
2057
# giving us the 'nothing to do' error
2058
self.build_tree(['unknown'])
2059
self.run_bzr_error(['Commit refused because there are unknown files'],
2060
['commit', --strict', '-m', 'my commit comment'])
2062
kwargs.setdefault('retcode', 3)
2063
kwargs['error_regexes'] = error_regexes
2064
out, err = self.run_bzr(*args, **kwargs)
2067
def run_bzr_subprocess(self, *args, **kwargs):
2068
"""Run brz in a subprocess for testing.
2070
This starts a new Python interpreter and runs brz in there.
2071
This should only be used for tests that have a justifiable need for
2072
this isolation: e.g. they are testing startup time, or signal
2073
handling, or early startup code, etc. Subprocess code can't be
2074
profiled or debugged so easily.
2076
:keyword retcode: The status code that is expected. Defaults to 0. If
2077
None is supplied, the status code is not checked.
2078
:keyword env_changes: A dictionary which lists changes to environment
2079
variables. A value of None will unset the env variable.
2080
The values must be strings. The change will only occur in the
2081
child, so you don't need to fix the environment after running.
2082
:keyword universal_newlines: Convert CRLF => LF
2083
:keyword allow_plugins: By default the subprocess is run with
2084
--no-plugins to ensure test reproducibility. Also, it is possible
2085
for system-wide plugins to create unexpected output on stderr,
2086
which can cause unnecessary test failures.
2088
env_changes = kwargs.get('env_changes', {})
2089
working_dir = kwargs.get('working_dir', None)
2090
allow_plugins = kwargs.get('allow_plugins', False)
2092
if isinstance(args[0], list):
2094
elif isinstance(args[0], basestring):
2095
args = list(shlex.split(args[0]))
2097
raise ValueError("passing varargs to run_bzr_subprocess")
2098
process = self.start_bzr_subprocess(args, env_changes=env_changes,
2099
working_dir=working_dir,
2100
allow_plugins=allow_plugins)
2101
# We distinguish between retcode=None and retcode not passed.
2102
supplied_retcode = kwargs.get('retcode', 0)
2103
return self.finish_bzr_subprocess(process, retcode=supplied_retcode,
2104
universal_newlines=kwargs.get('universal_newlines', False),
2107
def start_bzr_subprocess(self, process_args, env_changes=None,
2108
skip_if_plan_to_signal=False,
2110
allow_plugins=False, stderr=subprocess.PIPE):
2111
"""Start brz in a subprocess for testing.
2113
This starts a new Python interpreter and runs brz in there.
2114
This should only be used for tests that have a justifiable need for
2115
this isolation: e.g. they are testing startup time, or signal
2116
handling, or early startup code, etc. Subprocess code can't be
2117
profiled or debugged so easily.
2119
:param process_args: a list of arguments to pass to the brz executable,
2120
for example ``['--version']``.
2121
:param env_changes: A dictionary which lists changes to environment
2122
variables. A value of None will unset the env variable.
2123
The values must be strings. The change will only occur in the
2124
child, so you don't need to fix the environment after running.
2125
:param skip_if_plan_to_signal: raise TestSkipped when true and system
2126
doesn't support signalling subprocesses.
2127
:param allow_plugins: If False (default) pass --no-plugins to brz.
2128
:param stderr: file to use for the subprocess's stderr. Valid values
2129
are those valid for the stderr argument of `subprocess.Popen`.
2130
Default value is ``subprocess.PIPE``.
2132
:returns: Popen object for the started process.
2134
if skip_if_plan_to_signal:
2135
if os.name != "posix":
2136
raise TestSkipped("Sending signals not supported")
2138
if env_changes is None:
2140
# Because $HOME is set to a tempdir for the context of a test, modules
2141
# installed in the user dir will not be found unless $PYTHONUSERBASE
2142
# gets set to the computed directory of this parent process.
2143
if site.USER_BASE is not None:
2144
env_changes["PYTHONUSERBASE"] = site.USER_BASE
2147
def cleanup_environment():
2148
for env_var, value in env_changes.items():
2149
old_env[env_var] = osutils.set_or_unset_env(env_var, value)
2151
def restore_environment():
2152
for env_var, value in old_env.items():
2153
osutils.set_or_unset_env(env_var, value)
2155
bzr_path = self.get_brz_path()
2158
if working_dir is not None:
2159
cwd = osutils.getcwd()
2160
os.chdir(working_dir)
2163
# win32 subprocess doesn't support preexec_fn
2164
# so we will avoid using it on all platforms, just to
2165
# make sure the code path is used, and we don't break on win32
2166
cleanup_environment()
2167
# Include the subprocess's log file in the test details, in case
2168
# the test fails due to an error in the subprocess.
2169
self._add_subprocess_log(trace._get_brz_log_filename())
2170
command = [sys.executable]
2171
# frozen executables don't need the path to bzr
2172
if getattr(sys, "frozen", None) is None:
2173
command.append(bzr_path)
2174
if not allow_plugins:
2175
command.append('--no-plugins')
2176
command.extend(process_args)
2177
process = self._popen(command, stdin=subprocess.PIPE,
2178
stdout=subprocess.PIPE,
2181
restore_environment()
2187
def _add_subprocess_log(self, log_file_path):
2188
if len(self._log_files) == 0:
2189
# Register an addCleanup func. We do this on the first call to
2190
# _add_subprocess_log rather than in TestCase.setUp so that this
2191
# addCleanup is registered after any cleanups for tempdirs that
2192
# subclasses might create, which will probably remove the log file
2194
self.addCleanup(self._subprocess_log_cleanup)
2195
# self._log_files is a set, so if a log file is reused we won't grab it
2197
self._log_files.add(log_file_path)
2199
def _subprocess_log_cleanup(self):
2200
for count, log_file_path in enumerate(self._log_files):
2201
# We use buffer_now=True to avoid holding the file open beyond
2202
# the life of this function, which might interfere with e.g.
2203
# cleaning tempdirs on Windows.
2204
# XXX: Testtools 0.9.5 doesn't have the content_from_file helper
2205
#detail_content = content.content_from_file(
2206
# log_file_path, buffer_now=True)
2207
with open(log_file_path, 'rb') as log_file:
2208
log_file_bytes = log_file.read()
2209
detail_content = content.Content(content.ContentType("text",
2210
"plain", {"charset": "utf8"}), lambda: [log_file_bytes])
2211
self.addDetail("start_bzr_subprocess-log-%d" % (count,),
2214
def _popen(self, *args, **kwargs):
2215
"""Place a call to Popen.
2217
Allows tests to override this method to intercept the calls made to
2218
Popen for introspection.
2220
return subprocess.Popen(*args, **kwargs)
2222
def get_source_path(self):
2223
"""Return the path of the directory containing breezy."""
2224
return os.path.dirname(os.path.dirname(breezy.__file__))
2226
def get_brz_path(self):
2227
"""Return the path of the 'brz' executable for this test suite."""
2228
brz_path = os.path.join(self.get_source_path(), "brz")
2229
if not os.path.isfile(brz_path):
2230
# We are probably installed. Assume sys.argv is the right file
2231
brz_path = sys.argv[0]
2234
def finish_bzr_subprocess(self, process, retcode=0, send_signal=None,
2235
universal_newlines=False, process_args=None):
2236
"""Finish the execution of process.
2238
:param process: the Popen object returned from start_bzr_subprocess.
2239
:param retcode: The status code that is expected. Defaults to 0. If
2240
None is supplied, the status code is not checked.
2241
:param send_signal: an optional signal to send to the process.
2242
:param universal_newlines: Convert CRLF => LF
2243
:returns: (stdout, stderr)
2245
if send_signal is not None:
2246
os.kill(process.pid, send_signal)
2247
out, err = process.communicate()
2249
if universal_newlines:
2250
out = out.replace('\r\n', '\n')
2251
err = err.replace('\r\n', '\n')
2253
if retcode is not None and retcode != process.returncode:
2254
if process_args is None:
2255
process_args = "(unknown args)"
2256
trace.mutter('Output of brz %s:\n%s', process_args, out)
2257
trace.mutter('Error for brz %s:\n%s', process_args, err)
2258
self.fail('Command brz %s failed with retcode %s != %s'
2259
% (process_args, retcode, process.returncode))
2262
def check_tree_shape(self, tree, shape):
2263
"""Compare a tree to a list of expected names.
2265
Fail if they are not precisely equal.
2268
shape = list(shape) # copy
2269
for path, ie in tree.iter_entries_by_dir():
2270
name = path.replace('\\', '/')
2271
if ie.kind == 'directory':
2274
pass # ignore root entry
2280
self.fail("expected paths not found in inventory: %r" % shape)
2282
self.fail("unexpected paths found in inventory: %r" % extras)
2284
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2285
a_callable=None, *args, **kwargs):
2286
"""Call callable with redirected std io pipes.
2288
Returns the return code."""
2289
if not callable(a_callable):
2290
raise ValueError("a_callable must be callable.")
2294
if getattr(self, "_log_file", None) is not None:
2295
stdout = self._log_file
2299
if getattr(self, "_log_file", None is not None):
2300
stderr = self._log_file
2303
real_stdin = sys.stdin
2304
real_stdout = sys.stdout
2305
real_stderr = sys.stderr
2310
return a_callable(*args, **kwargs)
2312
sys.stdout = real_stdout
2313
sys.stderr = real_stderr
2314
sys.stdin = real_stdin
2316
def reduceLockdirTimeout(self):
2317
"""Reduce the default lock timeout for the duration of the test, so that
2318
if LockContention occurs during a test, it does so quickly.
2320
Tests that expect to provoke LockContention errors should call this.
2322
self.overrideAttr(lockdir, '_DEFAULT_TIMEOUT_SECONDS', 0)
2324
def make_utf8_encoded_stringio(self, encoding_type=None):
2325
"""Return a wrapped BytesIO, that will encode text input to UTF-8."""
2326
if encoding_type is None:
2327
encoding_type = 'strict'
2329
output_encoding = 'utf-8'
2330
sio = codecs.getwriter(output_encoding)(bio, errors=encoding_type)
2331
sio.encoding = output_encoding
2334
def disable_verb(self, verb):
2335
"""Disable a smart server verb for one test."""
2336
from breezy.smart import request
2337
request_handlers = request.request_handlers
2338
orig_method = request_handlers.get(verb)
2339
orig_info = request_handlers.get_info(verb)
2340
request_handlers.remove(verb)
2341
self.addCleanup(request_handlers.register, verb, orig_method,
2348
class CapturedCall(object):
2349
"""A helper for capturing smart server calls for easy debug analysis."""
2351
def __init__(self, params, prefix_length):
2352
"""Capture the call with params and skip prefix_length stack frames."""
2355
# The last 5 frames are the __init__, the hook frame, and 3 smart
2356
# client frames. Beyond this we could get more clever, but this is good
2358
stack = traceback.extract_stack()[prefix_length:-5]
2359
self.stack = ''.join(traceback.format_list(stack))
2362
return self.call.method
2365
return self.call.method
2371
class TestCaseWithMemoryTransport(TestCase):
2372
"""Common test class for tests that do not need disk resources.
2374
Tests that need disk resources should derive from TestCaseInTempDir
2375
orTestCaseWithTransport.
2377
TestCaseWithMemoryTransport sets the TEST_ROOT variable for all brz tests.
2379
For TestCaseWithMemoryTransport the ``test_home_dir`` is set to the name of
2380
a directory which does not exist. This serves to help ensure test isolation
2381
is preserved. ``test_dir`` is set to the TEST_ROOT, as is cwd, because they
2382
must exist. However, TestCaseWithMemoryTransport does not offer local file
2383
defaults for the transport in tests, nor does it obey the command line
2384
override, so tests that accidentally write to the common directory should
2387
:cvar TEST_ROOT: Directory containing all temporary directories, plus a
2388
``.bzr`` directory that stops us ascending higher into the filesystem.
2394
def __init__(self, methodName='runTest'):
2395
# allow test parameterization after test construction and before test
2396
# execution. Variables that the parameterizer sets need to be
2397
# ones that are not set by setUp, or setUp will trash them.
2398
super(TestCaseWithMemoryTransport, self).__init__(methodName)
2399
self.vfs_transport_factory = default_transport
2400
self.transport_server = None
2401
self.transport_readonly_server = None
2402
self.__vfs_server = None
2405
super(TestCaseWithMemoryTransport, self).setUp()
2407
def _add_disconnect_cleanup(transport):
2408
"""Schedule disconnection of given transport at test cleanup
2410
This needs to happen for all connected transports or leaks occur.
2412
Note reconnections may mean we call disconnect multiple times per
2413
transport which is suboptimal but seems harmless.
2415
self.addCleanup(transport.disconnect)
2417
_mod_transport.Transport.hooks.install_named_hook('post_connect',
2418
_add_disconnect_cleanup, None)
2420
self._make_test_root()
2421
self.addCleanup(os.chdir, osutils.getcwd())
2422
self.makeAndChdirToTestDir()
2423
self.overrideEnvironmentForTesting()
2424
self.__readonly_server = None
2425
self.__server = None
2426
self.reduceLockdirTimeout()
2427
# Each test may use its own config files even if the local config files
2428
# don't actually exist. They'll rightly fail if they try to create them
2430
self.overrideAttr(config, '_shared_stores', {})
2432
def get_transport(self, relpath=None):
2433
"""Return a writeable transport.
2435
This transport is for the test scratch space relative to
2438
:param relpath: a path relative to the base url.
2440
t = _mod_transport.get_transport_from_url(self.get_url(relpath))
2441
self.assertFalse(t.is_readonly())
2444
def get_readonly_transport(self, relpath=None):
2445
"""Return a readonly transport for the test scratch space
2447
This can be used to test that operations which should only need
2448
readonly access in fact do not try to write.
2450
:param relpath: a path relative to the base url.
2452
t = _mod_transport.get_transport_from_url(
2453
self.get_readonly_url(relpath))
2454
self.assertTrue(t.is_readonly())
2457
def create_transport_readonly_server(self):
2458
"""Create a transport server from class defined at init.
2460
This is mostly a hook for daughter classes.
2462
return self.transport_readonly_server()
2464
def get_readonly_server(self):
2465
"""Get the server instance for the readonly transport
2467
This is useful for some tests with specific servers to do diagnostics.
2469
if self.__readonly_server is None:
2470
if self.transport_readonly_server is None:
2471
# readonly decorator requested
2472
self.__readonly_server = test_server.ReadonlyServer()
2474
# explicit readonly transport.
2475
self.__readonly_server = self.create_transport_readonly_server()
2476
self.start_server(self.__readonly_server,
2477
self.get_vfs_only_server())
2478
return self.__readonly_server
2480
def get_readonly_url(self, relpath=None):
2481
"""Get a URL for the readonly transport.
2483
This will either be backed by '.' or a decorator to the transport
2484
used by self.get_url()
2485
relpath provides for clients to get a path relative to the base url.
2486
These should only be downwards relative, not upwards.
2488
base = self.get_readonly_server().get_url()
2489
return self._adjust_url(base, relpath)
2491
def get_vfs_only_server(self):
2492
"""Get the vfs only read/write server instance.
2494
This is useful for some tests with specific servers that need
2497
For TestCaseWithMemoryTransport this is always a MemoryServer, and there
2498
is no means to override it.
2500
if self.__vfs_server is None:
2501
self.__vfs_server = memory.MemoryServer()
2502
self.start_server(self.__vfs_server)
2503
return self.__vfs_server
2505
def get_server(self):
2506
"""Get the read/write server instance.
2508
This is useful for some tests with specific servers that need
2511
This is built from the self.transport_server factory. If that is None,
2512
then the self.get_vfs_server is returned.
2514
if self.__server is None:
2515
if (self.transport_server is None or self.transport_server is
2516
self.vfs_transport_factory):
2517
self.__server = self.get_vfs_only_server()
2519
# bring up a decorated means of access to the vfs only server.
2520
self.__server = self.transport_server()
2521
self.start_server(self.__server, self.get_vfs_only_server())
2522
return self.__server
2524
def _adjust_url(self, base, relpath):
2525
"""Get a URL (or maybe a path) for the readwrite transport.
2527
This will either be backed by '.' or to an equivalent non-file based
2529
relpath provides for clients to get a path relative to the base url.
2530
These should only be downwards relative, not upwards.
2532
if relpath is not None and relpath != '.':
2533
if not base.endswith('/'):
2535
# XXX: Really base should be a url; we did after all call
2536
# get_url()! But sometimes it's just a path (from
2537
# LocalAbspathServer), and it'd be wrong to append urlescaped data
2538
# to a non-escaped local path.
2539
if base.startswith('./') or base.startswith('/'):
2542
base += urlutils.escape(relpath)
2545
def get_url(self, relpath=None):
2546
"""Get a URL (or maybe a path) for the readwrite transport.
2548
This will either be backed by '.' or to an equivalent non-file based
2550
relpath provides for clients to get a path relative to the base url.
2551
These should only be downwards relative, not upwards.
2553
base = self.get_server().get_url()
2554
return self._adjust_url(base, relpath)
2556
def get_vfs_only_url(self, relpath=None):
2557
"""Get a URL (or maybe a path for the plain old vfs transport.
2559
This will never be a smart protocol. It always has all the
2560
capabilities of the local filesystem, but it might actually be a
2561
MemoryTransport or some other similar virtual filesystem.
2563
This is the backing transport (if any) of the server returned by
2564
get_url and get_readonly_url.
2566
:param relpath: provides for clients to get a path relative to the base
2567
url. These should only be downwards relative, not upwards.
2570
base = self.get_vfs_only_server().get_url()
2571
return self._adjust_url(base, relpath)
2573
def _create_safety_net(self):
2574
"""Make a fake bzr directory.
2576
This prevents any tests propagating up onto the TEST_ROOT directory's
2579
root = TestCaseWithMemoryTransport.TEST_ROOT
2581
# Make sure we get a readable and accessible home for .brz.log
2582
# and/or config files, and not fallback to weird defaults (see
2583
# http://pad.lv/825027).
2584
self.assertIs(None, os.environ.get('BRZ_HOME', None))
2585
os.environ['BRZ_HOME'] = root
2586
wt = controldir.ControlDir.create_standalone_workingtree(root)
2587
del os.environ['BRZ_HOME']
2588
except Exception as e:
2589
self.fail("Fail to initialize the safety net: %r\n" % (e,))
2590
# Hack for speed: remember the raw bytes of the dirstate file so that
2591
# we don't need to re-open the wt to check it hasn't changed.
2592
TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE = (
2593
wt.control_transport.get_bytes('dirstate'))
2595
def _check_safety_net(self):
2596
"""Check that the safety .bzr directory have not been touched.
2598
_make_test_root have created a .bzr directory to prevent tests from
2599
propagating. This method ensures than a test did not leaked.
2601
root = TestCaseWithMemoryTransport.TEST_ROOT
2602
t = _mod_transport.get_transport_from_path(root)
2603
self.permit_url(t.base)
2604
if (t.get_bytes('.bzr/checkout/dirstate') !=
2605
TestCaseWithMemoryTransport._SAFETY_NET_PRISTINE_DIRSTATE):
2606
# The current test have modified the /bzr directory, we need to
2607
# recreate a new one or all the followng tests will fail.
2608
# If you need to inspect its content uncomment the following line
2609
# import pdb; pdb.set_trace()
2610
_rmtree_temp_dir(root + '/.bzr', test_id=self.id())
2611
self._create_safety_net()
2612
raise AssertionError('%s/.bzr should not be modified' % root)
2614
def _make_test_root(self):
2615
if TestCaseWithMemoryTransport.TEST_ROOT is None:
2616
# Watch out for tricky test dir (on OSX /tmp -> /private/tmp)
2617
root = osutils.realpath(osutils.mkdtemp(prefix='testbzr-',
2619
TestCaseWithMemoryTransport.TEST_ROOT = root
2621
self._create_safety_net()
2623
# The same directory is used by all tests, and we're not
2624
# specifically told when all tests are finished. This will do.
2625
atexit.register(_rmtree_temp_dir, root)
2627
self.permit_dir(TestCaseWithMemoryTransport.TEST_ROOT)
2628
self.addCleanup(self._check_safety_net)
2630
def makeAndChdirToTestDir(self):
2631
"""Create a temporary directories for this one test.
2633
This must set self.test_home_dir and self.test_dir and chdir to
2636
For TestCaseWithMemoryTransport we chdir to the TEST_ROOT for this test.
2638
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2639
self.test_dir = TestCaseWithMemoryTransport.TEST_ROOT
2640
self.test_home_dir = self.test_dir + "/MemoryTransportMissingHomeDir"
2641
self.permit_dir(self.test_dir)
2643
def make_branch(self, relpath, format=None, name=None):
2644
"""Create a branch on the transport at relpath."""
2645
repo = self.make_repository(relpath, format=format)
2646
return repo.bzrdir.create_branch(append_revisions_only=False,
2649
def get_default_format(self):
2652
def resolve_format(self, format):
2653
"""Resolve an object to a ControlDir format object.
2655
The initial format object can either already be
2656
a ControlDirFormat, None (for the default format),
2657
or a string with the name of the control dir format.
2659
:param format: Object to resolve
2660
:return A ControlDirFormat instance
2663
format = self.get_default_format()
2664
if isinstance(format, basestring):
2665
format = controldir.format_registry.make_bzrdir(format)
2668
def make_bzrdir(self, relpath, format=None):
2670
# might be a relative or absolute path
2671
maybe_a_url = self.get_url(relpath)
2672
segments = maybe_a_url.rsplit('/', 1)
2673
t = _mod_transport.get_transport(maybe_a_url)
2674
if len(segments) > 1 and segments[-1] not in ('', '.'):
2676
format = self.resolve_format(format)
2677
return format.initialize_on_transport(t)
2678
except errors.UninitializableFormat:
2679
raise TestSkipped("Format %s is not initializable." % format)
2681
def make_repository(self, relpath, shared=None, format=None):
2682
"""Create a repository on our default transport at relpath.
2684
Note that relpath must be a relative path, not a full url.
2686
# FIXME: If you create a remoterepository this returns the underlying
2687
# real format, which is incorrect. Actually we should make sure that
2688
# RemoteBzrDir returns a RemoteRepository.
2689
# maybe mbp 20070410
2690
made_control = self.make_bzrdir(relpath, format=format)
2691
return made_control.create_repository(shared=shared)
2693
def make_smart_server(self, path, backing_server=None):
2694
if backing_server is None:
2695
backing_server = self.get_server()
2696
smart_server = test_server.SmartTCPServer_for_testing()
2697
self.start_server(smart_server, backing_server)
2698
remote_transport = _mod_transport.get_transport_from_url(smart_server.get_url()
2700
return remote_transport
2702
def make_branch_and_memory_tree(self, relpath, format=None):
2703
"""Create a branch on the default transport and a MemoryTree for it."""
2704
b = self.make_branch(relpath, format=format)
2705
return memorytree.MemoryTree.create_on_branch(b)
2707
def make_branch_builder(self, relpath, format=None):
2708
branch = self.make_branch(relpath, format=format)
2709
return branchbuilder.BranchBuilder(branch=branch)
2711
def overrideEnvironmentForTesting(self):
2712
test_home_dir = self.test_home_dir
2713
if isinstance(test_home_dir, text_type):
2714
test_home_dir = test_home_dir.encode(sys.getfilesystemencoding())
2715
self.overrideEnv('HOME', test_home_dir)
2716
self.overrideEnv('BRZ_HOME', test_home_dir)
2718
def setup_smart_server_with_call_log(self):
2719
"""Sets up a smart server as the transport server with a call log."""
2720
self.transport_server = test_server.SmartTCPServer_for_testing
2721
self.hpss_connections = []
2722
self.hpss_calls = []
2724
# Skip the current stack down to the caller of
2725
# setup_smart_server_with_call_log
2726
prefix_length = len(traceback.extract_stack()) - 2
2727
def capture_hpss_call(params):
2728
self.hpss_calls.append(
2729
CapturedCall(params, prefix_length))
2730
def capture_connect(transport):
2731
self.hpss_connections.append(transport)
2732
client._SmartClient.hooks.install_named_hook(
2733
'call', capture_hpss_call, None)
2734
_mod_transport.Transport.hooks.install_named_hook(
2735
'post_connect', capture_connect, None)
2737
def reset_smart_call_log(self):
2738
self.hpss_calls = []
2739
self.hpss_connections = []
2742
class TestCaseInTempDir(TestCaseWithMemoryTransport):
2743
"""Derived class that runs a test within a temporary directory.
2745
This is useful for tests that need to create a branch, etc.
2747
The directory is created in a slightly complex way: for each
2748
Python invocation, a new temporary top-level directory is created.
2749
All test cases create their own directory within that. If the
2750
tests complete successfully, the directory is removed.
2752
:ivar test_base_dir: The path of the top-level directory for this
2753
test, which contains a home directory and a work directory.
2755
:ivar test_home_dir: An initially empty directory under test_base_dir
2756
which is used as $HOME for this test.
2758
:ivar test_dir: A directory under test_base_dir used as the current
2759
directory when the test proper is run.
2762
OVERRIDE_PYTHON = 'python'
2765
super(TestCaseInTempDir, self).setUp()
2766
# Remove the protection set in isolated_environ, we have a proper
2767
# access to disk resources now.
2768
self.overrideEnv('BRZ_LOG', None)
2770
def check_file_contents(self, filename, expect):
2771
self.log("check contents of file %s" % filename)
2777
if contents != expect:
2778
self.log("expected: %r" % expect)
2779
self.log("actually: %r" % contents)
2780
self.fail("contents of %s not as expected" % filename)
2782
def _getTestDirPrefix(self):
2783
# create a directory within the top level test directory
2784
if sys.platform in ('win32', 'cygwin'):
2785
name_prefix = re.sub('[<>*=+",:;_/\\-]', '_', self.id())
2786
# windows is likely to have path-length limits so use a short name
2787
name_prefix = name_prefix[-30:]
2789
name_prefix = re.sub('[/]', '_', self.id())
2792
def makeAndChdirToTestDir(self):
2793
"""See TestCaseWithMemoryTransport.makeAndChdirToTestDir().
2795
For TestCaseInTempDir we create a temporary directory based on the test
2796
name and then create two subdirs - test and home under it.
2798
name_prefix = osutils.pathjoin(TestCaseWithMemoryTransport.TEST_ROOT,
2799
self._getTestDirPrefix())
2801
for i in range(100):
2802
if os.path.exists(name):
2803
name = name_prefix + '_' + str(i)
2805
# now create test and home directories within this dir
2806
self.test_base_dir = name
2807
self.addCleanup(self.deleteTestDir)
2808
os.mkdir(self.test_base_dir)
2810
self.permit_dir(self.test_base_dir)
2811
# 'sprouting' and 'init' of a branch both walk up the tree to find
2812
# stacking policy to honour; create a bzr dir with an unshared
2813
# repository (but not a branch - our code would be trying to escape
2814
# then!) to stop them, and permit it to be read.
2815
# control = controldir.ControlDir.create(self.test_base_dir)
2816
# control.create_repository()
2817
self.test_home_dir = self.test_base_dir + '/home'
2818
os.mkdir(self.test_home_dir)
2819
self.test_dir = self.test_base_dir + '/work'
2820
os.mkdir(self.test_dir)
2821
os.chdir(self.test_dir)
2822
# put name of test inside
2823
f = file(self.test_base_dir + '/name', 'w')
2829
def deleteTestDir(self):
2830
os.chdir(TestCaseWithMemoryTransport.TEST_ROOT)
2831
_rmtree_temp_dir(self.test_base_dir, test_id=self.id())
2833
def build_tree(self, shape, line_endings='binary', transport=None):
2834
"""Build a test tree according to a pattern.
2836
shape is a sequence of file specifications. If the final
2837
character is '/', a directory is created.
2839
This assumes that all the elements in the tree being built are new.
2841
This doesn't add anything to a branch.
2843
:type shape: list or tuple.
2844
:param line_endings: Either 'binary' or 'native'
2845
in binary mode, exact contents are written in native mode, the
2846
line endings match the default platform endings.
2847
:param transport: A transport to write to, for building trees on VFS's.
2848
If the transport is readonly or None, "." is opened automatically.
2851
if type(shape) not in (list, tuple):
2852
raise AssertionError("Parameter 'shape' should be "
2853
"a list or a tuple. Got %r instead" % (shape,))
2854
# It's OK to just create them using forward slashes on windows.
2855
if transport is None or transport.is_readonly():
2856
transport = _mod_transport.get_transport_from_path(".")
2858
self.assertIsInstance(name, basestring)
2860
transport.mkdir(urlutils.escape(name[:-1]))
2862
if line_endings == 'binary':
2864
elif line_endings == 'native':
2867
raise errors.BzrError(
2868
'Invalid line ending request %r' % line_endings)
2869
content = "contents of %s%s" % (name.encode('utf-8'), end)
2870
transport.put_bytes_non_atomic(urlutils.escape(name), content)
2872
build_tree_contents = staticmethod(treeshape.build_tree_contents)
2874
def assertInWorkingTree(self, path, root_path='.', tree=None):
2875
"""Assert whether path or paths are in the WorkingTree"""
2877
tree = workingtree.WorkingTree.open(root_path)
2878
if not isinstance(path, basestring):
2880
self.assertInWorkingTree(p, tree=tree)
2882
self.assertIsNot(tree.path2id(path), None,
2883
path+' not in working tree.')
2885
def assertNotInWorkingTree(self, path, root_path='.', tree=None):
2886
"""Assert whether path or paths are not in the WorkingTree"""
2888
tree = workingtree.WorkingTree.open(root_path)
2889
if not isinstance(path, basestring):
2891
self.assertNotInWorkingTree(p,tree=tree)
2893
self.assertIs(tree.path2id(path), None, path+' in working tree.')
2896
class TestCaseWithTransport(TestCaseInTempDir):
2897
"""A test case that provides get_url and get_readonly_url facilities.
2899
These back onto two transport servers, one for readonly access and one for
2902
If no explicit class is provided for readonly access, a
2903
ReadonlyTransportDecorator is used instead which allows the use of non disk
2904
based read write transports.
2906
If an explicit class is provided for readonly access, that server and the
2907
readwrite one must both define get_url() as resolving to os.getcwd().
2911
super(TestCaseWithTransport, self).setUp()
2912
self.__vfs_server = None
2914
def get_vfs_only_server(self):
2915
"""See TestCaseWithMemoryTransport.
2917
This is useful for some tests with specific servers that need
2920
if self.__vfs_server is None:
2921
self.__vfs_server = self.vfs_transport_factory()
2922
self.start_server(self.__vfs_server)
2923
return self.__vfs_server
2925
def make_branch_and_tree(self, relpath, format=None):
2926
"""Create a branch on the transport and a tree locally.
2928
If the transport is not a LocalTransport, the Tree can't be created on
2929
the transport. In that case if the vfs_transport_factory is
2930
LocalURLServer the working tree is created in the local
2931
directory backing the transport, and the returned tree's branch and
2932
repository will also be accessed locally. Otherwise a lightweight
2933
checkout is created and returned.
2935
We do this because we can't physically create a tree in the local
2936
path, with a branch reference to the transport_factory url, and
2937
a branch + repository in the vfs_transport, unless the vfs_transport
2938
namespace is distinct from the local disk - the two branch objects
2939
would collide. While we could construct a tree with its branch object
2940
pointing at the transport_factory transport in memory, reopening it
2941
would behaving unexpectedly, and has in the past caused testing bugs
2942
when we tried to do it that way.
2944
:param format: The BzrDirFormat.
2945
:returns: the WorkingTree.
2947
# TODO: always use the local disk path for the working tree,
2948
# this obviously requires a format that supports branch references
2949
# so check for that by checking bzrdir.BzrDirFormat.get_default_format()
2951
format = self.resolve_format(format=format)
2952
if not format.supports_workingtrees:
2953
b = self.make_branch(relpath+'.branch', format=format)
2954
return b.create_checkout(relpath, lightweight=True)
2955
b = self.make_branch(relpath, format=format)
2957
return b.bzrdir.create_workingtree()
2958
except errors.NotLocalUrl:
2959
# We can only make working trees locally at the moment. If the
2960
# transport can't support them, then we keep the non-disk-backed
2961
# branch and create a local checkout.
2962
if self.vfs_transport_factory is test_server.LocalURLServer:
2963
# the branch is colocated on disk, we cannot create a checkout.
2964
# hopefully callers will expect this.
2965
local_controldir = controldir.ControlDir.open(
2966
self.get_vfs_only_url(relpath))
2967
wt = local_controldir.create_workingtree()
2968
if wt.branch._format != b._format:
2970
# Make sure that assigning to wt._branch fixes wt.branch,
2971
# in case the implementation details of workingtree objects
2973
self.assertIs(b, wt.branch)
2976
return b.create_checkout(relpath, lightweight=True)
2978
def assertIsDirectory(self, relpath, transport):
2979
"""Assert that relpath within transport is a directory.
2981
This may not be possible on all transports; in that case it propagates
2982
a TransportNotPossible.
2985
mode = transport.stat(relpath).st_mode
2986
except errors.NoSuchFile:
2987
self.fail("path %s is not a directory; no such file"
2989
if not stat.S_ISDIR(mode):
2990
self.fail("path %s is not a directory; has mode %#o"
2993
def assertTreesEqual(self, left, right):
2994
"""Check that left and right have the same content and properties."""
2995
# we use a tree delta to check for equality of the content, and we
2996
# manually check for equality of other things such as the parents list.
2997
self.assertEqual(left.get_parent_ids(), right.get_parent_ids())
2998
differences = left.changes_from(right)
2999
self.assertFalse(differences.has_changed(),
3000
"Trees %r and %r are different: %r" % (left, right, differences))
3002
def disable_missing_extensions_warning(self):
3003
"""Some tests expect a precise stderr content.
3005
There is no point in forcing them to duplicate the extension related
3008
config.GlobalStack().set('ignore_missing_extensions', True)
3011
class ChrootedTestCase(TestCaseWithTransport):
3012
"""A support class that provides readonly urls outside the local namespace.
3014
This is done by checking if self.transport_server is a MemoryServer. if it
3015
is then we are chrooted already, if it is not then an HttpServer is used
3018
TODO RBC 20060127: make this an option to TestCaseWithTransport so it can
3019
be used without needed to redo it when a different
3020
subclass is in use ?
3024
from breezy.tests import http_server
3025
super(ChrootedTestCase, self).setUp()
3026
if not self.vfs_transport_factory == memory.MemoryServer:
3027
self.transport_readonly_server = http_server.HttpServer
3030
def condition_id_re(pattern):
3031
"""Create a condition filter which performs a re check on a test's id.
3033
:param pattern: A regular expression string.
3034
:return: A callable that returns True if the re matches.
3036
filter_re = re.compile(pattern, 0)
3037
def condition(test):
3039
return filter_re.search(test_id)
3043
def condition_isinstance(klass_or_klass_list):
3044
"""Create a condition filter which returns isinstance(param, klass).
3046
:return: A callable which when called with one parameter obj return the
3047
result of isinstance(obj, klass_or_klass_list).
3050
return isinstance(obj, klass_or_klass_list)
3054
def condition_id_in_list(id_list):
3055
"""Create a condition filter which verify that test's id in a list.
3057
:param id_list: A TestIdList object.
3058
:return: A callable that returns True if the test's id appears in the list.
3060
def condition(test):
3061
return id_list.includes(test.id())
3065
def condition_id_startswith(starts):
3066
"""Create a condition filter verifying that test's id starts with a string.
3068
:param starts: A list of string.
3069
:return: A callable that returns True if the test's id starts with one of
3072
def condition(test):
3073
for start in starts:
3074
if test.id().startswith(start):
3080
def exclude_tests_by_condition(suite, condition):
3081
"""Create a test suite which excludes some tests from suite.
3083
:param suite: The suite to get tests from.
3084
:param condition: A callable whose result evaluates True when called with a
3085
test case which should be excluded from the result.
3086
:return: A suite which contains the tests found in suite that fail
3090
for test in iter_suite_tests(suite):
3091
if not condition(test):
3093
return TestUtil.TestSuite(result)
3096
def filter_suite_by_condition(suite, condition):
3097
"""Create a test suite by filtering another one.
3099
:param suite: The source suite.
3100
:param condition: A callable whose result evaluates True when called with a
3101
test case which should be included in the result.
3102
:return: A suite which contains the tests found in suite that pass
3106
for test in iter_suite_tests(suite):
3109
return TestUtil.TestSuite(result)
3112
def filter_suite_by_re(suite, pattern):
3113
"""Create a test suite by filtering another one.
3115
:param suite: the source suite
3116
:param pattern: pattern that names must match
3117
:returns: the newly created suite
3119
condition = condition_id_re(pattern)
3120
result_suite = filter_suite_by_condition(suite, condition)
3124
def filter_suite_by_id_list(suite, test_id_list):
3125
"""Create a test suite by filtering another one.
3127
:param suite: The source suite.
3128
:param test_id_list: A list of the test ids to keep as strings.
3129
:returns: the newly created suite
3131
condition = condition_id_in_list(test_id_list)
3132
result_suite = filter_suite_by_condition(suite, condition)
3136
def filter_suite_by_id_startswith(suite, start):
3137
"""Create a test suite by filtering another one.
3139
:param suite: The source suite.
3140
:param start: A list of string the test id must start with one of.
3141
:returns: the newly created suite
3143
condition = condition_id_startswith(start)
3144
result_suite = filter_suite_by_condition(suite, condition)
3148
def exclude_tests_by_re(suite, pattern):
3149
"""Create a test suite which excludes some tests from suite.
3151
:param suite: The suite to get tests from.
3152
:param pattern: A regular expression string. Test ids that match this
3153
pattern will be excluded from the result.
3154
:return: A TestSuite that contains all the tests from suite without the
3155
tests that matched pattern. The order of tests is the same as it was in
3158
return exclude_tests_by_condition(suite, condition_id_re(pattern))
3161
def preserve_input(something):
3162
"""A helper for performing test suite transformation chains.
3164
:param something: Anything you want to preserve.
3170
def randomize_suite(suite):
3171
"""Return a new TestSuite with suite's tests in random order.
3173
The tests in the input suite are flattened into a single suite in order to
3174
accomplish this. Any nested TestSuites are removed to provide global
3177
tests = list(iter_suite_tests(suite))
3178
random.shuffle(tests)
3179
return TestUtil.TestSuite(tests)
3182
def split_suite_by_condition(suite, condition):
3183
"""Split a test suite into two by a condition.
3185
:param suite: The suite to split.
3186
:param condition: The condition to match on. Tests that match this
3187
condition are returned in the first test suite, ones that do not match
3188
are in the second suite.
3189
:return: A tuple of two test suites, where the first contains tests from
3190
suite matching the condition, and the second contains the remainder
3191
from suite. The order within each output suite is the same as it was in
3196
for test in iter_suite_tests(suite):
3198
matched.append(test)
3200
did_not_match.append(test)
3201
return TestUtil.TestSuite(matched), TestUtil.TestSuite(did_not_match)
3204
def split_suite_by_re(suite, pattern):
3205
"""Split a test suite into two by a regular expression.
3207
:param suite: The suite to split.
3208
:param pattern: A regular expression string. Test ids that match this
3209
pattern will be in the first test suite returned, and the others in the
3210
second test suite returned.
3211
:return: A tuple of two test suites, where the first contains tests from
3212
suite matching pattern, and the second contains the remainder from
3213
suite. The order within each output suite is the same as it was in
3216
return split_suite_by_condition(suite, condition_id_re(pattern))
3219
def run_suite(suite, name='test', verbose=False, pattern=".*",
3220
stop_on_failure=False,
3221
transport=None, lsprof_timed=None, bench_history=None,
3222
matching_tests_first=None,
3225
exclude_pattern=None,
3228
suite_decorators=None,
3230
result_decorators=None,
3232
"""Run a test suite for brz selftest.
3234
:param runner_class: The class of runner to use. Must support the
3235
constructor arguments passed by run_suite which are more than standard
3237
:return: A boolean indicating success.
3239
TestCase._gather_lsprof_in_benchmarks = lsprof_timed
3244
if runner_class is None:
3245
runner_class = TextTestRunner
3248
runner = runner_class(stream=stream,
3250
verbosity=verbosity,
3251
bench_history=bench_history,
3253
result_decorators=result_decorators,
3255
runner.stop_on_failure=stop_on_failure
3256
if isinstance(suite, unittest.TestSuite):
3257
# Empty out _tests list of passed suite and populate new TestSuite
3258
suite._tests[:], suite = [], TestSuite(suite)
3259
# built in decorator factories:
3261
random_order(random_seed, runner),
3262
exclude_tests(exclude_pattern),
3264
if matching_tests_first:
3265
decorators.append(tests_first(pattern))
3267
decorators.append(filter_tests(pattern))
3268
if suite_decorators:
3269
decorators.extend(suite_decorators)
3270
# tell the result object how many tests will be running: (except if
3271
# --parallel=fork is being used. Robert said he will provide a better
3272
# progress design later -- vila 20090817)
3273
if fork_decorator not in decorators:
3274
decorators.append(CountingDecorator)
3275
for decorator in decorators:
3276
suite = decorator(suite)
3278
# Done after test suite decoration to allow randomisation etc
3279
# to take effect, though that is of marginal benefit.
3281
stream.write("Listing tests only ...\n")
3282
for t in iter_suite_tests(suite):
3283
stream.write("%s\n" % (t.id()))
3285
result = runner.run(suite)
3287
return result.wasStrictlySuccessful()
3289
return result.wasSuccessful()
3292
# A registry where get() returns a suite decorator.
3293
parallel_registry = registry.Registry()
3296
def fork_decorator(suite):
3297
if getattr(os, "fork", None) is None:
3298
raise errors.BzrCommandError("platform does not support fork,"
3299
" try --parallel=subprocess instead.")
3300
concurrency = osutils.local_concurrency()
3301
if concurrency == 1:
3303
from testtools import ConcurrentTestSuite
3304
return ConcurrentTestSuite(suite, fork_for_tests)
3305
parallel_registry.register('fork', fork_decorator)
3308
def subprocess_decorator(suite):
3309
concurrency = osutils.local_concurrency()
3310
if concurrency == 1:
3312
from testtools import ConcurrentTestSuite
3313
return ConcurrentTestSuite(suite, reinvoke_for_tests)
3314
parallel_registry.register('subprocess', subprocess_decorator)
3317
def exclude_tests(exclude_pattern):
3318
"""Return a test suite decorator that excludes tests."""
3319
if exclude_pattern is None:
3320
return identity_decorator
3321
def decorator(suite):
3322
return ExcludeDecorator(suite, exclude_pattern)
3326
def filter_tests(pattern):
3328
return identity_decorator
3329
def decorator(suite):
3330
return FilterTestsDecorator(suite, pattern)
3334
def random_order(random_seed, runner):
3335
"""Return a test suite decorator factory for randomising tests order.
3337
:param random_seed: now, a string which casts to an integer, or an integer.
3338
:param runner: A test runner with a stream attribute to report on.
3340
if random_seed is None:
3341
return identity_decorator
3342
def decorator(suite):
3343
return RandomDecorator(suite, random_seed, runner.stream)
3347
def tests_first(pattern):
3349
return identity_decorator
3350
def decorator(suite):
3351
return TestFirstDecorator(suite, pattern)
3355
def identity_decorator(suite):
3360
class TestDecorator(TestUtil.TestSuite):
3361
"""A decorator for TestCase/TestSuite objects.
3363
Contains rather than flattening suite passed on construction
3366
def __init__(self, suite=None):
3367
super(TestDecorator, self).__init__()
3368
if suite is not None:
3371
# Don't need subclass run method with suite emptying
3372
run = unittest.TestSuite.run
3375
class CountingDecorator(TestDecorator):
3376
"""A decorator which calls result.progress(self.countTestCases)."""
3378
def run(self, result):
3379
progress_method = getattr(result, 'progress', None)
3380
if callable(progress_method):
3381
progress_method(self.countTestCases(), SUBUNIT_SEEK_SET)
3382
return super(CountingDecorator, self).run(result)
3385
class ExcludeDecorator(TestDecorator):
3386
"""A decorator which excludes test matching an exclude pattern."""
3388
def __init__(self, suite, exclude_pattern):
3389
super(ExcludeDecorator, self).__init__(
3390
exclude_tests_by_re(suite, exclude_pattern))
3393
class FilterTestsDecorator(TestDecorator):
3394
"""A decorator which filters tests to those matching a pattern."""
3396
def __init__(self, suite, pattern):
3397
super(FilterTestsDecorator, self).__init__(
3398
filter_suite_by_re(suite, pattern))
3401
class RandomDecorator(TestDecorator):
3402
"""A decorator which randomises the order of its tests."""
3404
def __init__(self, suite, random_seed, stream):
3405
random_seed = self.actual_seed(random_seed)
3406
stream.write("Randomizing test order using seed %s\n\n" %
3408
# Initialise the random number generator.
3409
random.seed(random_seed)
3410
super(RandomDecorator, self).__init__(randomize_suite(suite))
3413
def actual_seed(seed):
3415
# We convert the seed to an integer to make it reuseable across
3416
# invocations (because the user can reenter it).
3417
return int(time.time())
3419
# Convert the seed to an integer if we can
3422
except (TypeError, ValueError):
3427
class TestFirstDecorator(TestDecorator):
3428
"""A decorator which moves named tests to the front."""
3430
def __init__(self, suite, pattern):
3431
super(TestFirstDecorator, self).__init__()
3432
self.addTests(split_suite_by_re(suite, pattern))
3435
def partition_tests(suite, count):
3436
"""Partition suite into count lists of tests."""
3437
# This just assigns tests in a round-robin fashion. On one hand this
3438
# splits up blocks of related tests that might run faster if they shared
3439
# resources, but on the other it avoids assigning blocks of slow tests to
3440
# just one partition. So the slowest partition shouldn't be much slower
3442
partitions = [list() for i in range(count)]
3443
tests = iter_suite_tests(suite)
3444
for partition, test in zip(itertools.cycle(partitions), tests):
3445
partition.append(test)
3449
def workaround_zealous_crypto_random():
3450
"""Crypto.Random want to help us being secure, but we don't care here.
3452
This workaround some test failure related to the sftp server. Once paramiko
3453
stop using the controversial API in Crypto.Random, we may get rid of it.
3456
from Crypto.Random import atfork
3462
def fork_for_tests(suite):
3463
"""Take suite and start up one runner per CPU by forking()
3465
:return: An iterable of TestCase-like objects which can each have
3466
run(result) called on them to feed tests to result.
3468
concurrency = osutils.local_concurrency()
3470
from subunit import ProtocolTestCase
3471
from subunit.test_results import AutoTimingTestResultDecorator
3472
class TestInOtherProcess(ProtocolTestCase):
3473
# Should be in subunit, I think. RBC.
3474
def __init__(self, stream, pid):
3475
ProtocolTestCase.__init__(self, stream)
3478
def run(self, result):
3480
ProtocolTestCase.run(self, result)
3482
pid, status = os.waitpid(self.pid, 0)
3483
# GZ 2011-10-18: If status is nonzero, should report to the result
3484
# that something went wrong.
3486
test_blocks = partition_tests(suite, concurrency)
3487
# Clear the tests from the original suite so it doesn't keep them alive
3488
suite._tests[:] = []
3489
for process_tests in test_blocks:
3490
process_suite = TestUtil.TestSuite(process_tests)
3491
# Also clear each split list so new suite has only reference
3492
process_tests[:] = []
3493
c2pread, c2pwrite = os.pipe()
3497
stream = os.fdopen(c2pwrite, 'wb', 1)
3498
workaround_zealous_crypto_random()
3500
# Leave stderr and stdout open so we can see test noise
3501
# Close stdin so that the child goes away if it decides to
3502
# read from stdin (otherwise its a roulette to see what
3503
# child actually gets keystrokes for pdb etc).
3505
subunit_result = AutoTimingTestResultDecorator(
3506
SubUnitBzrProtocolClient(stream))
3507
process_suite.run(subunit_result)
3509
# Try and report traceback on stream, but exit with error even
3510
# if stream couldn't be created or something else goes wrong.
3511
# The traceback is formatted to a string and written in one go
3512
# to avoid interleaving lines from multiple failing children.
3514
stream.write(traceback.format_exc())
3520
stream = os.fdopen(c2pread, 'rb', 1)
3521
test = TestInOtherProcess(stream, pid)
3526
def reinvoke_for_tests(suite):
3527
"""Take suite and start up one runner per CPU using subprocess().
3529
:return: An iterable of TestCase-like objects which can each have
3530
run(result) called on them to feed tests to result.
3532
concurrency = osutils.local_concurrency()
3534
from subunit import ProtocolTestCase
3535
class TestInSubprocess(ProtocolTestCase):
3536
def __init__(self, process, name):
3537
ProtocolTestCase.__init__(self, process.stdout)
3538
self.process = process
3539
self.process.stdin.close()
3542
def run(self, result):
3544
ProtocolTestCase.run(self, result)
3547
os.unlink(self.name)
3548
# print "pid %d finished" % finished_process
3549
test_blocks = partition_tests(suite, concurrency)
3550
for process_tests in test_blocks:
3551
# ugly; currently reimplement rather than reuses TestCase methods.
3552
bzr_path = os.path.dirname(os.path.dirname(breezy.__file__))+'/bzr'
3553
if not os.path.isfile(bzr_path):
3554
# We are probably installed. Assume sys.argv is the right file
3555
bzr_path = sys.argv[0]
3556
bzr_path = [bzr_path]
3557
if sys.platform == "win32":
3558
# if we're on windows, we can't execute the bzr script directly
3559
bzr_path = [sys.executable] + bzr_path
3560
fd, test_list_file_name = tempfile.mkstemp()
3561
test_list_file = os.fdopen(fd, 'wb', 1)
3562
for test in process_tests:
3563
test_list_file.write(test.id() + '\n')
3564
test_list_file.close()
3566
argv = bzr_path + ['selftest', '--load-list', test_list_file_name,
3568
if '--no-plugins' in sys.argv:
3569
argv.append('--no-plugins')
3570
# stderr=subprocess.STDOUT would be ideal, but until we prevent
3571
# noise on stderr it can interrupt the subunit protocol.
3572
process = subprocess.Popen(argv, stdin=subprocess.PIPE,
3573
stdout=subprocess.PIPE,
3574
stderr=subprocess.PIPE,
3576
test = TestInSubprocess(process, test_list_file_name)
3579
os.unlink(test_list_file_name)
3584
class ProfileResult(testtools.ExtendedToOriginalDecorator):
3585
"""Generate profiling data for all activity between start and success.
3587
The profile data is appended to the test's _benchcalls attribute and can
3588
be accessed by the forwarded-to TestResult.
3590
While it might be cleaner do accumulate this in stopTest, addSuccess is
3591
where our existing output support for lsprof is, and this class aims to
3592
fit in with that: while it could be moved it's not necessary to accomplish
3593
test profiling, nor would it be dramatically cleaner.
3596
def startTest(self, test):
3597
self.profiler = breezy.lsprof.BzrProfiler()
3598
# Prevent deadlocks in tests that use lsprof: those tests will
3600
breezy.lsprof.BzrProfiler.profiler_block = 0
3601
self.profiler.start()
3602
testtools.ExtendedToOriginalDecorator.startTest(self, test)
3604
def addSuccess(self, test):
3605
stats = self.profiler.stop()
3607
calls = test._benchcalls
3608
except AttributeError:
3609
test._benchcalls = []
3610
calls = test._benchcalls
3611
calls.append(((test.id(), "", ""), stats))
3612
testtools.ExtendedToOriginalDecorator.addSuccess(self, test)
3614
def stopTest(self, test):
3615
testtools.ExtendedToOriginalDecorator.stopTest(self, test)
3616
self.profiler = None
3619
# Controlled by "brz selftest -E=..." option
3620
# Currently supported:
3621
# -Eallow_debug Will no longer clear debug.debug_flags() so it
3622
# preserves any flags supplied at the command line.
3623
# -Edisable_lock_checks Turns errors in mismatched locks into simple prints
3624
# rather than failing tests. And no longer raise
3625
# LockContention when fctnl locks are not being used
3626
# with proper exclusion rules.
3627
# -Ethreads Will display thread ident at creation/join time to
3628
# help track thread leaks
3629
# -Euncollected_cases Display the identity of any test cases that weren't
3630
# deallocated after being completed.
3631
# -Econfig_stats Will collect statistics using addDetail
3632
selftest_debug_flags = set()
3635
def selftest(verbose=False, pattern=".*", stop_on_failure=True,
3637
test_suite_factory=None,
3640
matching_tests_first=None,
3643
exclude_pattern=None,
3649
suite_decorators=None,
3653
"""Run the whole test suite under the enhanced runner"""
3654
# XXX: Very ugly way to do this...
3655
# Disable warning about old formats because we don't want it to disturb
3656
# any blackbox tests.
3657
from breezy import repository
3658
repository._deprecation_warning_done = True
3660
global default_transport
3661
if transport is None:
3662
transport = default_transport
3663
old_transport = default_transport
3664
default_transport = transport
3665
global selftest_debug_flags
3666
old_debug_flags = selftest_debug_flags
3667
if debug_flags is not None:
3668
selftest_debug_flags = set(debug_flags)
3670
if load_list is None:
3673
keep_only = load_test_id_list(load_list)
3675
starting_with = [test_prefix_alias_registry.resolve_alias(start)
3676
for start in starting_with]
3677
if test_suite_factory is None:
3678
# Reduce loading time by loading modules based on the starting_with
3680
suite = test_suite(keep_only, starting_with)
3682
suite = test_suite_factory()
3684
# But always filter as requested.
3685
suite = filter_suite_by_id_startswith(suite, starting_with)
3686
result_decorators = []
3688
result_decorators.append(ProfileResult)
3689
return run_suite(suite, 'testbzr', verbose=verbose, pattern=pattern,
3690
stop_on_failure=stop_on_failure,
3691
transport=transport,
3692
lsprof_timed=lsprof_timed,
3693
bench_history=bench_history,
3694
matching_tests_first=matching_tests_first,
3695
list_only=list_only,
3696
random_seed=random_seed,
3697
exclude_pattern=exclude_pattern,
3699
runner_class=runner_class,
3700
suite_decorators=suite_decorators,
3702
result_decorators=result_decorators,
3705
default_transport = old_transport
3706
selftest_debug_flags = old_debug_flags
3709
def load_test_id_list(file_name):
3710
"""Load a test id list from a text file.
3712
The format is one test id by line. No special care is taken to impose
3713
strict rules, these test ids are used to filter the test suite so a test id
3714
that do not match an existing test will do no harm. This allows user to add
3715
comments, leave blank lines, etc.
3719
ftest = open(file_name, 'rt')
3720
except IOError as e:
3721
if e.errno != errno.ENOENT:
3724
raise errors.NoSuchFile(file_name)
3726
for test_name in ftest.readlines():
3727
test_list.append(test_name.strip())
3732
def suite_matches_id_list(test_suite, id_list):
3733
"""Warns about tests not appearing or appearing more than once.
3735
:param test_suite: A TestSuite object.
3736
:param test_id_list: The list of test ids that should be found in
3739
:return: (absents, duplicates) absents is a list containing the test found
3740
in id_list but not in test_suite, duplicates is a list containing the
3741
tests found multiple times in test_suite.
3743
When using a prefined test id list, it may occurs that some tests do not
3744
exist anymore or that some tests use the same id. This function warns the
3745
tester about potential problems in his workflow (test lists are volatile)
3746
or in the test suite itself (using the same id for several tests does not
3747
help to localize defects).
3749
# Build a dict counting id occurrences
3751
for test in iter_suite_tests(test_suite):
3753
tests[id] = tests.get(id, 0) + 1
3758
occurs = tests.get(id, 0)
3760
not_found.append(id)
3762
duplicates.append(id)
3764
return not_found, duplicates
3767
class TestIdList(object):
3768
"""Test id list to filter a test suite.
3770
Relying on the assumption that test ids are built as:
3771
<module>[.<class>.<method>][(<param>+)], <module> being in python dotted
3772
notation, this class offers methods to :
3773
- avoid building a test suite for modules not refered to in the test list,
3774
- keep only the tests listed from the module test suite.
3777
def __init__(self, test_id_list):
3778
# When a test suite needs to be filtered against us we compare test ids
3779
# for equality, so a simple dict offers a quick and simple solution.
3780
self.tests = dict().fromkeys(test_id_list, True)
3782
# While unittest.TestCase have ids like:
3783
# <module>.<class>.<method>[(<param+)],
3784
# doctest.DocTestCase can have ids like:
3787
# <module>.<function>
3788
# <module>.<class>.<method>
3790
# Since we can't predict a test class from its name only, we settle on
3791
# a simple constraint: a test id always begins with its module name.
3794
for test_id in test_id_list:
3795
parts = test_id.split('.')
3796
mod_name = parts.pop(0)
3797
modules[mod_name] = True
3799
mod_name += '.' + part
3800
modules[mod_name] = True
3801
self.modules = modules
3803
def refers_to(self, module_name):
3804
"""Is there tests for the module or one of its sub modules."""
3805
return module_name in self.modules
3807
def includes(self, test_id):
3808
return test_id in self.tests
3811
class TestPrefixAliasRegistry(registry.Registry):
3812
"""A registry for test prefix aliases.
3814
This helps implement shorcuts for the --starting-with selftest
3815
option. Overriding existing prefixes is not allowed but not fatal (a
3816
warning will be emitted).
3819
def register(self, key, obj, help=None, info=None,
3820
override_existing=False):
3821
"""See Registry.register.
3823
Trying to override an existing alias causes a warning to be emitted,
3824
not a fatal execption.
3827
super(TestPrefixAliasRegistry, self).register(
3828
key, obj, help=help, info=info, override_existing=False)
3830
actual = self.get(key)
3832
'Test prefix alias %s is already used for %s, ignoring %s'
3833
% (key, actual, obj))
3835
def resolve_alias(self, id_start):
3836
"""Replace the alias by the prefix in the given string.
3838
Using an unknown prefix is an error to help catching typos.
3840
parts = id_start.split('.')
3842
parts[0] = self.get(parts[0])
3844
raise errors.BzrCommandError(
3845
'%s is not a known test prefix alias' % parts[0])
3846
return '.'.join(parts)
3849
test_prefix_alias_registry = TestPrefixAliasRegistry()
3850
"""Registry of test prefix aliases."""
3853
# This alias allows to detect typos ('bzrlin.') by making all valid test ids
3854
# appear prefixed ('breezy.' is "replaced" by 'breezy.').
3855
test_prefix_alias_registry.register('breezy', 'breezy')
3857
# Obvious highest levels prefixes, feel free to add your own via a plugin
3858
test_prefix_alias_registry.register('bd', 'breezy.doc')
3859
test_prefix_alias_registry.register('bu', 'breezy.utils')
3860
test_prefix_alias_registry.register('bt', 'breezy.tests')
3861
test_prefix_alias_registry.register('bb', 'breezy.tests.blackbox')
3862
test_prefix_alias_registry.register('bp', 'breezy.plugins')
3865
def _test_suite_testmod_names():
3866
"""Return the standard list of test module names to test."""
3869
'breezy.tests.blackbox',
3870
'breezy.tests.commands',
3871
'breezy.tests.per_branch',
3872
'breezy.tests.per_bzrdir',
3873
'breezy.tests.per_controldir',
3874
'breezy.tests.per_controldir_colo',
3875
'breezy.tests.per_foreign_vcs',
3876
'breezy.tests.per_interrepository',
3877
'breezy.tests.per_intertree',
3878
'breezy.tests.per_inventory',
3879
'breezy.tests.per_interbranch',
3880
'breezy.tests.per_lock',
3881
'breezy.tests.per_merger',
3882
'breezy.tests.per_transport',
3883
'breezy.tests.per_tree',
3884
'breezy.tests.per_pack_repository',
3885
'breezy.tests.per_repository',
3886
'breezy.tests.per_repository_chk',
3887
'breezy.tests.per_repository_reference',
3888
'breezy.tests.per_repository_vf',
3889
'breezy.tests.per_uifactory',
3890
'breezy.tests.per_versionedfile',
3891
'breezy.tests.per_workingtree',
3892
'breezy.tests.test__annotator',
3893
'breezy.tests.test__bencode',
3894
'breezy.tests.test__btree_serializer',
3895
'breezy.tests.test__chk_map',
3896
'breezy.tests.test__dirstate_helpers',
3897
'breezy.tests.test__groupcompress',
3898
'breezy.tests.test__known_graph',
3899
'breezy.tests.test__rio',
3900
'breezy.tests.test__simple_set',
3901
'breezy.tests.test__static_tuple',
3902
'breezy.tests.test__walkdirs_win32',
3903
'breezy.tests.test_ancestry',
3904
'breezy.tests.test_annotate',
3905
'breezy.tests.test_api',
3906
'breezy.tests.test_atomicfile',
3907
'breezy.tests.test_bad_files',
3908
'breezy.tests.test_bisect_multi',
3909
'breezy.tests.test_branch',
3910
'breezy.tests.test_branchbuilder',
3911
'breezy.tests.test_btree_index',
3912
'breezy.tests.test_bugtracker',
3913
'breezy.tests.test_bundle',
3914
'breezy.tests.test_bzrdir',
3915
'breezy.tests.test__chunks_to_lines',
3916
'breezy.tests.test_cache_utf8',
3917
'breezy.tests.test_chk_map',
3918
'breezy.tests.test_chk_serializer',
3919
'breezy.tests.test_chunk_writer',
3920
'breezy.tests.test_clean_tree',
3921
'breezy.tests.test_cleanup',
3922
'breezy.tests.test_cmdline',
3923
'breezy.tests.test_commands',
3924
'breezy.tests.test_commit',
3925
'breezy.tests.test_commit_merge',
3926
'breezy.tests.test_config',
3927
'breezy.tests.test_conflicts',
3928
'breezy.tests.test_controldir',
3929
'breezy.tests.test_counted_lock',
3930
'breezy.tests.test_crash',
3931
'breezy.tests.test_decorators',
3932
'breezy.tests.test_delta',
3933
'breezy.tests.test_debug',
3934
'breezy.tests.test_diff',
3935
'breezy.tests.test_directory_service',
3936
'breezy.tests.test_dirstate',
3937
'breezy.tests.test_email_message',
3938
'breezy.tests.test_eol_filters',
3939
'breezy.tests.test_errors',
3940
'breezy.tests.test_estimate_compressed_size',
3941
'breezy.tests.test_export',
3942
'breezy.tests.test_export_pot',
3943
'breezy.tests.test_extract',
3944
'breezy.tests.test_features',
3945
'breezy.tests.test_fetch',
3946
'breezy.tests.test_fetch_ghosts',
3947
'breezy.tests.test_fixtures',
3948
'breezy.tests.test_fifo_cache',
3949
'breezy.tests.test_filters',
3950
'breezy.tests.test_filter_tree',
3951
'breezy.tests.test_ftp_transport',
3952
'breezy.tests.test_foreign',
3953
'breezy.tests.test_generate_docs',
3954
'breezy.tests.test_generate_ids',
3955
'breezy.tests.test_globbing',
3956
'breezy.tests.test_gpg',
3957
'breezy.tests.test_graph',
3958
'breezy.tests.test_groupcompress',
3959
'breezy.tests.test_hashcache',
3960
'breezy.tests.test_help',
3961
'breezy.tests.test_hooks',
3962
'breezy.tests.test_http',
3963
'breezy.tests.test_http_response',
3964
'breezy.tests.test_https_ca_bundle',
3965
'breezy.tests.test_https_urllib',
3966
'breezy.tests.test_i18n',
3967
'breezy.tests.test_identitymap',
3968
'breezy.tests.test_ignores',
3969
'breezy.tests.test_index',
3970
'breezy.tests.test_import_tariff',
3971
'breezy.tests.test_info',
3972
'breezy.tests.test_inv',
3973
'breezy.tests.test_inventory_delta',
3974
'breezy.tests.test_knit',
3975
'breezy.tests.test_lazy_import',
3976
'breezy.tests.test_lazy_regex',
3977
'breezy.tests.test_library_state',
3978
'breezy.tests.test_lock',
3979
'breezy.tests.test_lockable_files',
3980
'breezy.tests.test_lockdir',
3981
'breezy.tests.test_log',
3982
'breezy.tests.test_lru_cache',
3983
'breezy.tests.test_lsprof',
3984
'breezy.tests.test_mail_client',
3985
'breezy.tests.test_matchers',
3986
'breezy.tests.test_memorytree',
3987
'breezy.tests.test_merge',
3988
'breezy.tests.test_merge3',
3989
'breezy.tests.test_merge_core',
3990
'breezy.tests.test_merge_directive',
3991
'breezy.tests.test_mergetools',
3992
'breezy.tests.test_missing',
3993
'breezy.tests.test_msgeditor',
3994
'breezy.tests.test_multiparent',
3995
'breezy.tests.test_mutabletree',
3996
'breezy.tests.test_nonascii',
3997
'breezy.tests.test_options',
3998
'breezy.tests.test_osutils',
3999
'breezy.tests.test_osutils_encodings',
4000
'breezy.tests.test_pack',
4001
'breezy.tests.test_patch',
4002
'breezy.tests.test_patches',
4003
'breezy.tests.test_permissions',
4004
'breezy.tests.test_plugins',
4005
'breezy.tests.test_progress',
4006
'breezy.tests.test_pyutils',
4007
'breezy.tests.test_read_bundle',
4008
'breezy.tests.test_reconcile',
4009
'breezy.tests.test_reconfigure',
4010
'breezy.tests.test_registry',
4011
'breezy.tests.test_remote',
4012
'breezy.tests.test_rename_map',
4013
'breezy.tests.test_repository',
4014
'breezy.tests.test_revert',
4015
'breezy.tests.test_revision',
4016
'breezy.tests.test_revisionspec',
4017
'breezy.tests.test_revisiontree',
4018
'breezy.tests.test_rio',
4019
'breezy.tests.test_rules',
4020
'breezy.tests.test_url_policy_open',
4021
'breezy.tests.test_sampler',
4022
'breezy.tests.test_scenarios',
4023
'breezy.tests.test_script',
4024
'breezy.tests.test_selftest',
4025
'breezy.tests.test_serializer',
4026
'breezy.tests.test_setup',
4027
'breezy.tests.test_sftp_transport',
4028
'breezy.tests.test_shelf',
4029
'breezy.tests.test_shelf_ui',
4030
'breezy.tests.test_smart',
4031
'breezy.tests.test_smart_add',
4032
'breezy.tests.test_smart_request',
4033
'breezy.tests.test_smart_signals',
4034
'breezy.tests.test_smart_transport',
4035
'breezy.tests.test_smtp_connection',
4036
'breezy.tests.test_source',
4037
'breezy.tests.test_ssh_transport',
4038
'breezy.tests.test_status',
4039
'breezy.tests.test_store',
4040
'breezy.tests.test_strace',
4041
'breezy.tests.test_subsume',
4042
'breezy.tests.test_switch',
4043
'breezy.tests.test_symbol_versioning',
4044
'breezy.tests.test_tag',
4045
'breezy.tests.test_test_server',
4046
'breezy.tests.test_testament',
4047
'breezy.tests.test_textfile',
4048
'breezy.tests.test_textmerge',
4049
'breezy.tests.test_cethread',
4050
'breezy.tests.test_timestamp',
4051
'breezy.tests.test_trace',
4052
'breezy.tests.test_transactions',
4053
'breezy.tests.test_transform',
4054
'breezy.tests.test_transport',
4055
'breezy.tests.test_transport_log',
4056
'breezy.tests.test_tree',
4057
'breezy.tests.test_treebuilder',
4058
'breezy.tests.test_treeshape',
4059
'breezy.tests.test_tsort',
4060
'breezy.tests.test_tuned_gzip',
4061
'breezy.tests.test_ui',
4062
'breezy.tests.test_uncommit',
4063
'breezy.tests.test_upgrade',
4064
'breezy.tests.test_upgrade_stacked',
4065
'breezy.tests.test_upstream_import',
4066
'breezy.tests.test_urlutils',
4067
'breezy.tests.test_utextwrap',
4068
'breezy.tests.test_version',
4069
'breezy.tests.test_version_info',
4070
'breezy.tests.test_versionedfile',
4071
'breezy.tests.test_vf_search',
4072
'breezy.tests.test_weave',
4073
'breezy.tests.test_whitebox',
4074
'breezy.tests.test_win32utils',
4075
'breezy.tests.test_workingtree',
4076
'breezy.tests.test_workingtree_4',
4077
'breezy.tests.test_wsgi',
4078
'breezy.tests.test_xml',
4082
def _test_suite_modules_to_doctest():
4083
"""Return the list of modules to doctest."""
4085
# GZ 2009-03-31: No docstrings with -OO so there's nothing to doctest
4089
'breezy.branchbuilder',
4090
'breezy.decorators',
4092
'breezy.iterablefile',
4097
'breezy.symbol_versioning',
4099
'breezy.tests.fixtures',
4101
'breezy.transport.http',
4102
'breezy.version_info_formats.format_custom',
4106
def test_suite(keep_only=None, starting_with=None):
4107
"""Build and return TestSuite for the whole of breezy.
4109
:param keep_only: A list of test ids limiting the suite returned.
4111
:param starting_with: An id limiting the suite returned to the tests
4114
This function can be replaced if you need to change the default test
4115
suite on a global basis, but it is not encouraged.
4118
loader = TestUtil.TestLoader()
4120
if keep_only is not None:
4121
id_filter = TestIdList(keep_only)
4123
# We take precedence over keep_only because *at loading time* using
4124
# both options means we will load less tests for the same final result.
4125
def interesting_module(name):
4126
for start in starting_with:
4128
# Either the module name starts with the specified string
4129
name.startswith(start)
4130
# or it may contain tests starting with the specified string
4131
or start.startswith(name)
4135
loader = TestUtil.FilteredByModuleTestLoader(interesting_module)
4137
elif keep_only is not None:
4138
loader = TestUtil.FilteredByModuleTestLoader(id_filter.refers_to)
4139
def interesting_module(name):
4140
return id_filter.refers_to(name)
4143
loader = TestUtil.TestLoader()
4144
def interesting_module(name):
4145
# No filtering, all modules are interesting
4148
suite = loader.suiteClass()
4150
# modules building their suite with loadTestsFromModuleNames
4151
suite.addTest(loader.loadTestsFromModuleNames(_test_suite_testmod_names()))
4153
for mod in _test_suite_modules_to_doctest():
4154
if not interesting_module(mod):
4155
# No tests to keep here, move along
4158
# note that this really does mean "report only" -- doctest
4159
# still runs the rest of the examples
4160
doc_suite = IsolatedDocTestSuite(
4161
mod, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
4162
except ValueError as e:
4163
print('**failed to get doctest for: %s\n%s' % (mod, e))
4165
if len(doc_suite._tests) == 0:
4166
raise errors.BzrError("no doctests found in %s" % (mod,))
4167
suite.addTest(doc_suite)
4169
default_encoding = sys.getdefaultencoding()
4170
for name, plugin in _mod_plugin.plugins().items():
4171
if not interesting_module(plugin.module.__name__):
4173
plugin_suite = plugin.test_suite()
4174
# We used to catch ImportError here and turn it into just a warning,
4175
# but really if you don't have --no-plugins this should be a failure.
4176
# mbp 20080213 - see http://bugs.launchpad.net/bugs/189771
4177
if plugin_suite is None:
4178
plugin_suite = plugin.load_plugin_tests(loader)
4179
if plugin_suite is not None:
4180
suite.addTest(plugin_suite)
4181
if default_encoding != sys.getdefaultencoding():
4183
'Plugin "%s" tried to reset default encoding to: %s', name,
4184
sys.getdefaultencoding())
4186
sys.setdefaultencoding(default_encoding)
4188
if keep_only is not None:
4189
# Now that the referred modules have loaded their tests, keep only the
4191
suite = filter_suite_by_id_list(suite, id_filter)
4192
# Do some sanity checks on the id_list filtering
4193
not_found, duplicates = suite_matches_id_list(suite, keep_only)
4195
# The tester has used both keep_only and starting_with, so he is
4196
# already aware that some tests are excluded from the list, there
4197
# is no need to tell him which.
4200
# Some tests mentioned in the list are not in the test suite. The
4201
# list may be out of date, report to the tester.
4202
for id in not_found:
4203
trace.warning('"%s" not found in the test suite', id)
4204
for id in duplicates:
4205
trace.warning('"%s" is used as an id by several tests', id)
4210
def multiply_scenarios(*scenarios):
4211
"""Multiply two or more iterables of scenarios.
4213
It is safe to pass scenario generators or iterators.
4215
:returns: A list of compound scenarios: the cross-product of all
4216
scenarios, with the names concatenated and the parameters
4219
return functools.reduce(_multiply_two_scenarios, map(list, scenarios))
4222
def _multiply_two_scenarios(scenarios_left, scenarios_right):
4223
"""Multiply two sets of scenarios.
4225
:returns: the cartesian product of the two sets of scenarios, that is
4226
a scenario for every possible combination of a left scenario and a
4230
('%s,%s' % (left_name, right_name),
4231
dict(left_dict, **right_dict))
4232
for left_name, left_dict in scenarios_left
4233
for right_name, right_dict in scenarios_right]
4236
def multiply_tests(tests, scenarios, result):
4237
"""Multiply tests_list by scenarios into result.
4239
This is the core workhorse for test parameterisation.
4241
Typically the load_tests() method for a per-implementation test suite will
4242
call multiply_tests and return the result.
4244
:param tests: The tests to parameterise.
4245
:param scenarios: The scenarios to apply: pairs of (scenario_name,
4246
scenario_param_dict).
4247
:param result: A TestSuite to add created tests to.
4249
This returns the passed in result TestSuite with the cross product of all
4250
the tests repeated once for each scenario. Each test is adapted by adding
4251
the scenario name at the end of its id(), and updating the test object's
4252
__dict__ with the scenario_param_dict.
4254
>>> import breezy.tests.test_sampler
4255
>>> r = multiply_tests(
4256
... breezy.tests.test_sampler.DemoTest('test_nothing'),
4257
... [('one', dict(param=1)),
4258
... ('two', dict(param=2))],
4259
... TestUtil.TestSuite())
4260
>>> tests = list(iter_suite_tests(r))
4264
'breezy.tests.test_sampler.DemoTest.test_nothing(one)'
4270
for test in iter_suite_tests(tests):
4271
apply_scenarios(test, scenarios, result)
4275
def apply_scenarios(test, scenarios, result):
4276
"""Apply the scenarios in scenarios to test and add to result.
4278
:param test: The test to apply scenarios to.
4279
:param scenarios: An iterable of scenarios to apply to test.
4281
:seealso: apply_scenario
4283
for scenario in scenarios:
4284
result.addTest(apply_scenario(test, scenario))
4288
def apply_scenario(test, scenario):
4289
"""Copy test and apply scenario to it.
4291
:param test: A test to adapt.
4292
:param scenario: A tuple describing the scenario.
4293
The first element of the tuple is the new test id.
4294
The second element is a dict containing attributes to set on the
4296
:return: The adapted test.
4298
new_id = "%s(%s)" % (test.id(), scenario[0])
4299
new_test = clone_test(test, new_id)
4300
for name, value in scenario[1].items():
4301
setattr(new_test, name, value)
4305
def clone_test(test, new_id):
4306
"""Clone a test giving it a new id.
4308
:param test: The test to clone.
4309
:param new_id: The id to assign to it.
4310
:return: The new test.
4312
new_test = copy.copy(test)
4313
new_test.id = lambda: new_id
4314
# XXX: Workaround <https://bugs.launchpad.net/testtools/+bug/637725>, which
4315
# causes cloned tests to share the 'details' dict. This makes it hard to
4316
# read the test output for parameterized tests, because tracebacks will be
4317
# associated with irrelevant tests.
4319
details = new_test._TestCase__details
4320
except AttributeError:
4321
# must be a different version of testtools than expected. Do nothing.
4324
# Reset the '__details' dict.
4325
new_test._TestCase__details = {}
4329
def permute_tests_for_extension(standard_tests, loader, py_module_name,
4331
"""Helper for permutating tests against an extension module.
4333
This is meant to be used inside a modules 'load_tests()' function. It will
4334
create 2 scenarios, and cause all tests in the 'standard_tests' to be run
4335
against both implementations. Setting 'test.module' to the appropriate
4336
module. See breezy.tests.test__chk_map.load_tests as an example.
4338
:param standard_tests: A test suite to permute
4339
:param loader: A TestLoader
4340
:param py_module_name: The python path to a python module that can always
4341
be loaded, and will be considered the 'python' implementation. (eg
4342
'breezy._chk_map_py')
4343
:param ext_module_name: The python path to an extension module. If the
4344
module cannot be loaded, a single test will be added, which notes that
4345
the module is not available. If it can be loaded, all standard_tests
4346
will be run against that module.
4347
:return: (suite, feature) suite is a test-suite that has all the permuted
4348
tests. feature is the Feature object that can be used to determine if
4349
the module is available.
4352
from .features import ModuleAvailableFeature
4353
py_module = pyutils.get_named_object(py_module_name)
4355
('python', {'module': py_module}),
4357
suite = loader.suiteClass()
4358
feature = ModuleAvailableFeature(ext_module_name)
4359
if feature.available():
4360
scenarios.append(('C', {'module': feature.module}))
4362
# the compiled module isn't available, so we add a failing test
4363
class FailWithoutFeature(TestCase):
4364
def test_fail(self):
4365
self.requireFeature(feature)
4366
suite.addTest(loader.loadTestsFromTestCase(FailWithoutFeature))
4367
result = multiply_tests(standard_tests, scenarios, suite)
4368
return result, feature
4371
def _rmtree_temp_dir(dirname, test_id=None):
4372
# If LANG=C we probably have created some bogus paths
4373
# which rmtree(unicode) will fail to delete
4374
# so make sure we are using rmtree(str) to delete everything
4375
# except on win32, where rmtree(str) will fail
4376
# since it doesn't have the property of byte-stream paths
4377
# (they are either ascii or mbcs)
4378
if sys.platform == 'win32':
4379
# make sure we are using the unicode win32 api
4380
dirname = text_type(dirname)
4382
dirname = dirname.encode(sys.getfilesystemencoding())
4384
osutils.rmtree(dirname)
4385
except OSError as e:
4386
# We don't want to fail here because some useful display will be lost
4387
# otherwise. Polluting the tmp dir is bad, but not giving all the
4388
# possible info to the test runner is even worse.
4390
ui.ui_factory.clear_term()
4391
sys.stderr.write('\nWhile running: %s\n' % (test_id,))
4392
# Ugly, but the last thing we want here is fail, so bear with it.
4393
printable_e = str(e).decode(osutils.get_user_encoding(), 'replace'
4394
).encode('ascii', 'replace')
4395
sys.stderr.write('Unable to remove testing dir %s\n%s'
4396
% (os.path.basename(dirname), printable_e))
4399
def probe_unicode_in_user_encoding():
4400
"""Try to encode several unicode strings to use in unicode-aware tests.
4401
Return first successfull match.
4403
:return: (unicode value, encoded plain string value) or (None, None)
4405
possible_vals = [u'm\xb5', u'\xe1', u'\u0410']
4406
for uni_val in possible_vals:
4408
str_val = uni_val.encode(osutils.get_user_encoding())
4409
except UnicodeEncodeError:
4410
# Try a different character
4413
return uni_val, str_val
4417
def probe_bad_non_ascii(encoding):
4418
"""Try to find [bad] character with code [128..255]
4419
that cannot be decoded to unicode in some encoding.
4420
Return None if all non-ascii characters is valid
4423
for i in range(128, 256):
4426
char.decode(encoding)
4427
except UnicodeDecodeError:
4432
# Only define SubUnitBzrRunner if subunit is available.
4434
from subunit import TestProtocolClient
4435
from subunit.test_results import AutoTimingTestResultDecorator
4436
class SubUnitBzrProtocolClient(TestProtocolClient):
4438
def stopTest(self, test):
4439
super(SubUnitBzrProtocolClient, self).stopTest(test)
4440
_clear__type_equality_funcs(test)
4442
def addSuccess(self, test, details=None):
4443
# The subunit client always includes the details in the subunit
4444
# stream, but we don't want to include it in ours.
4445
if details is not None and 'log' in details:
4447
return super(SubUnitBzrProtocolClient, self).addSuccess(
4450
class SubUnitBzrRunner(TextTestRunner):
4451
def run(self, test):
4452
result = AutoTimingTestResultDecorator(
4453
SubUnitBzrProtocolClient(self.stream))