94
90
DocTestMatches(u"...a test message\n", doctest.ELLIPSIS))
93
class TestUnicodeFilename(tests.TestCase):
95
def test_probe_passes(self):
96
"""UnicodeFilename._probe passes."""
97
# We can't test much more than that because the behaviour depends
99
tests.UnicodeFilename._probe()
97
102
class TestTreeShape(tests.TestCaseInTempDir):
99
104
def test_unicode_paths(self):
100
self.requireFeature(features.UnicodeFilenameFeature)
105
self.requireFeature(tests.UnicodeFilename)
102
107
filename = u'hell\u00d8'
103
108
self.build_tree_contents([(filename, 'contents of hello')])
104
self.assertPathExists(filename)
109
self.failUnlessExists(filename)
107
112
class TestClassesAvailable(tests.TestCase):
373
formats = [workingtree_4.WorkingTreeFormat4(),
374
workingtree_3.WorkingTreeFormat3(),]
378
formats = [workingtree.WorkingTreeFormat4(),
379
workingtree.WorkingTreeFormat3(),]
375
380
scenarios = make_scenarios(server1, server2, formats)
376
381
self.assertEqual(7, len(scenarios))
377
382
default_wt_format = workingtree.format_registry.get_default()
378
wt4_format = workingtree_4.WorkingTreeFormat4()
379
wt5_format = workingtree_4.WorkingTreeFormat5()
383
wt4_format = workingtree.WorkingTreeFormat4()
384
wt5_format = workingtree.WorkingTreeFormat5()
380
385
expected_scenarios = [
381
386
('WorkingTreeFormat4',
382
387
{'bzrdir_format': formats[0]._matchingbzrdir,
506
510
self.assertRaises(AssertionError, self.assertEqualStat,
507
511
os.lstat("foo"), os.lstat("longname"))
509
def test_failUnlessExists(self):
510
"""Deprecated failUnlessExists and failIfExists"""
511
self.applyDeprecated(
512
deprecated_in((2, 4)),
513
self.failUnlessExists, '.')
514
self.build_tree(['foo/', 'foo/bar'])
515
self.applyDeprecated(
516
deprecated_in((2, 4)),
517
self.failUnlessExists, 'foo/bar')
518
self.applyDeprecated(
519
deprecated_in((2, 4)),
520
self.failIfExists, 'foo/foo')
522
def test_assertPathExists(self):
523
self.assertPathExists('.')
524
self.build_tree(['foo/', 'foo/bar'])
525
self.assertPathExists('foo/bar')
526
self.assertPathDoesNotExist('foo/foo')
529
514
class TestTestCaseWithMemoryTransport(tests.TestCaseWithMemoryTransport):
574
559
tree = self.make_branch_and_memory_tree('dir', format=format)
575
560
# Guard against regression into MemoryTransport leaking
576
561
# files to disk instead of keeping them in memory.
577
self.assertFalse(osutils.lexists('dir'))
562
self.failIf(osutils.lexists('dir'))
578
563
self.assertIsInstance(tree, memorytree.MemoryTree)
579
564
self.assertEqual(format.repository_format.__class__,
580
565
tree.branch.repository._format.__class__)
596
581
the_branch = builder.get_branch()
597
582
# Guard against regression into MemoryTransport leaking
598
583
# files to disk instead of keeping them in memory.
599
self.assertFalse(osutils.lexists('dir'))
584
self.failIf(osutils.lexists('dir'))
600
585
self.assertEqual(format.repository_format.__class__,
601
586
the_branch.repository._format.__class__)
602
587
self.assertEqual(repo_format.get_format_string(),
646
631
url = self.get_readonly_url()
647
632
url2 = self.get_readonly_url('foo/bar')
648
t = transport.get_transport_from_url(url)
649
t2 = transport.get_transport_from_url(url2)
650
self.assertIsInstance(t, ReadonlyTransportDecorator)
651
self.assertIsInstance(t2, ReadonlyTransportDecorator)
633
t = transport.get_transport(url)
634
t2 = transport.get_transport(url2)
635
self.failUnless(isinstance(t, ReadonlyTransportDecorator))
636
self.failUnless(isinstance(t2, ReadonlyTransportDecorator))
652
637
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
654
639
def test_get_readonly_url_http(self):
660
645
url = self.get_readonly_url()
661
646
url2 = self.get_readonly_url('foo/bar')
662
647
# the transport returned may be any HttpTransportBase subclass
663
t = transport.get_transport_from_url(url)
664
t2 = transport.get_transport_from_url(url2)
665
self.assertIsInstance(t, HttpTransportBase)
666
self.assertIsInstance(t2, HttpTransportBase)
648
t = transport.get_transport(url)
649
t2 = transport.get_transport(url2)
650
self.failUnless(isinstance(t, HttpTransportBase))
651
self.failUnless(isinstance(t2, HttpTransportBase))
667
652
self.assertEqual(t2.base[:-1], t.abspath('foo/bar'))
669
654
def test_is_directory(self):
699
684
self.assertIsInstance(result_bzrdir.transport,
700
685
memory.MemoryTransport)
701
686
# should not be on disk, should only be in memory
702
self.assertPathDoesNotExist('subdir')
687
self.failIfExists('subdir')
705
690
class TestChrootedTest(tests.ChrootedTestCase):
707
692
def test_root_is_root(self):
708
t = transport.get_transport_from_url(self.get_readonly_url())
693
t = transport.get_transport(self.get_readonly_url())
710
695
self.assertEqual(url, t.clone('..').base)
764
749
self.check_timing(ShortDelayTestCase('test_short_delay'),
752
def _patch_get_bzr_source_tree(self):
753
# Reading from the actual source tree breaks isolation, but we don't
754
# want to assume that thats *all* that would happen.
755
self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', lambda: None)
757
def test_assigned_benchmark_file_stores_date(self):
758
self._patch_get_bzr_source_tree()
760
result = bzrlib.tests.TextTestResult(self._log_file,
765
output_string = output.getvalue()
766
# if you are wondering about the regexp please read the comment in
767
# test_bench_history (bzrlib.tests.test_selftest.TestRunner)
768
# XXX: what comment? -- Andrew Bennetts
769
self.assertContainsRe(output_string, "--date [0-9.]+")
771
def test_benchhistory_records_test_times(self):
772
self._patch_get_bzr_source_tree()
773
result_stream = StringIO()
774
result = bzrlib.tests.TextTestResult(
778
bench_history=result_stream
781
# we want profile a call and check that its test duration is recorded
782
# make a new test instance that when run will generate a benchmark
783
example_test_case = TestTestResult("_time_hello_world_encoding")
784
# execute the test, which should succeed and record times
785
example_test_case.run(result)
786
lines = result_stream.getvalue().splitlines()
787
self.assertEqual(2, len(lines))
788
self.assertContainsRe(lines[1],
789
" *[0-9]+ms bzrlib.tests.test_selftest.TestTestResult"
790
"._time_hello_world_encoding")
767
792
def _time_hello_world_encoding(self):
768
793
"""Profile two sleep calls
859
_get_test("test_xfail").run(result)
860
self.assertContainsRe(result_stream.getvalue(),
861
"\n\\S+\\.test_xfail\\s+XFAIL\\s+\\d+ms\n"
862
"\\s*(?:Text attachment: )?reason"
884
test = self.get_passing_test()
885
result.startTest(test)
886
prefix = len(result_stream.getvalue())
887
# the err parameter has the shape:
888
# (class, exception object, traceback)
889
# KnownFailures dont get their tracebacks shown though, so we
891
err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
892
result.report_known_failure(test, err)
893
output = result_stream.getvalue()[prefix:]
894
lines = output.splitlines()
895
self.assertContainsRe(lines[0], r'XFAIL *\d+ms$')
896
if sys.version_info > (2, 7):
897
self.expectFailure("_ExpectedFailure on 2.7 loses the message",
898
self.assertNotEqual, lines[1], ' ')
899
self.assertEqual(lines[1], ' foo')
900
self.assertEqual(2, len(lines))
867
902
def get_passing_test(self):
868
903
"""Return a test object that can't be run usefully."""
879
914
self._call = test, feature
880
915
result = InstrumentedTestResult(None, None, None, None)
881
916
test = SampleTestCase('_test_pass')
882
feature = features.Feature()
917
feature = tests.Feature()
883
918
result.startTest(test)
884
919
result.addNotSupported(test, feature)
885
920
# it should invoke 'report_unsupported'.
923
958
def addNotSupported(self, test, feature):
924
959
self._call = test, feature
925
960
result = InstrumentedTestResult(None, None, None, None)
926
feature = features.Feature()
961
feature = tests.Feature()
927
962
class Test(tests.TestCase):
928
963
def test_function(self):
929
964
raise tests.UnavailableFeature(feature)
948
983
def test_strict_with_known_failure(self):
949
984
result = bzrlib.tests.TextTestResult(self._log_file, descriptions=0,
951
test = _get_test("test_xfail")
986
test = self.get_passing_test()
987
err = (tests.KnownFailure, tests.KnownFailure('foo'), None)
988
result.addExpectedFailure(test, err)
953
989
self.assertFalse(result.wasStrictlySuccessful())
954
990
self.assertEqual(None, result._extractBenchmarkTime(test))
1057
1102
'OK \\(known_failures=1\\)\n')
1059
def test_unexpected_success_bad(self):
1060
class Test(tests.TestCase):
1061
def test_truth(self):
1062
self.expectFailure("No absolute truth", self.assertTrue, True)
1063
runner = tests.TextTestRunner(stream=StringIO())
1064
result = self.run_test_runner(runner, Test("test_truth"))
1065
if testtools_version[:3] <= (0, 9, 11):
1066
self.assertContainsRe(runner.stream.getvalue(),
1068
"FAIL: \\S+\.test_truth\n"
1071
"No absolute truth\n"
1074
"Ran 1 test in .*\n"
1076
"FAILED \\(failures=1\\)\n\\Z")
1078
self.assertContainsRe(runner.stream.getvalue(),
1080
"FAIL: \\S+\.test_truth\n"
1082
"Empty attachments:\n"
1085
"reason: {{{No absolute truth}}}\n"
1087
"Ran 1 test in .*\n"
1089
"FAILED \\(failures=1\\)\n\\Z")
1091
1104
def test_result_decorator(self):
1092
1105
# decorate results
1178
1191
def test_unsupported_features_listed(self):
1179
1192
"""When unsupported features are encountered they are detailed."""
1180
class Feature1(features.Feature):
1193
class Feature1(tests.Feature):
1181
1194
def _probe(self): return False
1182
class Feature2(features.Feature):
1195
class Feature2(tests.Feature):
1183
1196
def _probe(self): return False
1184
1197
# create sample tests
1185
1198
test1 = SampleTestCase('_test_pass')
1216
def _patch_get_bzr_source_tree(self):
1217
# Reading from the actual source tree breaks isolation, but we don't
1218
# want to assume that thats *all* that would happen.
1219
self._get_source_tree_calls = []
1221
self._get_source_tree_calls.append("called")
1223
self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', new_get)
1225
def test_bench_history(self):
1226
# tests that the running the benchmark passes bench_history into
1227
# the test result object. We can tell that happens if
1228
# _get_bzr_source_tree is called.
1229
self._patch_get_bzr_source_tree()
1230
test = TestRunner('dummy_test')
1232
runner = tests.TextTestRunner(stream=self._log_file,
1233
bench_history=output)
1234
result = self.run_test_runner(runner, test)
1235
output_string = output.getvalue()
1236
self.assertContainsRe(output_string, "--date [0-9.]+")
1237
self.assertLength(1, self._get_source_tree_calls)
1203
1239
def test_verbose_test_count(self):
1204
1240
"""A verbose test run reports the right test count at the start"""
1205
1241
suite = TestUtil.TestSuite([
1251
1287
lambda trace=False: "ascii")
1252
1288
result = self.run_test_runner(tests.TextTestRunner(stream=out),
1253
1289
FailureWithUnicode("test_log_unicode"))
1254
if testtools_version[:3] > (0, 9, 11):
1255
self.assertContainsRe(out.getvalue(), "log: {{{\d+\.\d+ \\\\u2606}}}")
1257
self.assertContainsRe(out.getvalue(),
1258
"Text attachment: log\n"
1260
"\d+\.\d+ \\\\u2606\n"
1290
self.assertContainsRe(out.getvalue(),
1291
"Text attachment: log\n"
1293
"\d+\.\d+ \\\\u2606\n"
1264
1297
class SampleTestCase(tests.TestCase):
1453
1486
# Note this test won't fail with hooks that the core library doesn't
1454
1487
# use - but it trigger with a plugin that adds hooks, so its still a
1455
1488
# useful warning in that case.
1456
self.assertEqual(bzrlib.branch.BranchHooks(), bzrlib.branch.Branch.hooks)
1458
bzrlib.smart.server.SmartServerHooks(),
1489
self.assertEqual(bzrlib.branch.BranchHooks(),
1490
bzrlib.branch.Branch.hooks)
1491
self.assertEqual(bzrlib.smart.server.SmartServerHooks(),
1459
1492
bzrlib.smart.server.SmartTCPServer.hooks)
1461
bzrlib.commands.CommandHooks(), bzrlib.commands.Command.hooks)
1493
self.assertEqual(bzrlib.commands.CommandHooks(),
1494
bzrlib.commands.Command.hooks)
1463
1496
def test__gather_lsprof_in_benchmarks(self):
1464
1497
"""When _gather_lsprof_in_benchmarks is on, accumulate profile data.
1466
1499
Each self.time() call is individually and separately profiled.
1468
self.requireFeature(features.lsprof_feature)
1501
self.requireFeature(test_lsprof.LSProfFeature)
1469
1502
# overrides the class member with an instance member so no cleanup
1471
1504
self._gather_lsprof_in_benchmarks = True
1490
1523
transport_server = memory.MemoryServer()
1491
1524
transport_server.start_server()
1492
1525
self.addCleanup(transport_server.stop_server)
1493
t = transport.get_transport_from_url(transport_server.get_url())
1526
t = transport.get_transport(transport_server.get_url())
1494
1527
bzrdir.BzrDir.create(t.base)
1495
1528
self.assertRaises(errors.BzrError,
1496
1529
bzrdir.BzrDir.open_from_transport, t)
1502
1535
def test_requireFeature_available(self):
1503
1536
"""self.requireFeature(available) is a no-op."""
1504
class Available(features.Feature):
1537
class Available(tests.Feature):
1505
1538
def _probe(self):return True
1506
1539
feature = Available()
1507
1540
self.requireFeature(feature)
1509
1542
def test_requireFeature_unavailable(self):
1510
1543
"""self.requireFeature(unavailable) raises UnavailableFeature."""
1511
class Unavailable(features.Feature):
1544
class Unavailable(tests.Feature):
1512
1545
def _probe(self):return False
1513
1546
feature = Unavailable()
1514
1547
self.assertRaises(tests.UnavailableFeature,
1673
1706
test.run(unittest.TestResult())
1674
1707
self.assertEqual('original', obj.test_attr)
1676
def test_recordCalls(self):
1677
from bzrlib.tests import test_selftest
1678
calls = self.recordCalls(
1679
test_selftest, '_add_numbers')
1680
self.assertEqual(test_selftest._add_numbers(2, 10),
1682
self.assertEquals(calls, [((2, 10), {})])
1685
def _add_numbers(a, b):
1689
class _MissingFeature(features.Feature):
1710
class _MissingFeature(tests.Feature):
1690
1711
def _probe(self):
1692
1713
missing_feature = _MissingFeature()
1743
1764
result = self._run_test('test_fail')
1744
1765
self.assertEqual(1, len(result.failures))
1745
1766
result_content = result.failures[0][1]
1746
if testtools_version < (0, 9, 12):
1747
self.assertContainsRe(result_content, 'Text attachment: log')
1767
self.assertContainsRe(result_content, 'Text attachment: log')
1748
1768
self.assertContainsRe(result_content, 'this was a failing test')
1750
1770
def test_error_has_log(self):
1751
1771
result = self._run_test('test_error')
1752
1772
self.assertEqual(1, len(result.errors))
1753
1773
result_content = result.errors[0][1]
1754
if testtools_version < (0, 9, 12):
1755
self.assertContainsRe(result_content, 'Text attachment: log')
1774
self.assertContainsRe(result_content, 'Text attachment: log')
1756
1775
self.assertContainsRe(result_content, 'this test errored')
1758
1777
def test_skip_has_no_log(self):
2040
2059
self.assertLength(2, output.readlines())
2042
2061
def test_lsprof_tests(self):
2043
self.requireFeature(features.lsprof_feature)
2062
self.requireFeature(test_lsprof.LSProfFeature)
2045
2064
class Test(object):
2046
2065
def __call__(test, result):
2047
2066
test.run(result)
2048
2067
def run(test, result):
2049
results.append(result)
2068
self.assertIsInstance(result, ExtendedToOriginalDecorator)
2069
calls.append("called")
2050
2070
def countTestCases(self):
2052
2072
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
2053
self.assertLength(1, results)
2054
self.assertIsInstance(results.pop(), ExtendedToOriginalDecorator)
2073
self.assertLength(1, calls)
2056
2075
def test_random(self):
2057
2076
# test randomising by listing a number of tests.
2199
2218
content, result = self.run_subunit_stream('test_unexpected_success')
2200
2219
self.assertContainsRe(content, '(?m)^log$')
2201
2220
self.assertContainsRe(content, 'test with unexpected success')
2202
# GZ 2011-05-18: Old versions of subunit treat unexpected success as a
2203
# success, if a min version check is added remove this
2204
from subunit import TestProtocolClient as _Client
2205
if _Client.addUnexpectedSuccess.im_func is _Client.addSuccess.im_func:
2206
self.expectFailure('subunit treats "unexpectedSuccess"'
2207
' as a plain success',
2208
self.assertEqual, 1, len(result.unexpectedSuccesses))
2221
self.expectFailure('subunit treats "unexpectedSuccess"'
2222
' as a plain success',
2223
self.assertEqual, 1, len(result.unexpectedSuccesses))
2209
2224
self.assertEqual(1, len(result.unexpectedSuccesses))
2210
2225
test = result.unexpectedSuccesses[0]
2211
2226
# RemotedTestCase doesn't preserve the "details"
2511
2526
class TestStartBzrSubProcess(tests.TestCase):
2512
"""Stub test start_bzr_subprocess."""
2514
def _subprocess_log_cleanup(self):
2515
"""Inhibits the base version as we don't produce a log file."""
2528
def check_popen_state(self):
2529
"""Replace to make assertions when popen is called."""
2517
2531
def _popen(self, *args, **kwargs):
2518
"""Override the base version to record the command that is run.
2520
From there we can ensure it is correct without spawning a real process.
2532
"""Record the command that is run, so that we can ensure it is correct"""
2522
2533
self.check_popen_state()
2523
2534
self._popen_args = args
2524
2535
self._popen_kwargs = kwargs
2525
2536
raise _DontSpawnProcess()
2527
def check_popen_state(self):
2528
"""Replace to make assertions when popen is called."""
2530
2538
def test_run_bzr_subprocess_no_plugins(self):
2531
2539
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2532
2540
command = self._popen_args[0]
2537
2545
def test_allow_plugins(self):
2538
2546
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2540
2548
command = self._popen_args[0]
2541
2549
self.assertEqual([], command[2:])
2543
2551
def test_set_env(self):
2544
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2552
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2545
2553
# set in the child
2546
2554
def check_environment():
2547
2555
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2548
2556
self.check_popen_state = check_environment
2549
2557
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2550
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2558
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2551
2559
# not set in theparent
2552
2560
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2554
2562
def test_run_bzr_subprocess_env_del(self):
2555
2563
"""run_bzr_subprocess can remove environment variables too."""
2556
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2564
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2557
2565
def check_environment():
2558
2566
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2559
2567
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2560
2568
self.check_popen_state = check_environment
2561
2569
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2562
env_changes={'EXISTANT_ENV_VAR':None})
2570
env_changes={'EXISTANT_ENV_VAR':None})
2563
2571
# Still set in parent
2564
2572
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2565
2573
del os.environ['EXISTANT_ENV_VAR']
2567
2575
def test_env_del_missing(self):
2568
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2576
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2569
2577
def check_environment():
2570
2578
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2571
2579
self.check_popen_state = check_environment
2572
2580
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2573
env_changes={'NON_EXISTANT_ENV_VAR':None})
2581
env_changes={'NON_EXISTANT_ENV_VAR':None})
2575
2583
def test_working_dir(self):
2576
2584
"""Test that we can specify the working dir for the child"""
2580
2588
def chdir(path):
2581
2589
chdirs.append(path)
2582
self.overrideAttr(os, 'chdir', chdir)
2585
self.overrideAttr(osutils, 'getcwd', getcwd)
2586
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2594
osutils.getcwd = getcwd
2596
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2599
osutils.getcwd = orig_getcwd
2601
os.chdir = orig_chdir
2588
2602
self.assertEqual(['foo', 'current'], chdirs)
2590
2604
def test_get_bzr_path_with_cwd_bzrlib(self):
2610
2624
self.assertEqual('bzr: interrupted\n', result[1])
2627
class TestFeature(tests.TestCase):
2629
def test_caching(self):
2630
"""Feature._probe is called by the feature at most once."""
2631
class InstrumentedFeature(tests.Feature):
2633
super(InstrumentedFeature, self).__init__()
2636
self.calls.append('_probe')
2638
feature = InstrumentedFeature()
2640
self.assertEqual(['_probe'], feature.calls)
2642
self.assertEqual(['_probe'], feature.calls)
2644
def test_named_str(self):
2645
"""Feature.__str__ should thunk to feature_name()."""
2646
class NamedFeature(tests.Feature):
2647
def feature_name(self):
2649
feature = NamedFeature()
2650
self.assertEqual('symlinks', str(feature))
2652
def test_default_str(self):
2653
"""Feature.__str__ should default to __class__.__name__."""
2654
class NamedFeature(tests.Feature):
2656
feature = NamedFeature()
2657
self.assertEqual('NamedFeature', str(feature))
2660
class TestUnavailableFeature(tests.TestCase):
2662
def test_access_feature(self):
2663
feature = tests.Feature()
2664
exception = tests.UnavailableFeature(feature)
2665
self.assertIs(feature, exception.args[0])
2668
simple_thunk_feature = tests._CompatabilityThunkFeature(
2669
deprecated_in((2, 1, 0)),
2670
'bzrlib.tests.test_selftest',
2671
'simple_thunk_feature','UnicodeFilename',
2672
replacement_module='bzrlib.tests'
2675
class Test_CompatibilityFeature(tests.TestCase):
2677
def test_does_thunk(self):
2678
res = self.callDeprecated(
2679
['bzrlib.tests.test_selftest.simple_thunk_feature was deprecated'
2680
' in version 2.1.0. Use bzrlib.tests.UnicodeFilename instead.'],
2681
simple_thunk_feature.available)
2682
self.assertEqual(tests.UnicodeFilename.available(), res)
2685
class TestModuleAvailableFeature(tests.TestCase):
2687
def test_available_module(self):
2688
feature = tests.ModuleAvailableFeature('bzrlib.tests')
2689
self.assertEqual('bzrlib.tests', feature.module_name)
2690
self.assertEqual('bzrlib.tests', str(feature))
2691
self.assertTrue(feature.available())
2692
self.assertIs(tests, feature.module)
2694
def test_unavailable_module(self):
2695
feature = tests.ModuleAvailableFeature('bzrlib.no_such_module_exists')
2696
self.assertEqual('bzrlib.no_such_module_exists', str(feature))
2697
self.assertFalse(feature.available())
2698
self.assertIs(None, feature.module)
2613
2701
class TestSelftestFiltering(tests.TestCase):
2615
2703
def setUp(self):
2766
2854
self.assertEqual(remaining_names, _test_ids(split_suite[1]))
2769
class TestCheckTreeShape(tests.TestCaseWithTransport):
2857
class TestCheckInventoryShape(tests.TestCaseWithTransport):
2771
def test_check_tree_shape(self):
2859
def test_check_inventory_shape(self):
2772
2860
files = ['a', 'b/', 'b/c']
2773
2861
tree = self.make_branch_and_tree('.')
2774
2862
self.build_tree(files)
2775
2863
tree.add(files)
2776
2864
tree.lock_read()
2778
self.check_tree_shape(tree, files)
2866
self.check_inventory_shape(tree.inventory, files)
3453
3541
self.assertDocTestStringFails(doctest.DocTestSuite, test)
3454
3542
# tests.DocTestSuite sees None
3455
3543
self.assertDocTestStringSucceds(tests.IsolatedDocTestSuite, test)
3458
class TestSelftestExcludePatterns(tests.TestCase):
3461
super(TestSelftestExcludePatterns, self).setUp()
3462
self.overrideAttr(tests, 'test_suite', self.suite_factory)
3464
def suite_factory(self, keep_only=None, starting_with=None):
3465
"""A test suite factory with only a few tests."""
3466
class Test(tests.TestCase):
3468
# We don't need the full class path
3469
return self._testMethodName
3476
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
3478
def assertTestList(self, expected, *selftest_args):
3479
# We rely on setUp installing the right test suite factory so we can
3480
# test at the command level without loading the whole test suite
3481
out, err = self.run_bzr(('selftest', '--list') + selftest_args)
3482
actual = out.splitlines()
3483
self.assertEquals(expected, actual)
3485
def test_full_list(self):
3486
self.assertTestList(['a', 'b', 'c'])
3488
def test_single_exclude(self):
3489
self.assertTestList(['b', 'c'], '-x', 'a')
3491
def test_mutiple_excludes(self):
3492
self.assertTestList(['c'], '-x', 'a', '-x', 'b')
3495
class TestCounterHooks(tests.TestCase, SelfTestHelper):
3497
_test_needs_features = [features.subunit]
3500
super(TestCounterHooks, self).setUp()
3501
class Test(tests.TestCase):
3504
super(Test, self).setUp()
3505
self.hooks = hooks.Hooks()
3506
self.hooks.add_hook('myhook', 'Foo bar blah', (2,4))
3507
self.install_counter_hook(self.hooks, 'myhook')
3512
def run_hook_once(self):
3513
for hook in self.hooks['myhook']:
3516
self.test_class = Test
3518
def assertHookCalls(self, expected_calls, test_name):
3519
test = self.test_class(test_name)
3520
result = unittest.TestResult()
3522
self.assertTrue(hasattr(test, '_counters'))
3523
self.assertTrue(test._counters.has_key('myhook'))
3524
self.assertEquals(expected_calls, test._counters['myhook'])
3526
def test_no_hook(self):
3527
self.assertHookCalls(0, 'no_hook')
3529
def test_run_hook_once(self):
3530
tt = features.testtools
3531
if tt.module.__version__ < (0, 9, 8):
3532
raise tests.TestSkipped('testtools-0.9.8 required for addDetail')
3533
self.assertHookCalls(1, 'run_hook_once')