441
397
format1 = WorkingTreeFormat2()
442
398
format2 = WorkingTreeFormat3()
443
formats = [(str, format1, format2, "converter1"),
444
(int, format2, format1, "converter2")]
399
formats = [(str, format1, format2, False, True),
400
(int, format2, format1, False, True)]
445
401
adapter = InterTreeTestProviderAdapter(server1, server2, formats)
446
402
suite = adapter.adapt(input_test)
447
403
tests = list(iter(suite))
448
404
self.assertEqual(2, len(tests))
449
405
self.assertEqual(tests[0].intertree_class, formats[0][0])
450
406
self.assertEqual(tests[0].workingtree_format, formats[0][1])
451
self.assertEqual(tests[0].workingtree_format_to, formats[0][2])
452
self.assertEqual(tests[0].mutable_trees_to_test_trees, formats[0][3])
453
self.assertEqual(tests[0].workingtree_to_test_tree, return_parameter)
407
self.assertEqual(tests[0].workingtree_to_test_tree, formats[0][2])
408
self.assertEqual(tests[0].workingtree_format_to, formats[0][3])
409
self.assertEqual(tests[0].workingtree_to_test_tree_to, formats[0][4])
454
410
self.assertEqual(tests[0].transport_server, server1)
455
411
self.assertEqual(tests[0].transport_readonly_server, server2)
456
412
self.assertEqual(tests[1].intertree_class, formats[1][0])
457
413
self.assertEqual(tests[1].workingtree_format, formats[1][1])
458
self.assertEqual(tests[1].workingtree_format_to, formats[1][2])
459
self.assertEqual(tests[1].mutable_trees_to_test_trees, formats[1][3])
460
self.assertEqual(tests[1].workingtree_to_test_tree, return_parameter)
414
self.assertEqual(tests[1].workingtree_to_test_tree, formats[1][2])
415
self.assertEqual(tests[1].workingtree_format_to, formats[1][3])
416
self.assertEqual(tests[1].workingtree_to_test_tree_to, formats[1][4])
461
417
self.assertEqual(tests[1].transport_server, server1)
462
418
self.assertEqual(tests[1].transport_readonly_server, server2)
465
class TestTestCaseInTempDir(TestCaseInTempDir):
467
def test_home_is_not_working(self):
468
self.assertNotEqual(self.test_dir, self.test_home_dir)
469
cwd = osutils.getcwd()
470
self.assertEqual(self.test_dir, cwd)
471
self.assertEqual(self.test_home_dir, os.environ['HOME'])
474
class TestTestCaseWithMemoryTransport(TestCaseWithMemoryTransport):
476
def test_home_is_non_existant_dir_under_root(self):
477
"""The test_home_dir for TestCaseWithMemoryTransport is missing.
479
This is because TestCaseWithMemoryTransport is for tests that do not
480
need any disk resources: they should be hooked into bzrlib in such a
481
way that no global settings are being changed by the test (only a
482
few tests should need to do that), and having a missing dir as home is
483
an effective way to ensure that this is the case.
485
self.assertEqual(self.TEST_ROOT + "/MemoryTransportMissingHomeDir",
487
self.assertEqual(self.test_home_dir, os.environ['HOME'])
489
def test_cwd_is_TEST_ROOT(self):
490
self.assertEqual(self.test_dir, self.TEST_ROOT)
491
cwd = osutils.getcwd()
492
self.assertEqual(self.test_dir, cwd)
494
def test_make_branch_and_memory_tree(self):
495
"""In TestCaseWithMemoryTransport we should not make the branch on disk.
497
This is hard to comprehensively robustly test, so we settle for making
498
a branch and checking no directory was created at its relpath.
500
tree = self.make_branch_and_memory_tree('dir')
501
# Guard against regression into MemoryTransport leaking
502
# files to disk instead of keeping them in memory.
503
self.failIf(osutils.lexists('dir'))
504
self.assertIsInstance(tree, memorytree.MemoryTree)
506
def test_make_branch_and_memory_tree_with_format(self):
507
"""make_branch_and_memory_tree should accept a format option."""
508
format = bzrdir.BzrDirMetaFormat1()
509
format.repository_format = weaverepo.RepositoryFormat7()
510
tree = self.make_branch_and_memory_tree('dir', format=format)
511
# Guard against regression into MemoryTransport leaking
512
# files to disk instead of keeping them in memory.
513
self.failIf(osutils.lexists('dir'))
514
self.assertIsInstance(tree, memorytree.MemoryTree)
515
self.assertEqual(format.repository_format.__class__,
516
tree.branch.repository._format.__class__)
519
420
class TestTestCaseWithTransport(TestCaseWithTransport):
520
421
"""Tests for the convenience functions TestCaseWithTransport introduces."""
611
496
class TestTestResult(TestCase):
498
def test_progress_bar_style_quiet(self):
499
# test using a progress bar.
500
dummy_test = TestTestResult('test_progress_bar_style_quiet')
501
dummy_error = (Exception, None, [])
502
mypb = MockProgress()
503
mypb.update('Running tests', 0, 4)
504
last_calls = mypb.calls[:]
506
result = bzrlib.tests._MyResult(self._log_file,
510
self.assertEqual(last_calls, mypb.calls)
513
"""Shorten a string based on the terminal width"""
514
return result._ellipsise_unimportant_words(s,
515
osutils.terminal_width())
518
result.startTest(dummy_test)
519
# starting a test prints the test name
520
last_calls += [('update', '...tyle_quiet', 0, None)]
521
self.assertEqual(last_calls, mypb.calls)
522
result.addError(dummy_test, dummy_error)
523
last_calls += [('update', 'ERROR ', 1, None),
524
('note', shorten(dummy_test.id() + ': ERROR'), ())
526
self.assertEqual(last_calls, mypb.calls)
529
result.startTest(dummy_test)
530
last_calls += [('update', '...tyle_quiet', 1, None)]
531
self.assertEqual(last_calls, mypb.calls)
532
last_calls += [('update', 'FAIL ', 2, None),
533
('note', shorten(dummy_test.id() + ': FAIL'), ())
535
result.addFailure(dummy_test, dummy_error)
536
self.assertEqual(last_calls, mypb.calls)
539
result.startTest(dummy_test)
540
last_calls += [('update', '...tyle_quiet', 2, None)]
541
self.assertEqual(last_calls, mypb.calls)
542
result.addSuccess(dummy_test)
543
last_calls += [('update', 'OK ', 3, None)]
544
self.assertEqual(last_calls, mypb.calls)
547
result.startTest(dummy_test)
548
last_calls += [('update', '...tyle_quiet', 3, None)]
549
self.assertEqual(last_calls, mypb.calls)
550
result.addSkipped(dummy_test, dummy_error)
551
last_calls += [('update', 'SKIP ', 4, None)]
552
self.assertEqual(last_calls, mypb.calls)
613
554
def test_elapsed_time_with_benchmarking(self):
614
result = bzrlib.tests.TextTestResult(self._log_file,
555
result = bzrlib.tests._MyResult(self._log_file,
620
561
result.extractBenchmarkTime(self)
621
562
timed_string = result._testTimeString()
622
563
# without explicit benchmarking, we should get a simple time.
623
self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms$")
564
self.assertContainsRe(timed_string, "^ [ 1-9][0-9]ms$")
624
565
# if a benchmark time is given, we want a x of y style result.
625
566
self.time(time.sleep, 0.001)
626
567
result.extractBenchmarkTime(self)
627
568
timed_string = result._testTimeString()
628
self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms/ *[ 1-9][0-9]ms$")
569
self.assertContainsRe(timed_string, "^ [ 1-9][0-9]ms/ [ 1-9][0-9]ms$")
629
570
# extracting the time from a non-bzrlib testcase sets to None
630
571
result._recordTestStartTime()
631
572
result.extractBenchmarkTime(
632
573
unittest.FunctionTestCase(self.test_elapsed_time_with_benchmarking))
633
574
timed_string = result._testTimeString()
634
self.assertContainsRe(timed_string, "^ *[ 1-9][0-9]ms$")
575
self.assertContainsRe(timed_string, "^ [ 1-9][0-9]ms$")
635
576
# cheat. Yes, wash thy mouth out with soap.
636
577
self._benchtime = None
638
def test_assigned_benchmark_file_stores_date(self):
640
result = bzrlib.tests.TextTestResult(self._log_file,
645
output_string = output.getvalue()
647
# if you are wondering about the regexp please read the comment in
648
# test_bench_history (bzrlib.tests.test_selftest.TestRunner)
649
# XXX: what comment? -- Andrew Bennetts
650
self.assertContainsRe(output_string, "--date [0-9.]+")
652
def test_benchhistory_records_test_times(self):
653
result_stream = StringIO()
654
result = bzrlib.tests.TextTestResult(
658
bench_history=result_stream
661
# we want profile a call and check that its test duration is recorded
662
# make a new test instance that when run will generate a benchmark
663
example_test_case = TestTestResult("_time_hello_world_encoding")
664
# execute the test, which should succeed and record times
665
example_test_case.run(result)
666
lines = result_stream.getvalue().splitlines()
667
self.assertEqual(2, len(lines))
668
self.assertContainsRe(lines[1],
669
" *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
670
"._time_hello_world_encoding")
672
579
def _time_hello_world_encoding(self):
673
580
"""Profile two sleep calls
717
624
self.assertContainsRe(output,
718
625
r"LSProf output for <type 'unicode'>\(\('world',\), {'errors': 'replace'}\)\n")
720
def test_known_failure(self):
721
"""A KnownFailure being raised should trigger several result actions."""
722
class InstrumentedTestResult(ExtendedTestResult):
724
def report_test_start(self, test): pass
725
def report_known_failure(self, test, err):
726
self._call = test, err
727
result = InstrumentedTestResult(None, None, None, None)
729
raise KnownFailure('failed!')
730
test = unittest.FunctionTestCase(test_function)
732
# it should invoke 'report_known_failure'.
733
self.assertEqual(2, len(result._call))
734
self.assertEqual(test, result._call[0])
735
self.assertEqual(KnownFailure, result._call[1][0])
736
self.assertIsInstance(result._call[1][1], KnownFailure)
737
# we dont introspec the traceback, if the rest is ok, it would be
738
# exceptional for it not to be.
739
# it should update the known_failure_count on the object.
740
self.assertEqual(1, result.known_failure_count)
741
# the result should be successful.
742
self.assertTrue(result.wasSuccessful())
744
def test_verbose_report_known_failure(self):
745
# verbose test output formatting
746
result_stream = StringIO()
747
result = bzrlib.tests.VerboseTestResult(
748
unittest._WritelnDecorator(result_stream),
752
test = self.get_passing_test()
753
result.startTest(test)
754
result.extractBenchmarkTime(test)
755
prefix = len(result_stream.getvalue())
756
# the err parameter has the shape:
757
# (class, exception object, traceback)
758
# KnownFailures dont get their tracebacks shown though, so we
760
err = (KnownFailure, KnownFailure('foo'), None)
761
result.report_known_failure(test, err)
762
output = result_stream.getvalue()[prefix:]
763
lines = output.splitlines()
764
self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
765
self.assertEqual(lines[1], ' foo')
766
self.assertEqual(2, len(lines))
768
def test_text_report_known_failure(self):
769
# text test output formatting
771
result = bzrlib.tests.TextTestResult(
777
test = self.get_passing_test()
778
# this seeds the state to handle reporting the test.
779
result.startTest(test)
780
result.extractBenchmarkTime(test)
781
# the err parameter has the shape:
782
# (class, exception object, traceback)
783
# KnownFailures dont get their tracebacks shown though, so we
785
err = (KnownFailure, KnownFailure('foo'), None)
786
result.report_known_failure(test, err)
789
('update', '[1 in 0s] passing_test', None, None),
790
('note', 'XFAIL: %s\n%s\n', ('passing_test', err[1]))
793
# known_failures should be printed in the summary, so if we run a test
794
# after there are some known failures, the update prefix should match
796
result.known_failure_count = 3
800
('update', '[2 in 0s, 3 known failures] passing_test', None, None),
804
def get_passing_test(self):
805
"""Return a test object that can't be run usefully."""
808
return unittest.FunctionTestCase(passing_test)
810
def test_add_not_supported(self):
811
"""Test the behaviour of invoking addNotSupported."""
812
class InstrumentedTestResult(ExtendedTestResult):
813
def report_test_start(self, test): pass
814
def report_unsupported(self, test, feature):
815
self._call = test, feature
816
result = InstrumentedTestResult(None, None, None, None)
817
test = SampleTestCase('_test_pass')
819
result.startTest(test)
820
result.addNotSupported(test, feature)
821
# it should invoke 'report_unsupported'.
822
self.assertEqual(2, len(result._call))
823
self.assertEqual(test, result._call[0])
824
self.assertEqual(feature, result._call[1])
825
# the result should be successful.
826
self.assertTrue(result.wasSuccessful())
827
# it should record the test against a count of tests not run due to
829
self.assertEqual(1, result.unsupported['Feature'])
830
# and invoking it again should increment that counter
831
result.addNotSupported(test, feature)
832
self.assertEqual(2, result.unsupported['Feature'])
834
def test_verbose_report_unsupported(self):
835
# verbose test output formatting
836
result_stream = StringIO()
837
result = bzrlib.tests.VerboseTestResult(
838
unittest._WritelnDecorator(result_stream),
842
test = self.get_passing_test()
844
result.startTest(test)
845
result.extractBenchmarkTime(test)
846
prefix = len(result_stream.getvalue())
847
result.report_unsupported(test, feature)
848
output = result_stream.getvalue()[prefix:]
849
lines = output.splitlines()
850
self.assertEqual(lines, ['NODEP 0ms', " The feature 'Feature' is not available."])
852
def test_text_report_unsupported(self):
853
# text test output formatting
855
result = bzrlib.tests.TextTestResult(
861
test = self.get_passing_test()
863
# this seeds the state to handle reporting the test.
864
result.startTest(test)
865
result.extractBenchmarkTime(test)
866
result.report_unsupported(test, feature)
867
# no output on unsupported features
869
[('update', '[1 in 0s] passing_test', None, None)
872
# the number of missing features should be printed in the progress
873
# summary, so check for that.
874
result.unsupported = {'foo':0, 'bar':0}
878
('update', '[2 in 0s, 2 missing features] passing_test', None, None),
882
def test_unavailable_exception(self):
883
"""An UnavailableFeature being raised should invoke addNotSupported."""
884
class InstrumentedTestResult(ExtendedTestResult):
886
def report_test_start(self, test): pass
887
def addNotSupported(self, test, feature):
888
self._call = test, feature
889
result = InstrumentedTestResult(None, None, None, None)
892
raise UnavailableFeature(feature)
893
test = unittest.FunctionTestCase(test_function)
895
# it should invoke 'addNotSupported'.
896
self.assertEqual(2, len(result._call))
897
self.assertEqual(test, result._call[0])
898
self.assertEqual(feature, result._call[1])
899
# and not count as an error
900
self.assertEqual(0, result.error_count)
903
628
class TestRunner(TestCase):
922
647
TestCaseInTempDir.TEST_ROOT = old_root
924
def test_known_failure_failed_run(self):
925
# run a test that generates a known failure which should be printed in
926
# the final output when real failures occur.
927
def known_failure_test():
928
raise KnownFailure('failed')
929
test = unittest.TestSuite()
930
test.addTest(unittest.FunctionTestCase(known_failure_test))
932
raise AssertionError('foo')
933
test.addTest(unittest.FunctionTestCase(failing_test))
935
runner = TextTestRunner(stream=stream)
936
result = self.run_test_runner(runner, test)
937
lines = stream.getvalue().splitlines()
940
'======================================================================',
941
'FAIL: unittest.FunctionTestCase (failing_test)',
942
'----------------------------------------------------------------------',
943
'Traceback (most recent call last):',
944
' raise AssertionError(\'foo\')',
945
'AssertionError: foo',
947
'----------------------------------------------------------------------',
949
'FAILED (failures=1, known_failure_count=1)'],
950
lines[0:5] + lines[6:10] + lines[11:])
952
def test_known_failure_ok_run(self):
953
# run a test that generates a known failure which should be printed in the final output.
954
def known_failure_test():
955
raise KnownFailure('failed')
956
test = unittest.FunctionTestCase(known_failure_test)
958
runner = TextTestRunner(stream=stream)
959
result = self.run_test_runner(runner, test)
960
self.assertContainsRe(stream.getvalue(),
965
'OK \\(known_failures=1\\)\n')
649
def test_accepts_and_uses_pb_parameter(self):
650
test = TestRunner('dummy_test')
651
mypb = MockProgress()
652
self.assertEqual([], mypb.calls)
653
runner = TextTestRunner(stream=self._log_file, pb=mypb)
654
result = self.run_test_runner(runner, test)
655
self.assertEqual(1, result.testsRun)
656
self.assertEqual(('update', 'Running tests', 0, 1), mypb.calls[0])
657
self.assertEqual(('update', '...dummy_test', 0, None), mypb.calls[1])
658
self.assertEqual(('update', 'OK ', 1, None), mypb.calls[2])
659
self.assertEqual(('update', 'Cleaning up', 0, 1), mypb.calls[3])
660
self.assertEqual(('clear',), mypb.calls[4])
661
self.assertEqual(5, len(mypb.calls))
967
663
def test_skipped_test(self):
968
664
# run a test that is skipped, and check the suite as a whole still
970
666
# skipping_test must be hidden in here so it's not run as a real test
971
667
def skipping_test():
972
668
raise TestSkipped('test intentionally skipped')
974
669
runner = TextTestRunner(stream=self._log_file, keep_output=True)
975
670
test = unittest.FunctionTestCase(skipping_test)
976
671
result = self.run_test_runner(runner, test)
977
672
self.assertTrue(result.wasSuccessful())
979
def test_skipped_from_setup(self):
980
class SkippedSetupTest(TestCase):
984
self.addCleanup(self.cleanup)
985
raise TestSkipped('skipped setup')
988
self.fail('test reached')
993
runner = TextTestRunner(stream=self._log_file, keep_output=True)
994
test = SkippedSetupTest('test_skip')
995
result = self.run_test_runner(runner, test)
996
self.assertTrue(result.wasSuccessful())
997
# Check if cleanup was called the right number of times.
998
self.assertEqual(0, test.counter)
1000
def test_skipped_from_test(self):
1001
class SkippedTest(TestCase):
1005
self.addCleanup(self.cleanup)
1007
def test_skip(self):
1008
raise TestSkipped('skipped test')
1013
runner = TextTestRunner(stream=self._log_file, keep_output=True)
1014
test = SkippedTest('test_skip')
1015
result = self.run_test_runner(runner, test)
1016
self.assertTrue(result.wasSuccessful())
1017
# Check if cleanup was called the right number of times.
1018
self.assertEqual(0, test.counter)
1020
def test_unsupported_features_listed(self):
1021
"""When unsupported features are encountered they are detailed."""
1022
class Feature1(Feature):
1023
def _probe(self): return False
1024
class Feature2(Feature):
1025
def _probe(self): return False
1026
# create sample tests
1027
test1 = SampleTestCase('_test_pass')
1028
test1._test_needs_features = [Feature1()]
1029
test2 = SampleTestCase('_test_pass')
1030
test2._test_needs_features = [Feature2()]
1031
test = unittest.TestSuite()
1035
runner = TextTestRunner(stream=stream)
1036
result = self.run_test_runner(runner, test)
1037
lines = stream.getvalue().splitlines()
1040
"Missing feature 'Feature1' skipped 1 tests.",
1041
"Missing feature 'Feature2' skipped 1 tests.",
1045
def test_bench_history(self):
1046
# tests that the running the benchmark produces a history file
1047
# containing a timestamp and the revision id of the bzrlib source which
1049
workingtree = _get_bzr_source_tree()
1050
test = TestRunner('dummy_test')
1052
runner = TextTestRunner(stream=self._log_file, bench_history=output)
1053
result = self.run_test_runner(runner, test)
1054
output_string = output.getvalue()
1055
self.assertContainsRe(output_string, "--date [0-9.]+")
1056
if workingtree is not None:
1057
revision_id = workingtree.get_parent_ids()[0]
1058
self.assertEndsWith(output_string.rstrip(), revision_id)
1060
def test_success_log_deleted(self):
1061
"""Successful tests have their log deleted"""
1063
class LogTester(TestCase):
1065
def test_success(self):
1066
self.log('this will be removed\n')
1068
sio = cStringIO.StringIO()
1069
runner = TextTestRunner(stream=sio)
1070
test = LogTester('test_success')
1071
result = self.run_test_runner(runner, test)
1073
log = test._get_log()
1074
self.assertEqual("DELETED log file to reduce memory footprint", log)
1075
self.assertEqual('', test._log_contents)
1076
self.assertIs(None, test._log_file_name)
1078
def test_fail_log_kept(self):
1079
"""Failed tests have their log kept"""
1081
class LogTester(TestCase):
1083
def test_fail(self):
1084
self.log('this will be kept\n')
1085
self.fail('this test fails')
1087
sio = cStringIO.StringIO()
1088
runner = TextTestRunner(stream=sio)
1089
test = LogTester('test_fail')
1090
result = self.run_test_runner(runner, test)
1092
text = sio.getvalue()
1093
self.assertContainsRe(text, 'this will be kept')
1094
self.assertContainsRe(text, 'this test fails')
1096
log = test._get_log()
1097
self.assertContainsRe(log, 'this will be kept')
1098
self.assertEqual(log, test._log_contents)
1100
def test_error_log_kept(self):
1101
"""Tests with errors have their log kept"""
1103
class LogTester(TestCase):
1105
def test_error(self):
1106
self.log('this will be kept\n')
1107
raise ValueError('random exception raised')
1109
sio = cStringIO.StringIO()
1110
runner = TextTestRunner(stream=sio)
1111
test = LogTester('test_error')
1112
result = self.run_test_runner(runner, test)
1114
text = sio.getvalue()
1115
self.assertContainsRe(text, 'this will be kept')
1116
self.assertContainsRe(text, 'random exception raised')
1118
log = test._get_log()
1119
self.assertContainsRe(log, 'this will be kept')
1120
self.assertEqual(log, test._log_contents)
1123
class SampleTestCase(TestCase):
1125
def _test_pass(self):
1129
675
class TestTestCase(TestCase):
1130
676
"""Tests that test the core bzrlib TestCase."""
1209
747
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1210
748
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1212
def test_knownFailure(self):
1213
"""Self.knownFailure() should raise a KnownFailure exception."""
1214
self.assertRaises(KnownFailure, self.knownFailure, "A Failure")
1216
def test_requireFeature_available(self):
1217
"""self.requireFeature(available) is a no-op."""
1218
class Available(Feature):
1219
def _probe(self):return True
1220
feature = Available()
1221
self.requireFeature(feature)
1223
def test_requireFeature_unavailable(self):
1224
"""self.requireFeature(unavailable) raises UnavailableFeature."""
1225
class Unavailable(Feature):
1226
def _probe(self):return False
1227
feature = Unavailable()
1228
self.assertRaises(UnavailableFeature, self.requireFeature, feature)
1230
def test_run_no_parameters(self):
1231
test = SampleTestCase('_test_pass')
1234
def test_run_enabled_unittest_result(self):
1235
"""Test we revert to regular behaviour when the test is enabled."""
1236
test = SampleTestCase('_test_pass')
1237
class EnabledFeature(object):
1238
def available(self):
1240
test._test_needs_features = [EnabledFeature()]
1241
result = unittest.TestResult()
1243
self.assertEqual(1, result.testsRun)
1244
self.assertEqual([], result.errors)
1245
self.assertEqual([], result.failures)
1247
def test_run_disabled_unittest_result(self):
1248
"""Test our compatability for disabled tests with unittest results."""
1249
test = SampleTestCase('_test_pass')
1250
class DisabledFeature(object):
1251
def available(self):
1253
test._test_needs_features = [DisabledFeature()]
1254
result = unittest.TestResult()
1256
self.assertEqual(1, result.testsRun)
1257
self.assertEqual([], result.errors)
1258
self.assertEqual([], result.failures)
1260
def test_run_disabled_supporting_result(self):
1261
"""Test disabled tests behaviour with support aware results."""
1262
test = SampleTestCase('_test_pass')
1263
class DisabledFeature(object):
1264
def available(self):
1266
the_feature = DisabledFeature()
1267
test._test_needs_features = [the_feature]
1268
class InstrumentedTestResult(unittest.TestResult):
1270
unittest.TestResult.__init__(self)
1272
def startTest(self, test):
1273
self.calls.append(('startTest', test))
1274
def stopTest(self, test):
1275
self.calls.append(('stopTest', test))
1276
def addNotSupported(self, test, feature):
1277
self.calls.append(('addNotSupported', test, feature))
1278
result = InstrumentedTestResult()
1281
('startTest', test),
1282
('addNotSupported', test, the_feature),
1288
@symbol_versioning.deprecated_function(zero_eleven)
1289
def sample_deprecated_function():
1290
"""A deprecated function to test applyDeprecated with."""
1294
def sample_undeprecated_function(a_param):
1295
"""A undeprecated function to test applyDeprecated with."""
1298
class ApplyDeprecatedHelper(object):
1299
"""A helper class for ApplyDeprecated tests."""
1301
@symbol_versioning.deprecated_method(zero_eleven)
1302
def sample_deprecated_method(self, param_one):
1303
"""A deprecated method for testing with."""
1306
def sample_normal_method(self):
1307
"""A undeprecated method."""
1309
@symbol_versioning.deprecated_method(zero_ten)
1310
def sample_nested_deprecation(self):
1311
return sample_deprecated_function()
1314
751
class TestExtraAssertions(TestCase):
1315
752
"""Tests for new test assertions in bzrlib test suite"""
1324
761
self.assertEndsWith('foo', 'oo')
1325
762
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1327
def test_applyDeprecated_not_deprecated(self):
1328
sample_object = ApplyDeprecatedHelper()
1329
# calling an undeprecated callable raises an assertion
1330
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1331
sample_object.sample_normal_method)
1332
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1333
sample_undeprecated_function, "a param value")
1334
# calling a deprecated callable (function or method) with the wrong
1335
# expected deprecation fails.
1336
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1337
sample_object.sample_deprecated_method, "a param value")
1338
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1339
sample_deprecated_function)
1340
# calling a deprecated callable (function or method) with the right
1341
# expected deprecation returns the functions result.
1342
self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1343
sample_object.sample_deprecated_method, "a param value"))
1344
self.assertEqual(2, self.applyDeprecated(zero_eleven,
1345
sample_deprecated_function))
1346
# calling a nested deprecation with the wrong deprecation version
1347
# fails even if a deeper nested function was deprecated with the
1349
self.assertRaises(AssertionError, self.applyDeprecated,
1350
zero_eleven, sample_object.sample_nested_deprecation)
1351
# calling a nested deprecation with the right deprecation value
1352
# returns the calls result.
1353
self.assertEqual(2, self.applyDeprecated(zero_ten,
1354
sample_object.sample_nested_deprecation))
1356
def test_callDeprecated(self):
1357
def testfunc(be_deprecated, result=None):
1358
if be_deprecated is True:
1359
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1362
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1363
self.assertIs(None, result)
1364
result = self.callDeprecated([], testfunc, False, 'result')
1365
self.assertEqual('result', result)
1366
self.callDeprecated(['i am deprecated'], testfunc, be_deprecated=True)
1367
self.callDeprecated([], testfunc, be_deprecated=False)
1370
765
class TestConvenienceMakers(TestCaseWithTransport):
1371
766
"""Test for the make_* convenience functions."""
1414
788
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1415
789
test_suite_factory=factory)
1416
790
self.assertEqual([True], factory_called)
1419
class TestSelftestCleanOutput(TestCaseInTempDir):
1421
def test_clean_output(self):
1422
# test functionality of clean_selftest_output()
1423
self.build_tree(['test0000.tmp/', 'test0001.tmp/',
1424
'bzrlib/', 'tests/',
1425
'bzr', 'setup.py', 'test9999.tmp'])
1428
before = os.listdir(root)
1430
self.assertEquals(['bzr','bzrlib','setup.py',
1431
'test0000.tmp','test0001.tmp',
1432
'test9999.tmp','tests'],
1434
clean_selftest_output(root, quiet=True)
1435
after = os.listdir(root)
1437
self.assertEquals(['bzr','bzrlib','setup.py',
1438
'test9999.tmp','tests'],
1441
def test_clean_readonly(self):
1442
# test for delete read-only files
1443
self.build_tree(['test0000.tmp/', 'test0000.tmp/foo'])
1444
osutils.make_readonly('test0000.tmp/foo')
1446
before = os.listdir(root); before.sort()
1447
self.assertEquals(['test0000.tmp'], before)
1448
clean_selftest_output(root, quiet=True)
1449
after = os.listdir(root); after.sort()
1450
self.assertEquals([], after)
1453
class TestKnownFailure(TestCase):
1455
def test_known_failure(self):
1456
"""Check that KnownFailure is defined appropriately."""
1457
# a KnownFailure is an assertion error for compatability with unaware
1459
self.assertIsInstance(KnownFailure(""), AssertionError)
1461
def test_expect_failure(self):
1463
self.expectFailure("Doomed to failure", self.assertTrue, False)
1464
except KnownFailure, e:
1465
self.assertEqual('Doomed to failure', e.args[0])
1467
self.expectFailure("Doomed to failure", self.assertTrue, True)
1468
except AssertionError, e:
1469
self.assertEqual('Unexpected success. Should have failed:'
1470
' Doomed to failure', e.args[0])
1472
self.fail('Assertion not raised')
1475
class TestFeature(TestCase):
1477
def test_caching(self):
1478
"""Feature._probe is called by the feature at most once."""
1479
class InstrumentedFeature(Feature):
1481
Feature.__init__(self)
1484
self.calls.append('_probe')
1486
feature = InstrumentedFeature()
1488
self.assertEqual(['_probe'], feature.calls)
1490
self.assertEqual(['_probe'], feature.calls)
1492
def test_named_str(self):
1493
"""Feature.__str__ should thunk to feature_name()."""
1494
class NamedFeature(Feature):
1495
def feature_name(self):
1497
feature = NamedFeature()
1498
self.assertEqual('symlinks', str(feature))
1500
def test_default_str(self):
1501
"""Feature.__str__ should default to __class__.__name__."""
1502
class NamedFeature(Feature):
1504
feature = NamedFeature()
1505
self.assertEqual('NamedFeature', str(feature))
1508
class TestUnavailableFeature(TestCase):
1510
def test_access_feature(self):
1512
exception = UnavailableFeature(feature)
1513
self.assertIs(feature, exception.args[0])
1516
class TestSelftestFiltering(TestCase):
1519
self.suite = TestUtil.TestSuite()
1520
self.loader = TestUtil.TestLoader()
1521
self.suite.addTest(self.loader.loadTestsFromModuleNames([
1522
'bzrlib.tests.test_selftest']))
1523
self.all_names = [t.id() for t in iter_suite_tests(self.suite)]
1525
def test_filter_suite_by_re(self):
1526
filtered_suite = filter_suite_by_re(self.suite, 'test_filter')
1527
filtered_names = [t.id() for t in iter_suite_tests(filtered_suite)]
1528
self.assertEqual(filtered_names, ['bzrlib.tests.test_selftest.'
1529
'TestSelftestFiltering.test_filter_suite_by_re'])
1531
def test_sort_suite_by_re(self):
1532
sorted_suite = sort_suite_by_re(self.suite, 'test_filter')
1533
sorted_names = [t.id() for t in iter_suite_tests(sorted_suite)]
1534
self.assertEqual(sorted_names[0], 'bzrlib.tests.test_selftest.'
1535
'TestSelftestFiltering.test_filter_suite_by_re')
1536
self.assertEquals(sorted(self.all_names), sorted(sorted_names))