350
393
'transport_readonly_server': 'b',
351
394
'transport_server': 'a',
352
395
'workingtree_format': formats[1]})],
356
class TestTreeScenarios(tests.TestCase):
358
def test_scenarios(self):
359
# the tree implementation scenario generator is meant to setup one
360
# instance for each working tree format, and one additional instance
361
# that will use the default wt format, but create a revision tree for
362
# the tests. this means that the wt ones should have the
363
# workingtree_to_test_tree attribute set to 'return_parameter' and the
364
# revision one set to revision_tree_from_workingtree.
366
from bzrlib.tests.per_tree import (
367
_dirstate_tree_from_workingtree,
399
class TestTreeProviderAdapter(TestCase):
400
"""Test the setup of tree_implementation tests."""
402
def test_adapted_tests(self):
403
# the tree implementation adapter is meant to setup one instance for
404
# each working tree format, and one additional instance that will
405
# use the default wt format, but create a revision tree for the tests.
406
# this means that the wt ones should have the workingtree_to_test_tree
407
# attribute set to 'return_parameter' and the revision one set to
408
# revision_tree_from_workingtree.
410
from bzrlib.tests.tree_implementations import (
411
TreeTestProviderAdapter,
371
412
return_parameter,
372
413
revision_tree_from_workingtree
415
input_test = TestTreeProviderAdapter(
416
"test_adapted_tests")
376
419
formats = [workingtree.WorkingTreeFormat2(),
377
420
workingtree.WorkingTreeFormat3(),]
378
scenarios = make_scenarios(server1, server2, formats)
379
self.assertEqual(7, len(scenarios))
380
default_wt_format = workingtree.WorkingTreeFormat4._default_format
381
wt4_format = workingtree.WorkingTreeFormat4()
382
wt5_format = workingtree.WorkingTreeFormat5()
383
expected_scenarios = [
384
('WorkingTreeFormat2',
385
{'bzrdir_format': formats[0]._matchingbzrdir,
386
'transport_readonly_server': 'b',
387
'transport_server': 'a',
388
'workingtree_format': formats[0],
389
'_workingtree_to_test_tree': return_parameter,
391
('WorkingTreeFormat3',
392
{'bzrdir_format': formats[1]._matchingbzrdir,
393
'transport_readonly_server': 'b',
394
'transport_server': 'a',
395
'workingtree_format': formats[1],
396
'_workingtree_to_test_tree': return_parameter,
399
{'_workingtree_to_test_tree': revision_tree_from_workingtree,
400
'bzrdir_format': default_wt_format._matchingbzrdir,
401
'transport_readonly_server': 'b',
402
'transport_server': 'a',
403
'workingtree_format': default_wt_format,
405
('DirStateRevisionTree,WT4',
406
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
407
'bzrdir_format': wt4_format._matchingbzrdir,
408
'transport_readonly_server': 'b',
409
'transport_server': 'a',
410
'workingtree_format': wt4_format,
412
('DirStateRevisionTree,WT5',
413
{'_workingtree_to_test_tree': _dirstate_tree_from_workingtree,
414
'bzrdir_format': wt5_format._matchingbzrdir,
415
'transport_readonly_server': 'b',
416
'transport_server': 'a',
417
'workingtree_format': wt5_format,
420
{'_workingtree_to_test_tree': preview_tree_pre,
421
'bzrdir_format': default_wt_format._matchingbzrdir,
422
'transport_readonly_server': 'b',
423
'transport_server': 'a',
424
'workingtree_format': default_wt_format}),
426
{'_workingtree_to_test_tree': preview_tree_post,
427
'bzrdir_format': default_wt_format._matchingbzrdir,
428
'transport_readonly_server': 'b',
429
'transport_server': 'a',
430
'workingtree_format': default_wt_format}),
432
self.assertEqual(expected_scenarios, scenarios)
435
class TestInterTreeScenarios(tests.TestCase):
421
adapter = TreeTestProviderAdapter(server1, server2, formats)
422
suite = adapter.adapt(input_test)
423
tests = list(iter(suite))
424
# XXX We should not have tests fail as we add more scenarios
426
self.assertEqual(7, len(tests))
427
# this must match the default format setp up in
428
# TreeTestProviderAdapter.adapt
429
default_format = workingtree.WorkingTreeFormat3
430
self.assertEqual(tests[0].workingtree_format, formats[0])
431
self.assertEqual(tests[0].bzrdir_format, formats[0]._matchingbzrdir)
432
self.assertEqual(tests[0].transport_server, server1)
433
self.assertEqual(tests[0].transport_readonly_server, server2)
434
self.assertEqual(tests[0]._workingtree_to_test_tree, return_parameter)
435
self.assertEqual(tests[1].workingtree_format, formats[1])
436
self.assertEqual(tests[1].bzrdir_format, formats[1]._matchingbzrdir)
437
self.assertEqual(tests[1].transport_server, server1)
438
self.assertEqual(tests[1].transport_readonly_server, server2)
439
self.assertEqual(tests[1]._workingtree_to_test_tree, return_parameter)
440
self.assertIsInstance(tests[2].workingtree_format, default_format)
441
#self.assertEqual(tests[2].bzrdir_format,
442
# default_format._matchingbzrdir)
443
self.assertEqual(tests[2].transport_server, server1)
444
self.assertEqual(tests[2].transport_readonly_server, server2)
445
self.assertEqual(tests[2]._workingtree_to_test_tree,
446
revision_tree_from_workingtree)
449
class TestInterTreeProviderAdapter(TestCase):
436
450
"""A group of tests that test the InterTreeTestAdapter."""
438
def test_scenarios(self):
452
def test_adapted_tests(self):
439
453
# check that constructor parameters are passed through to the adapted
441
455
# for InterTree tests we want the machinery to bring up two trees in
1194
def _patch_get_bzr_source_tree(self):
1195
# Reading from the actual source tree breaks isolation, but we don't
1196
# want to assume that thats *all* that would happen.
1197
self._get_source_tree_calls = []
1199
self._get_source_tree_calls.append("called")
1201
self.overrideAttr(bzrlib.version, '_get_bzr_source_tree', new_get)
1203
1208
def test_bench_history(self):
1204
# tests that the running the benchmark passes bench_history into
1205
# the test result object. We can tell that happens if
1206
# _get_bzr_source_tree is called.
1207
self._patch_get_bzr_source_tree()
1209
# tests that the running the benchmark produces a history file
1210
# containing a timestamp and the revision id of the bzrlib source which
1212
workingtree = _get_bzr_source_tree()
1208
1213
test = TestRunner('dummy_test')
1209
1214
output = StringIO()
1210
runner = tests.TextTestRunner(stream=self._log_file,
1211
bench_history=output)
1215
runner = TextTestRunner(stream=self._log_file, bench_history=output)
1212
1216
result = self.run_test_runner(runner, test)
1213
1217
output_string = output.getvalue()
1214
1218
self.assertContainsRe(output_string, "--date [0-9.]+")
1215
self.assertLength(1, self._get_source_tree_calls)
1217
def test_startTestRun(self):
1218
"""run should call result.startTestRun()"""
1220
class LoggingDecorator(tests.ForwardingResult):
1221
def startTestRun(self):
1222
tests.ForwardingResult.startTestRun(self)
1223
calls.append('startTestRun')
1224
test = unittest.FunctionTestCase(lambda:None)
1226
runner = tests.TextTestRunner(stream=stream,
1227
result_decorators=[LoggingDecorator])
1228
result = self.run_test_runner(runner, test)
1229
self.assertLength(1, calls)
1231
def test_stopTestRun(self):
1232
"""run should call result.stopTestRun()"""
1234
class LoggingDecorator(tests.ForwardingResult):
1235
def stopTestRun(self):
1236
tests.ForwardingResult.stopTestRun(self)
1237
calls.append('stopTestRun')
1238
test = unittest.FunctionTestCase(lambda:None)
1240
runner = tests.TextTestRunner(stream=stream,
1241
result_decorators=[LoggingDecorator])
1242
result = self.run_test_runner(runner, test)
1243
self.assertLength(1, calls)
1246
class SampleTestCase(tests.TestCase):
1219
if workingtree is not None:
1220
revision_id = workingtree.get_parent_ids()[0]
1221
self.assertEndsWith(output_string.rstrip(), revision_id)
1223
def assertLogDeleted(self, test):
1224
log = test._get_log()
1225
self.assertEqual("DELETED log file to reduce memory footprint", log)
1226
self.assertEqual('', test._log_contents)
1227
self.assertIs(None, test._log_file_name)
1229
def test_success_log_deleted(self):
1230
"""Successful tests have their log deleted"""
1232
class LogTester(TestCase):
1234
def test_success(self):
1235
self.log('this will be removed\n')
1237
sio = cStringIO.StringIO()
1238
runner = TextTestRunner(stream=sio)
1239
test = LogTester('test_success')
1240
result = self.run_test_runner(runner, test)
1242
self.assertLogDeleted(test)
1244
def test_skipped_log_deleted(self):
1245
"""Skipped tests have their log deleted"""
1247
class LogTester(TestCase):
1249
def test_skipped(self):
1250
self.log('this will be removed\n')
1251
raise tests.TestSkipped()
1253
sio = cStringIO.StringIO()
1254
runner = TextTestRunner(stream=sio)
1255
test = LogTester('test_skipped')
1256
result = self.run_test_runner(runner, test)
1258
self.assertLogDeleted(test)
1260
def test_not_aplicable_log_deleted(self):
1261
"""Not applicable tests have their log deleted"""
1263
class LogTester(TestCase):
1265
def test_not_applicable(self):
1266
self.log('this will be removed\n')
1267
raise tests.TestNotApplicable()
1269
sio = cStringIO.StringIO()
1270
runner = TextTestRunner(stream=sio)
1271
test = LogTester('test_not_applicable')
1272
result = self.run_test_runner(runner, test)
1274
self.assertLogDeleted(test)
1276
def test_known_failure_log_deleted(self):
1277
"""Know failure tests have their log deleted"""
1279
class LogTester(TestCase):
1281
def test_known_failure(self):
1282
self.log('this will be removed\n')
1283
raise tests.KnownFailure()
1285
sio = cStringIO.StringIO()
1286
runner = TextTestRunner(stream=sio)
1287
test = LogTester('test_known_failure')
1288
result = self.run_test_runner(runner, test)
1290
self.assertLogDeleted(test)
1292
def test_fail_log_kept(self):
1293
"""Failed tests have their log kept"""
1295
class LogTester(TestCase):
1297
def test_fail(self):
1298
self.log('this will be kept\n')
1299
self.fail('this test fails')
1301
sio = cStringIO.StringIO()
1302
runner = TextTestRunner(stream=sio)
1303
test = LogTester('test_fail')
1304
result = self.run_test_runner(runner, test)
1306
text = sio.getvalue()
1307
self.assertContainsRe(text, 'this will be kept')
1308
self.assertContainsRe(text, 'this test fails')
1310
log = test._get_log()
1311
self.assertContainsRe(log, 'this will be kept')
1312
self.assertEqual(log, test._log_contents)
1314
def test_error_log_kept(self):
1315
"""Tests with errors have their log kept"""
1317
class LogTester(TestCase):
1319
def test_error(self):
1320
self.log('this will be kept\n')
1321
raise ValueError('random exception raised')
1323
sio = cStringIO.StringIO()
1324
runner = TextTestRunner(stream=sio)
1325
test = LogTester('test_error')
1326
result = self.run_test_runner(runner, test)
1328
text = sio.getvalue()
1329
self.assertContainsRe(text, 'this will be kept')
1330
self.assertContainsRe(text, 'random exception raised')
1332
log = test._get_log()
1333
self.assertContainsRe(log, 'this will be kept')
1334
self.assertEqual(log, test._log_contents)
1337
class SampleTestCase(TestCase):
1248
1339
def _test_pass(self):
1678
1624
def sample_normal_method(self):
1679
1625
"""A undeprecated method."""
1681
@deprecated_method(deprecated_in((0, 10, 0)))
1627
@symbol_versioning.deprecated_method(zero_ten)
1682
1628
def sample_nested_deprecation(self):
1683
1629
return sample_deprecated_function()
1686
class TestExtraAssertions(tests.TestCase):
1632
class TestExtraAssertions(TestCase):
1687
1633
"""Tests for new test assertions in bzrlib test suite"""
1689
1635
def test_assert_isinstance(self):
1690
1636
self.assertIsInstance(2, int)
1691
1637
self.assertIsInstance(u'', basestring)
1692
e = self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1693
self.assertEquals(str(e),
1694
"None is an instance of <type 'NoneType'> rather than <type 'int'>")
1638
self.assertRaises(AssertionError, self.assertIsInstance, None, int)
1695
1639
self.assertRaises(AssertionError, self.assertIsInstance, 23.3, int)
1696
e = self.assertRaises(AssertionError,
1697
self.assertIsInstance, None, int, "it's just not")
1698
self.assertEquals(str(e),
1699
"None is an instance of <type 'NoneType'> rather than <type 'int'>"
1702
1641
def test_assertEndsWith(self):
1703
1642
self.assertEndsWith('foo', 'oo')
1704
1643
self.assertRaises(AssertionError, self.assertEndsWith, 'o', 'oo')
1706
def test_assertEqualDiff(self):
1707
e = self.assertRaises(AssertionError,
1708
self.assertEqualDiff, '', '\n')
1709
self.assertEquals(str(e),
1710
# Don't blink ! The '+' applies to the second string
1711
'first string is missing a final newline.\n+ \n')
1712
e = self.assertRaises(AssertionError,
1713
self.assertEqualDiff, '\n', '')
1714
self.assertEquals(str(e),
1715
# Don't blink ! The '-' applies to the second string
1716
'second string is missing a final newline.\n- \n')
1719
class TestDeprecations(tests.TestCase):
1721
1645
def test_applyDeprecated_not_deprecated(self):
1722
1646
sample_object = ApplyDeprecatedHelper()
1723
1647
# calling an undeprecated callable raises an assertion
1724
self.assertRaises(AssertionError, self.applyDeprecated,
1725
deprecated_in((0, 11, 0)),
1648
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1726
1649
sample_object.sample_normal_method)
1727
self.assertRaises(AssertionError, self.applyDeprecated,
1728
deprecated_in((0, 11, 0)),
1650
self.assertRaises(AssertionError, self.applyDeprecated, zero_eleven,
1729
1651
sample_undeprecated_function, "a param value")
1730
1652
# calling a deprecated callable (function or method) with the wrong
1731
1653
# expected deprecation fails.
1732
self.assertRaises(AssertionError, self.applyDeprecated,
1733
deprecated_in((0, 10, 0)),
1654
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1734
1655
sample_object.sample_deprecated_method, "a param value")
1735
self.assertRaises(AssertionError, self.applyDeprecated,
1736
deprecated_in((0, 10, 0)),
1656
self.assertRaises(AssertionError, self.applyDeprecated, zero_ten,
1737
1657
sample_deprecated_function)
1738
1658
# calling a deprecated callable (function or method) with the right
1739
1659
# expected deprecation returns the functions result.
1740
self.assertEqual("a param value",
1741
self.applyDeprecated(deprecated_in((0, 11, 0)),
1660
self.assertEqual("a param value", self.applyDeprecated(zero_eleven,
1742
1661
sample_object.sample_deprecated_method, "a param value"))
1743
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 11, 0)),
1662
self.assertEqual(2, self.applyDeprecated(zero_eleven,
1744
1663
sample_deprecated_function))
1745
1664
# calling a nested deprecation with the wrong deprecation version
1746
# fails even if a deeper nested function was deprecated with the
1665
# fails even if a deeper nested function was deprecated with the
1747
1666
# supplied version.
1748
1667
self.assertRaises(AssertionError, self.applyDeprecated,
1749
deprecated_in((0, 11, 0)), sample_object.sample_nested_deprecation)
1668
zero_eleven, sample_object.sample_nested_deprecation)
1750
1669
# calling a nested deprecation with the right deprecation value
1751
1670
# returns the calls result.
1752
self.assertEqual(2, self.applyDeprecated(deprecated_in((0, 10, 0)),
1671
self.assertEqual(2, self.applyDeprecated(zero_ten,
1753
1672
sample_object.sample_nested_deprecation))
1755
1674
def test_callDeprecated(self):
1756
1675
def testfunc(be_deprecated, result=None):
1757
1676
if be_deprecated is True:
1758
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1677
symbol_versioning.warn('i am deprecated', DeprecationWarning,
1761
1680
result = self.callDeprecated(['i am deprecated'], testfunc, True)
1800
1719
tree = self.make_branch_and_memory_tree('a')
1801
1720
self.assertIsInstance(tree, bzrlib.memorytree.MemoryTree)
1803
def test_make_tree_for_local_vfs_backed_transport(self):
1804
# make_branch_and_tree has to use local branch and repositories
1805
# when the vfs transport and local disk are colocated, even if
1806
# a different transport is in use for url generation.
1807
self.transport_server = test_server.FakeVFATServer
1808
self.assertFalse(self.get_url('t1').startswith('file://'))
1723
class TestSFTPMakeBranchAndTree(TestCaseWithSFTPServer):
1725
def test_make_tree_for_sftp_branch(self):
1726
"""Transports backed by local directories create local trees."""
1809
1728
tree = self.make_branch_and_tree('t1')
1810
1729
base = tree.bzrdir.root_transport.base
1811
self.assertStartsWith(base, 'file://')
1730
self.failIf(base.startswith('sftp'),
1731
'base %r is on sftp but should be local' % base)
1812
1732
self.assertEquals(tree.bzrdir.root_transport,
1813
1733
tree.branch.bzrdir.root_transport)
1814
1734
self.assertEquals(tree.bzrdir.root_transport,
1815
1735
tree.branch.repository.bzrdir.root_transport)
1818
class SelfTestHelper:
1820
def run_selftest(self, **kwargs):
1821
"""Run selftest returning its output."""
1823
old_transport = bzrlib.tests.default_transport
1824
old_root = tests.TestCaseWithMemoryTransport.TEST_ROOT
1825
tests.TestCaseWithMemoryTransport.TEST_ROOT = None
1827
self.assertEqual(True, tests.selftest(stream=output, **kwargs))
1829
bzrlib.tests.default_transport = old_transport
1830
tests.TestCaseWithMemoryTransport.TEST_ROOT = old_root
1835
class TestSelftest(tests.TestCase, SelfTestHelper):
1738
class TestSelftest(TestCase):
1836
1739
"""Tests of bzrlib.tests.selftest."""
1838
1741
def test_selftest_benchmark_parameter_invokes_test_suite__benchmark__(self):
1839
1742
factory_called = []
1841
1744
factory_called.append(True)
1842
return TestUtil.TestSuite()
1843
1746
out = StringIO()
1844
1747
err = StringIO()
1845
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1748
self.apply_redirected(out, err, None, bzrlib.tests.selftest,
1846
1749
test_suite_factory=factory)
1847
1750
self.assertEqual([True], factory_called)
1850
"""A test suite factory."""
1851
class Test(tests.TestCase):
1858
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1860
def test_list_only(self):
1861
output = self.run_selftest(test_suite_factory=self.factory,
1863
self.assertEqual(3, len(output.readlines()))
1865
def test_list_only_filtered(self):
1866
output = self.run_selftest(test_suite_factory=self.factory,
1867
list_only=True, pattern="Test.b")
1868
self.assertEndsWith(output.getvalue(), "Test.b\n")
1869
self.assertLength(1, output.readlines())
1871
def test_list_only_excludes(self):
1872
output = self.run_selftest(test_suite_factory=self.factory,
1873
list_only=True, exclude_pattern="Test.b")
1874
self.assertNotContainsRe("Test.b", output.getvalue())
1875
self.assertLength(2, output.readlines())
1877
def test_lsprof_tests(self):
1878
self.requireFeature(test_lsprof.LSProfFeature)
1881
def __call__(test, result):
1883
def run(test, result):
1884
self.assertIsInstance(result, tests.ForwardingResult)
1885
calls.append("called")
1886
def countTestCases(self):
1888
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1889
self.assertLength(1, calls)
1891
def test_random(self):
1892
# test randomising by listing a number of tests.
1893
output_123 = self.run_selftest(test_suite_factory=self.factory,
1894
list_only=True, random_seed="123")
1895
output_234 = self.run_selftest(test_suite_factory=self.factory,
1896
list_only=True, random_seed="234")
1897
self.assertNotEqual(output_123, output_234)
1898
# "Randominzing test order..\n\n
1899
self.assertLength(5, output_123.readlines())
1900
self.assertLength(5, output_234.readlines())
1902
def test_random_reuse_is_same_order(self):
1903
# test randomising by listing a number of tests.
1904
expected = self.run_selftest(test_suite_factory=self.factory,
1905
list_only=True, random_seed="123")
1906
repeated = self.run_selftest(test_suite_factory=self.factory,
1907
list_only=True, random_seed="123")
1908
self.assertEqual(expected.getvalue(), repeated.getvalue())
1910
def test_runner_class(self):
1911
self.requireFeature(features.subunit)
1912
from subunit import ProtocolTestCase
1913
stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1914
test_suite_factory=self.factory)
1915
test = ProtocolTestCase(stream)
1916
result = unittest.TestResult()
1918
self.assertEqual(3, result.testsRun)
1920
def test_starting_with_single_argument(self):
1921
output = self.run_selftest(test_suite_factory=self.factory,
1922
starting_with=['bzrlib.tests.test_selftest.Test.a'],
1924
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1927
def test_starting_with_multiple_argument(self):
1928
output = self.run_selftest(test_suite_factory=self.factory,
1929
starting_with=['bzrlib.tests.test_selftest.Test.a',
1930
'bzrlib.tests.test_selftest.Test.b'],
1932
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1933
'bzrlib.tests.test_selftest.Test.b\n',
1936
def check_transport_set(self, transport_server):
1937
captured_transport = []
1938
def seen_transport(a_transport):
1939
captured_transport.append(a_transport)
1940
class Capture(tests.TestCase):
1942
seen_transport(bzrlib.tests.default_transport)
1944
return TestUtil.TestSuite([Capture("a")])
1945
self.run_selftest(transport=transport_server, test_suite_factory=factory)
1946
self.assertEqual(transport_server, captured_transport[0])
1948
def test_transport_sftp(self):
1949
self.requireFeature(features.paramiko)
1950
from bzrlib.tests import stub_sftp
1951
self.check_transport_set(stub_sftp.SFTPAbsoluteServer)
1953
def test_transport_memory(self):
1954
self.check_transport_set(memory.MemoryServer)
1957
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
1958
# Does IO: reads test.list
1960
def test_load_list(self):
1961
# Provide a list with one test - this test.
1962
test_id_line = '%s\n' % self.id()
1963
self.build_tree_contents([('test.list', test_id_line)])
1964
# And generate a list of the tests in the suite.
1965
stream = self.run_selftest(load_list='test.list', list_only=True)
1966
self.assertEqual(test_id_line, stream.getvalue())
1968
def test_load_unknown(self):
1969
# Provide a list with one test - this test.
1970
# And generate a list of the tests in the suite.
1971
err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
1972
load_list='missing file name', list_only=True)
1975
class TestRunBzr(tests.TestCase):
1980
def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
1982
"""Override _run_bzr_core to test how it is invoked by run_bzr.
1984
Attempts to run bzr from inside this class don't actually run it.
1986
We test how run_bzr actually invokes bzr in another location. Here we
1987
only need to test that it passes the right parameters to run_bzr.
1989
self.argv = list(argv)
1990
self.retcode = retcode
1991
self.encoding = encoding
1993
self.working_dir = working_dir
1994
return self.retcode, self.out, self.err
1996
def test_run_bzr_error(self):
1997
self.out = "It sure does!\n"
1998
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
1999
self.assertEqual(['rocks'], self.argv)
2000
self.assertEqual(34, self.retcode)
2001
self.assertEqual('It sure does!\n', out)
2002
self.assertEquals(out, self.out)
2003
self.assertEqual('', err)
2004
self.assertEquals(err, self.err)
2006
def test_run_bzr_error_regexes(self):
2008
self.err = "bzr: ERROR: foobarbaz is not versioned"
2009
out, err = self.run_bzr_error(
2010
["bzr: ERROR: foobarbaz is not versioned"],
2011
['file-id', 'foobarbaz'])
2013
def test_encoding(self):
2014
"""Test that run_bzr passes encoding to _run_bzr_core"""
2015
self.run_bzr('foo bar')
2016
self.assertEqual(None, self.encoding)
2017
self.assertEqual(['foo', 'bar'], self.argv)
2019
self.run_bzr('foo bar', encoding='baz')
2020
self.assertEqual('baz', self.encoding)
2021
self.assertEqual(['foo', 'bar'], self.argv)
2023
def test_retcode(self):
2024
"""Test that run_bzr passes retcode to _run_bzr_core"""
2025
# Default is retcode == 0
2026
self.run_bzr('foo bar')
2027
self.assertEqual(0, self.retcode)
2028
self.assertEqual(['foo', 'bar'], self.argv)
2030
self.run_bzr('foo bar', retcode=1)
2031
self.assertEqual(1, self.retcode)
2032
self.assertEqual(['foo', 'bar'], self.argv)
2034
self.run_bzr('foo bar', retcode=None)
2035
self.assertEqual(None, self.retcode)
2036
self.assertEqual(['foo', 'bar'], self.argv)
2038
self.run_bzr(['foo', 'bar'], retcode=3)
2039
self.assertEqual(3, self.retcode)
2040
self.assertEqual(['foo', 'bar'], self.argv)
2042
def test_stdin(self):
2043
# test that the stdin keyword to run_bzr is passed through to
2044
# _run_bzr_core as-is. We do this by overriding
2045
# _run_bzr_core in this class, and then calling run_bzr,
2046
# which is a convenience function for _run_bzr_core, so
2048
self.run_bzr('foo bar', stdin='gam')
2049
self.assertEqual('gam', self.stdin)
2050
self.assertEqual(['foo', 'bar'], self.argv)
2052
self.run_bzr('foo bar', stdin='zippy')
2053
self.assertEqual('zippy', self.stdin)
2054
self.assertEqual(['foo', 'bar'], self.argv)
2056
def test_working_dir(self):
2057
"""Test that run_bzr passes working_dir to _run_bzr_core"""
2058
self.run_bzr('foo bar')
2059
self.assertEqual(None, self.working_dir)
2060
self.assertEqual(['foo', 'bar'], self.argv)
2062
self.run_bzr('foo bar', working_dir='baz')
2063
self.assertEqual('baz', self.working_dir)
2064
self.assertEqual(['foo', 'bar'], self.argv)
2066
def test_reject_extra_keyword_arguments(self):
2067
self.assertRaises(TypeError, self.run_bzr, "foo bar",
2068
error_regex=['error message'])
2071
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2072
# Does IO when testing the working_dir parameter.
2074
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2075
a_callable=None, *args, **kwargs):
2077
self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2078
self.factory = bzrlib.ui.ui_factory
2079
self.working_dir = osutils.getcwd()
2080
stdout.write('foo\n')
2081
stderr.write('bar\n')
2084
def test_stdin(self):
2085
# test that the stdin keyword to _run_bzr_core is passed through to
2086
# apply_redirected as a StringIO. We do this by overriding
2087
# apply_redirected in this class, and then calling _run_bzr_core,
2088
# which calls apply_redirected.
2089
self.run_bzr(['foo', 'bar'], stdin='gam')
2090
self.assertEqual('gam', self.stdin.read())
2091
self.assertTrue(self.stdin is self.factory_stdin)
2092
self.run_bzr(['foo', 'bar'], stdin='zippy')
2093
self.assertEqual('zippy', self.stdin.read())
2094
self.assertTrue(self.stdin is self.factory_stdin)
2096
def test_ui_factory(self):
2097
# each invocation of self.run_bzr should get its
2098
# own UI factory, which is an instance of TestUIFactory,
2099
# with stdin, stdout and stderr attached to the stdin,
2100
# stdout and stderr of the invoked run_bzr
2101
current_factory = bzrlib.ui.ui_factory
2102
self.run_bzr(['foo'])
2103
self.failIf(current_factory is self.factory)
2104
self.assertNotEqual(sys.stdout, self.factory.stdout)
2105
self.assertNotEqual(sys.stderr, self.factory.stderr)
2106
self.assertEqual('foo\n', self.factory.stdout.getvalue())
2107
self.assertEqual('bar\n', self.factory.stderr.getvalue())
2108
self.assertIsInstance(self.factory, tests.TestUIFactory)
2110
def test_working_dir(self):
2111
self.build_tree(['one/', 'two/'])
2112
cwd = osutils.getcwd()
2114
# Default is to work in the current directory
2115
self.run_bzr(['foo', 'bar'])
2116
self.assertEqual(cwd, self.working_dir)
2118
self.run_bzr(['foo', 'bar'], working_dir=None)
2119
self.assertEqual(cwd, self.working_dir)
2121
# The function should be run in the alternative directory
2122
# but afterwards the current working dir shouldn't be changed
2123
self.run_bzr(['foo', 'bar'], working_dir='one')
2124
self.assertNotEqual(cwd, self.working_dir)
2125
self.assertEndsWith(self.working_dir, 'one')
2126
self.assertEqual(cwd, osutils.getcwd())
2128
self.run_bzr(['foo', 'bar'], working_dir='two')
2129
self.assertNotEqual(cwd, self.working_dir)
2130
self.assertEndsWith(self.working_dir, 'two')
2131
self.assertEqual(cwd, osutils.getcwd())
2134
class StubProcess(object):
2135
"""A stub process for testing run_bzr_subprocess."""
2137
def __init__(self, out="", err="", retcode=0):
2140
self.returncode = retcode
2142
def communicate(self):
2143
return self.out, self.err
2146
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2147
"""Base class for tests testing how we might run bzr."""
2150
tests.TestCaseWithTransport.setUp(self)
2151
self.subprocess_calls = []
2153
def start_bzr_subprocess(self, process_args, env_changes=None,
2154
skip_if_plan_to_signal=False,
2156
allow_plugins=False):
2157
"""capture what run_bzr_subprocess tries to do."""
2158
self.subprocess_calls.append({'process_args':process_args,
2159
'env_changes':env_changes,
2160
'skip_if_plan_to_signal':skip_if_plan_to_signal,
2161
'working_dir':working_dir, 'allow_plugins':allow_plugins})
2162
return self.next_subprocess
2165
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2167
def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2168
"""Run run_bzr_subprocess with args and kwargs using a stubbed process.
2170
Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2171
that will return static results. This assertion method populates those
2172
results and also checks the arguments run_bzr_subprocess generates.
2174
self.next_subprocess = process
2176
result = self.run_bzr_subprocess(*args, **kwargs)
2178
self.next_subprocess = None
2179
for key, expected in expected_args.iteritems():
2180
self.assertEqual(expected, self.subprocess_calls[-1][key])
1753
class TestKnownFailure(TestCase):
1755
def test_known_failure(self):
1756
"""Check that KnownFailure is defined appropriately."""
1757
# a KnownFailure is an assertion error for compatability with unaware
1759
self.assertIsInstance(KnownFailure(""), AssertionError)
1761
def test_expect_failure(self):
1763
self.expectFailure("Doomed to failure", self.assertTrue, False)
1764
except KnownFailure, e:
1765
self.assertEqual('Doomed to failure', e.args[0])
1767
self.expectFailure("Doomed to failure", self.assertTrue, True)
1768
except AssertionError, e:
1769
self.assertEqual('Unexpected success. Should have failed:'
1770
' Doomed to failure', e.args[0])
2183
self.next_subprocess = None
2184
for key, expected in expected_args.iteritems():
2185
self.assertEqual(expected, self.subprocess_calls[-1][key])
2188
def test_run_bzr_subprocess(self):
2189
"""The run_bzr_helper_external command behaves nicely."""
2190
self.assertRunBzrSubprocess({'process_args':['--version']},
2191
StubProcess(), '--version')
2192
self.assertRunBzrSubprocess({'process_args':['--version']},
2193
StubProcess(), ['--version'])
2194
# retcode=None disables retcode checking
2195
result = self.assertRunBzrSubprocess({},
2196
StubProcess(retcode=3), '--version', retcode=None)
2197
result = self.assertRunBzrSubprocess({},
2198
StubProcess(out="is free software"), '--version')
2199
self.assertContainsRe(result[0], 'is free software')
2200
# Running a subcommand that is missing errors
2201
self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2202
{'process_args':['--versionn']}, StubProcess(retcode=3),
2204
# Unless it is told to expect the error from the subprocess
2205
result = self.assertRunBzrSubprocess({},
2206
StubProcess(retcode=3), '--versionn', retcode=3)
2207
# Or to ignore retcode checking
2208
result = self.assertRunBzrSubprocess({},
2209
StubProcess(err="unknown command", retcode=3), '--versionn',
2211
self.assertContainsRe(result[1], 'unknown command')
2213
def test_env_change_passes_through(self):
2214
self.assertRunBzrSubprocess(
2215
{'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2217
env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2219
def test_no_working_dir_passed_as_None(self):
2220
self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2222
def test_no_working_dir_passed_through(self):
2223
self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2226
def test_run_bzr_subprocess_no_plugins(self):
2227
self.assertRunBzrSubprocess({'allow_plugins': False},
2230
def test_allow_plugins(self):
2231
self.assertRunBzrSubprocess({'allow_plugins': True},
2232
StubProcess(), '', allow_plugins=True)
2235
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2237
def test_finish_bzr_subprocess_with_error(self):
2238
"""finish_bzr_subprocess allows specification of the desired exit code.
2240
process = StubProcess(err="unknown command", retcode=3)
2241
result = self.finish_bzr_subprocess(process, retcode=3)
2242
self.assertEqual('', result[0])
2243
self.assertContainsRe(result[1], 'unknown command')
2245
def test_finish_bzr_subprocess_ignoring_retcode(self):
2246
"""finish_bzr_subprocess allows the exit code to be ignored."""
2247
process = StubProcess(err="unknown command", retcode=3)
2248
result = self.finish_bzr_subprocess(process, retcode=None)
2249
self.assertEqual('', result[0])
2250
self.assertContainsRe(result[1], 'unknown command')
2252
def test_finish_subprocess_with_unexpected_retcode(self):
2253
"""finish_bzr_subprocess raises self.failureException if the retcode is
2254
not the expected one.
2256
process = StubProcess(err="unknown command", retcode=3)
2257
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2261
class _DontSpawnProcess(Exception):
2262
"""A simple exception which just allows us to skip unnecessary steps"""
2265
class TestStartBzrSubProcess(tests.TestCase):
2267
def check_popen_state(self):
2268
"""Replace to make assertions when popen is called."""
2270
def _popen(self, *args, **kwargs):
2271
"""Record the command that is run, so that we can ensure it is correct"""
2272
self.check_popen_state()
2273
self._popen_args = args
2274
self._popen_kwargs = kwargs
2275
raise _DontSpawnProcess()
2277
def test_run_bzr_subprocess_no_plugins(self):
2278
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2279
command = self._popen_args[0]
2280
self.assertEqual(sys.executable, command[0])
2281
self.assertEqual(self.get_bzr_path(), command[1])
2282
self.assertEqual(['--no-plugins'], command[2:])
2284
def test_allow_plugins(self):
2285
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2287
command = self._popen_args[0]
2288
self.assertEqual([], command[2:])
2290
def test_set_env(self):
2291
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2293
def check_environment():
2294
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2295
self.check_popen_state = check_environment
2296
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2297
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2298
# not set in theparent
2299
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2301
def test_run_bzr_subprocess_env_del(self):
2302
"""run_bzr_subprocess can remove environment variables too."""
2303
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2304
def check_environment():
2305
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2306
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2307
self.check_popen_state = check_environment
2308
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2309
env_changes={'EXISTANT_ENV_VAR':None})
2310
# Still set in parent
2311
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2312
del os.environ['EXISTANT_ENV_VAR']
2314
def test_env_del_missing(self):
2315
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2316
def check_environment():
2317
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2318
self.check_popen_state = check_environment
2319
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2320
env_changes={'NON_EXISTANT_ENV_VAR':None})
2322
def test_working_dir(self):
2323
"""Test that we can specify the working dir for the child"""
2324
orig_getcwd = osutils.getcwd
2325
orig_chdir = os.chdir
2333
osutils.getcwd = getcwd
2335
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2338
osutils.getcwd = orig_getcwd
2340
os.chdir = orig_chdir
2341
self.assertEqual(['foo', 'current'], chdirs)
2343
def test_get_bzr_path_with_cwd_bzrlib(self):
2344
self.get_source_path = lambda: ""
2345
self.overrideAttr(os.path, "isfile", lambda path: True)
2346
self.assertEqual(self.get_bzr_path(), "bzr")
2349
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2350
"""Tests that really need to do things with an external bzr."""
2352
def test_start_and_stop_bzr_subprocess_send_signal(self):
2353
"""finish_bzr_subprocess raises self.failureException if the retcode is
2354
not the expected one.
2356
self.disable_missing_extensions_warning()
2357
process = self.start_bzr_subprocess(['wait-until-signalled'],
2358
skip_if_plan_to_signal=True)
2359
self.assertEqual('running\n', process.stdout.readline())
2360
result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2362
self.assertEqual('', result[0])
2363
self.assertEqual('bzr: interrupted\n', result[1])
2366
class TestFeature(tests.TestCase):
1772
self.fail('Assertion not raised')
1775
class TestFeature(TestCase):
2368
1777
def test_caching(self):
2369
1778
"""Feature._probe is called by the feature at most once."""
2370
class InstrumentedFeature(tests.Feature):
1779
class InstrumentedFeature(Feature):
2371
1780
def __init__(self):
2372
super(InstrumentedFeature, self).__init__()
1781
Feature.__init__(self)
2373
1782
self.calls = []
2374
1783
def _probe(self):
2375
1784
self.calls.append('_probe')