576
577
self.get_transport().get_bytes(
577
578
'dir/.bzr/repository/format'))
579
def test_safety_net(self):
580
"""No test should modify the safety .bzr directory.
582
We just test that the _check_safety_net private method raises
583
AssertionError, it's easier than building a test suite with the same
586
# Oops, a commit in the current directory (i.e. without local .bzr
587
# directory) will crawl up the hierarchy to find a .bzr directory.
588
self.run_bzr(['commit', '-mfoo', '--unchanged'])
589
# But we have a safety net in place.
590
self.assertRaises(AssertionError, self._check_safety_net)
592
580
def test_dangling_locks_cause_failures(self):
593
581
class TestDanglingLock(tests.TestCaseWithMemoryTransport):
594
582
def test_function(self):
687
675
self.assertEqual(url, t.clone('..').base)
678
class TestProfileResult(tests.TestCase):
680
def test_profiles_tests(self):
681
self.requireFeature(test_lsprof.LSProfFeature)
682
terminal = unittest.TestResult()
683
result = tests.ProfileResult(terminal)
684
class Sample(tests.TestCase):
686
self.sample_function()
687
def sample_function(self):
690
test.attrs_to_keep = test.attrs_to_keep + ('_benchcalls',)
692
self.assertLength(1, test._benchcalls)
693
# We must be able to unpack it as the test reporting code wants
694
(_, _, _), stats = test._benchcalls[0]
695
self.assertTrue(callable(stats.pprint))
690
698
class TestTestResult(tests.TestCase):
692
700
def check_timing(self, test_case, expected_re):
719
727
self.check_timing(ShortDelayTestCase('test_short_delay'),
730
def _patch_get_bzr_source_tree(self):
731
# Reading from the actual source tree breaks isolation, but we don't
732
# want to assume that thats *all* that would happen.
733
def _get_bzr_source_tree():
735
orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
736
bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
738
bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
739
self.addCleanup(restore)
722
741
def test_assigned_benchmark_file_stores_date(self):
742
self._patch_get_bzr_source_tree()
723
743
output = StringIO()
724
744
result = bzrlib.tests.TextTestResult(self._log_file,
981
1002
because of our use of global state.
983
1004
old_root = tests.TestCaseInTempDir.TEST_ROOT
1005
old_leak = tests.TestCase._first_thread_leaker_id
985
1007
tests.TestCaseInTempDir.TEST_ROOT = None
1008
tests.TestCase._first_thread_leaker_id = None
986
1009
return testrunner.run(test)
988
1011
tests.TestCaseInTempDir.TEST_ROOT = old_root
1012
tests.TestCase._first_thread_leaker_id = old_leak
990
1014
def test_known_failure_failed_run(self):
991
1015
# run a test that generates a known failure which should be printed in
1032
1056
'OK \\(known_failures=1\\)\n')
1058
def test_result_decorator(self):
1061
class LoggingDecorator(tests.ForwardingResult):
1062
def startTest(self, test):
1063
tests.ForwardingResult.startTest(self, test)
1064
calls.append('start')
1065
test = unittest.FunctionTestCase(lambda:None)
1067
runner = tests.TextTestRunner(stream=stream,
1068
result_decorators=[LoggingDecorator])
1069
result = self.run_test_runner(runner, test)
1070
self.assertLength(1, calls)
1034
1072
def test_skipped_test(self):
1035
1073
# run a test that is skipped, and check the suite as a whole still
1169
def _patch_get_bzr_source_tree(self):
1170
# Reading from the actual source tree breaks isolation, but we don't
1171
# want to assume that thats *all* that would happen.
1172
self._get_source_tree_calls = []
1173
def _get_bzr_source_tree():
1174
self._get_source_tree_calls.append("called")
1176
orig_get_bzr_source_tree = bzrlib.version._get_bzr_source_tree
1177
bzrlib.version._get_bzr_source_tree = _get_bzr_source_tree
1179
bzrlib.version._get_bzr_source_tree = orig_get_bzr_source_tree
1180
self.addCleanup(restore)
1135
1182
def test_bench_history(self):
1136
# tests that the running the benchmark produces a history file
1137
# containing a timestamp and the revision id of the bzrlib source which
1139
workingtree = _get_bzr_source_tree()
1183
# tests that the running the benchmark passes bench_history into
1184
# the test result object. We can tell that happens if
1185
# _get_bzr_source_tree is called.
1186
self._patch_get_bzr_source_tree()
1140
1187
test = TestRunner('dummy_test')
1141
1188
output = StringIO()
1142
1189
runner = tests.TextTestRunner(stream=self._log_file,
1144
1191
result = self.run_test_runner(runner, test)
1145
1192
output_string = output.getvalue()
1146
1193
self.assertContainsRe(output_string, "--date [0-9.]+")
1147
if workingtree is not None:
1148
revision_id = workingtree.get_parent_ids()[0]
1149
self.assertEndsWith(output_string.rstrip(), revision_id)
1194
self.assertLength(1, self._get_source_tree_calls)
1151
1196
def assertLogDeleted(self, test):
1152
1197
log = test._get_log()
1261
1306
self.assertContainsRe(log, 'this will be kept')
1262
1307
self.assertEqual(log, test._log_contents)
1309
def test_startTestRun(self):
1310
"""run should call result.startTestRun()"""
1312
class LoggingDecorator(tests.ForwardingResult):
1313
def startTestRun(self):
1314
tests.ForwardingResult.startTestRun(self)
1315
calls.append('startTestRun')
1316
test = unittest.FunctionTestCase(lambda:None)
1318
runner = tests.TextTestRunner(stream=stream,
1319
result_decorators=[LoggingDecorator])
1320
result = self.run_test_runner(runner, test)
1321
self.assertLength(1, calls)
1323
def test_stopTestRun(self):
1324
"""run should call result.stopTestRun()"""
1326
class LoggingDecorator(tests.ForwardingResult):
1327
def stopTestRun(self):
1328
tests.ForwardingResult.stopTestRun(self)
1329
calls.append('stopTestRun')
1330
test = unittest.FunctionTestCase(lambda:None)
1332
runner = tests.TextTestRunner(stream=stream,
1333
result_decorators=[LoggingDecorator])
1334
result = self.run_test_runner(runner, test)
1335
self.assertLength(1, calls)
1265
1338
class SampleTestCase(tests.TestCase):
1480
1554
self.assertEqual((time.sleep, (0.003,), {}), self._benchcalls[1][0])
1481
1555
self.assertIsInstance(self._benchcalls[0][1], bzrlib.lsprof.Stats)
1482
1556
self.assertIsInstance(self._benchcalls[1][1], bzrlib.lsprof.Stats)
1557
del self._benchcalls[:]
1484
1559
def test_knownFailure(self):
1485
1560
"""Self.knownFailure() should raise a KnownFailure exception."""
1486
1561
self.assertRaises(tests.KnownFailure, self.knownFailure, "A Failure")
1563
def test_open_bzrdir_safe_roots(self):
1564
# even a memory transport should fail to open when its url isn't
1566
# Manually set one up (TestCase doesn't and shouldn't provide magic
1568
transport_server = MemoryServer()
1569
transport_server.setUp()
1570
self.addCleanup(transport_server.tearDown)
1571
t = transport.get_transport(transport_server.get_url())
1572
bzrdir.BzrDir.create(t.base)
1573
self.assertRaises(errors.BzrError,
1574
bzrdir.BzrDir.open_from_transport, t)
1575
# But if we declare this as safe, we can open the bzrdir.
1576
self.permit_url(t.base)
1577
self._bzr_selftest_roots.append(t.base)
1578
bzrdir.BzrDir.open_from_transport(t)
1488
1580
def test_requireFeature_available(self):
1489
1581
"""self.requireFeature(available) is a no-op."""
1490
1582
class Available(tests.Feature):
1652
def test_start_server_registers_url(self):
1653
transport_server = MemoryServer()
1654
# A little strict, but unlikely to be changed soon.
1655
self.assertEqual([], self._bzr_selftest_roots)
1656
self.start_server(transport_server)
1657
self.assertSubset([transport_server.get_url()],
1658
self._bzr_selftest_roots)
1560
1660
def test_assert_list_raises_on_generator(self):
1561
1661
def generator_which_will_raise():
1562
1662
# This will not raise until after the first yield
1660
1760
self.assertEndsWith('foo', 'oo')
1661
1761
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1763
def test_assertEqualDiff(self):
1764
e = self.assertRaises(AssertionError,
1765
self.assertEqualDiff, '', '\n')
1766
self.assertEquals(str(e),
1767
# Don't blink ! The '+' applies to the second string
1768
'first string is missing a final newline.\n+ \n')
1769
e = self.assertRaises(AssertionError,
1770
self.assertEqualDiff, '\n', '')
1771
self.assertEquals(str(e),
1772
# Don't blink ! The '-' applies to the second string
1773
'second string is missing a final newline.\n- \n')
1776
class TestDeprecations(tests.TestCase):
1663
1778
def test_applyDeprecated_not_deprecated(self):
1664
1779
sample_object = ApplyDeprecatedHelper()
1665
1780
# calling an undeprecated callable raises an assertion
1742
1857
tree = self.make_branch_and_memory_tree('a')
1743
1858
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1746
class TestSFTPMakeBranchAndTree(test_sftp_transport.TestCaseWithSFTPServer):
1748
def test_make_tree_for_sftp_branch(self):
1749
"""Transports backed by local directories create local trees."""
1750
# NB: This is arguably a bug in the definition of make_branch_and_tree.
1860
def test_make_tree_for_local_vfs_backed_transport(self):
1861
# make_branch_and_tree has to use local branch and repositories
1862
# when the vfs transport and local disk are colocated, even if
1863
# a different transport is in use for url generation.
1864
from bzrlib.transport.fakevfat import FakeVFATServer
1865
self.transport_server = FakeVFATServer
1866
self.assertFalse(self.get_url('t1').startswith('file://'))
1751
1867
tree = self.make_branch_and_tree('t1')
1752
1868
base = tree.bzrdir.root_transport.base
1753
self.failIf(base.startswith('sftp'),
1754
'base %r is on sftp but should be local' % base)
1869
self.assertStartsWith(base, 'file://')
1755
1870
self.assertEquals(tree.bzrdir.root_transport,
1756
1871
tree.branch.bzrdir.root_transport)
1757
1872
self.assertEquals(tree.bzrdir.root_transport,
1817
1932
self.assertNotContainsRe("Test.b", output.getvalue())
1818
1933
self.assertLength(2, output.readlines())
1935
def test_lsprof_tests(self):
1936
self.requireFeature(test_lsprof.LSProfFeature)
1939
def __call__(test, result):
1941
def run(test, result):
1942
self.assertIsInstance(result, tests.ForwardingResult)
1943
calls.append("called")
1944
def countTestCases(self):
1946
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1947
self.assertLength(1, calls)
1820
1949
def test_random(self):
1821
1950
# test randomising by listing a number of tests.
1822
1951
output_123 = self.run_selftest(test_suite_factory=self.factory,
1915
2044
Attempts to run bzr from inside this class don't actually run it.
1917
We test how run_bzr actually invokes bzr in another location.
1918
Here we only need to test that it is run_bzr passes the right
1919
parameters to run_bzr.
2046
We test how run_bzr actually invokes bzr in another location. Here we
2047
only need to test that it passes the right parameters to run_bzr.
1921
2049
self.argv = list(argv)
1922
2050
self.retcode = retcode
1923
2051
self.encoding = encoding
1924
2052
self.stdin = stdin
1925
2053
self.working_dir = working_dir
1926
return self.out, self.err
2054
return self.retcode, self.out, self.err
1928
2056
def test_run_bzr_error(self):
1929
2057
self.out = "It sure does!\n"
1930
2058
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
1931
2059
self.assertEqual(['rocks'], self.argv)
1932
2060
self.assertEqual(34, self.retcode)
1933
self.assertEqual(out, 'It sure does!\n')
2061
self.assertEqual('It sure does!\n', out)
2062
self.assertEquals(out, self.out)
2063
self.assertEqual('', err)
2064
self.assertEquals(err, self.err)
1935
2066
def test_run_bzr_error_regexes(self):
1937
2068
self.err = "bzr: ERROR: foobarbaz is not versioned"
1938
2069
out, err = self.run_bzr_error(
1939
["bzr: ERROR: foobarbaz is not versioned"],
1940
['file-id', 'foobarbaz'])
2070
["bzr: ERROR: foobarbaz is not versioned"],
2071
['file-id', 'foobarbaz'])
1942
2073
def test_encoding(self):
1943
2074
"""Test that run_bzr passes encoding to _run_bzr_core"""
2157
2292
StubProcess(), '', allow_plugins=True)
2295
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2297
def test_finish_bzr_subprocess_with_error(self):
2298
"""finish_bzr_subprocess allows specification of the desired exit code.
2300
process = StubProcess(err="unknown command", retcode=3)
2301
result = self.finish_bzr_subprocess(process, retcode=3)
2302
self.assertEqual('', result[0])
2303
self.assertContainsRe(result[1], 'unknown command')
2305
def test_finish_bzr_subprocess_ignoring_retcode(self):
2306
"""finish_bzr_subprocess allows the exit code to be ignored."""
2307
process = StubProcess(err="unknown command", retcode=3)
2308
result = self.finish_bzr_subprocess(process, retcode=None)
2309
self.assertEqual('', result[0])
2310
self.assertContainsRe(result[1], 'unknown command')
2312
def test_finish_subprocess_with_unexpected_retcode(self):
2313
"""finish_bzr_subprocess raises self.failureException if the retcode is
2314
not the expected one.
2316
process = StubProcess(err="unknown command", retcode=3)
2317
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2160
2321
class _DontSpawnProcess(Exception):
2161
2322
"""A simple exception which just allows us to skip unnecessary steps"""
2240
2401
self.assertEqual(['foo', 'current'], chdirs)
2243
class TestBzrSubprocess(tests.TestCaseWithTransport):
2245
def test_start_and_stop_bzr_subprocess(self):
2246
"""We can start and perform other test actions while that process is
2249
process = self.start_bzr_subprocess(['--version'])
2250
result = self.finish_bzr_subprocess(process)
2251
self.assertContainsRe(result[0], 'is free software')
2252
self.assertEqual('', result[1])
2254
def test_start_and_stop_bzr_subprocess_with_error(self):
2255
"""finish_bzr_subprocess allows specification of the desired exit code.
2257
process = self.start_bzr_subprocess(['--versionn'])
2258
result = self.finish_bzr_subprocess(process, retcode=3)
2259
self.assertEqual('', result[0])
2260
self.assertContainsRe(result[1], 'unknown command')
2262
def test_start_and_stop_bzr_subprocess_ignoring_retcode(self):
2263
"""finish_bzr_subprocess allows the exit code to be ignored."""
2264
process = self.start_bzr_subprocess(['--versionn'])
2265
result = self.finish_bzr_subprocess(process, retcode=None)
2266
self.assertEqual('', result[0])
2267
self.assertContainsRe(result[1], 'unknown command')
2269
def test_start_and_stop_bzr_subprocess_with_unexpected_retcode(self):
2270
"""finish_bzr_subprocess raises self.failureException if the retcode is
2271
not the expected one.
2273
process = self.start_bzr_subprocess(['--versionn'])
2274
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2404
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2405
"""Tests that really need to do things with an external bzr."""
2277
2407
def test_start_and_stop_bzr_subprocess_send_signal(self):
2278
2408
"""finish_bzr_subprocess raises self.failureException if the retcode is
2279
2409
not the expected one.
2411
self.disable_missing_extensions_warning()
2281
2412
process = self.start_bzr_subprocess(['wait-until-signalled'],
2282
2413
skip_if_plan_to_signal=True)
2283
2414
self.assertEqual('running\n', process.stdout.readline())
2286
2417
self.assertEqual('', result[0])
2287
2418
self.assertEqual('bzr: interrupted\n', result[1])
2289
def test_start_and_stop_working_dir(self):
2290
cwd = osutils.getcwd()
2291
self.make_branch_and_tree('one')
2292
process = self.start_bzr_subprocess(['root'], working_dir='one')
2293
result = self.finish_bzr_subprocess(process, universal_newlines=True)
2294
self.assertEndsWith(result[0], 'one\n')
2295
self.assertEqual('', result[1])
2298
2421
class TestKnownFailure(tests.TestCase):
2549
2672
# Running bzr in blackbox mode, normal/expected/user errors should be
2550
2673
# caught in the regular way and turned into an error message plus exit
2552
out, err = self.run_bzr(["log", "/nonexistantpath"], retcode=3)
2675
transport_server = MemoryServer()
2676
transport_server.setUp()
2677
self.addCleanup(transport_server.tearDown)
2678
url = transport_server.get_url()
2679
self.permit_url(url)
2680
out, err = self.run_bzr(["log", "%s/nonexistantpath" % url], retcode=3)
2553
2681
self.assertEqual(out, '')
2554
2682
self.assertContainsRe(err,
2555
2683
'bzr: ERROR: Not a branch: ".*nonexistantpath/".\n')
2682
2810
class TestTestSuite(tests.TestCase):
2812
def test__test_suite_testmod_names(self):
2813
# Test that a plausible list of test module names are returned
2814
# by _test_suite_testmod_names.
2815
test_list = tests._test_suite_testmod_names()
2817
'bzrlib.tests.blackbox',
2818
'bzrlib.tests.per_transport',
2819
'bzrlib.tests.test_selftest',
2823
def test__test_suite_modules_to_doctest(self):
2824
# Test that a plausible list of modules to doctest is returned
2825
# by _test_suite_modules_to_doctest.
2826
test_list = tests._test_suite_modules_to_doctest()
2684
2832
def test_test_suite(self):
2685
# This test is slow - it loads the entire test suite to operate, so we
2686
# do a single test with one test in each category
2833
# test_suite() loads the entire test suite to operate. To avoid this
2834
# overhead, and yet still be confident that things are happening,
2835
# we temporarily replace two functions used by test_suite with
2836
# test doubles that supply a few sample tests to load, and check they
2839
def _test_suite_testmod_names():
2840
calls.append("testmod_names")
2842
'bzrlib.tests.blackbox.test_branch',
2843
'bzrlib.tests.per_transport',
2844
'bzrlib.tests.test_selftest',
2846
original_testmod_names = tests._test_suite_testmod_names
2847
def _test_suite_modules_to_doctest():
2848
calls.append("modules_to_doctest")
2849
return ['bzrlib.timestamp']
2850
orig_modules_to_doctest = tests._test_suite_modules_to_doctest
2851
def restore_names():
2852
tests._test_suite_testmod_names = original_testmod_names
2853
tests._test_suite_modules_to_doctest = orig_modules_to_doctest
2854
self.addCleanup(restore_names)
2855
tests._test_suite_testmod_names = _test_suite_testmod_names
2856
tests._test_suite_modules_to_doctest = _test_suite_modules_to_doctest
2857
expected_test_list = [
2688
2858
# testmod_names
2689
2859
'bzrlib.tests.blackbox.test_branch.TestBranch.test_branch',
2690
2860
('bzrlib.tests.per_transport.TransportTests'
2691
'.test_abspath(LocalURLServer)'),
2861
'.test_abspath(LocalTransport,LocalURLServer)'),
2692
2862
'bzrlib.tests.test_selftest.TestTestSuite.test_test_suite',
2693
2863
# modules_to_doctest
2694
2864
'bzrlib.timestamp.format_highres_date',
2695
2865
# plugins can't be tested that way since selftest may be run with
2698
suite = tests.test_suite(test_list)
2699
self.assertEquals(test_list, _test_ids(suite))
2868
suite = tests.test_suite()
2869
self.assertEqual(set(["testmod_names", "modules_to_doctest"]),
2871
self.assertSubset(expected_test_list, _test_ids(suite))
2701
2873
def test_test_suite_list_and_start(self):
2702
2874
# We cannot test this at the same time as the main load, because we want
2703
# to know that starting_with == None works. So a second full load is
2875
# to know that starting_with == None works. So a second load is
2876
# incurred - note that the starting_with parameter causes a partial load
2877
# rather than a full load so this test should be pretty quick.
2705
2878
test_list = ['bzrlib.tests.test_selftest.TestTestSuite.test_test_suite']
2706
2879
suite = tests.test_suite(test_list,
2707
2880
['bzrlib.tests.test_selftest.TestTestSuite'])
2853
3026
self.verbosity)
2854
3027
tests.run_suite(suite, runner_class=MyRunner, stream=StringIO())
2855
3028
self.assertLength(1, calls)
2857
def test_done(self):
2858
"""run_suite should call result.done()"""
2860
def one_more_call(): self.calls += 1
2861
def test_function():
2863
test = unittest.FunctionTestCase(test_function)
2864
class InstrumentedTestResult(tests.ExtendedTestResult):
2865
def done(self): one_more_call()
2866
class MyRunner(tests.TextTestRunner):
2867
def run(self, test):
2868
return InstrumentedTestResult(self.stream, self.descriptions,
2870
tests.run_suite(test, runner_class=MyRunner, stream=StringIO())
2871
self.assertEquals(1, self.calls)