1813
1867
test_suite_factory=factory)
1814
1868
self.assertEqual([True], factory_called)
1871
"""A test suite factory."""
1872
class Test(tests.TestCase):
1879
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1881
def test_list_only(self):
1882
output = self.run_selftest(test_suite_factory=self.factory,
1884
self.assertEqual(3, len(output.readlines()))
1886
def test_list_only_filtered(self):
1887
output = self.run_selftest(test_suite_factory=self.factory,
1888
list_only=True, pattern="Test.b")
1889
self.assertEndsWith(output.getvalue(), "Test.b\n")
1890
self.assertLength(1, output.readlines())
1892
def test_list_only_excludes(self):
1893
output = self.run_selftest(test_suite_factory=self.factory,
1894
list_only=True, exclude_pattern="Test.b")
1895
self.assertNotContainsRe("Test.b", output.getvalue())
1896
self.assertLength(2, output.readlines())
1898
def test_lsprof_tests(self):
1899
self.requireFeature(test_lsprof.LSProfFeature)
1902
def __call__(test, result):
1904
def run(test, result):
1905
self.assertIsInstance(result, tests.ForwardingResult)
1906
calls.append("called")
1907
def countTestCases(self):
1909
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1910
self.assertLength(1, calls)
1912
def test_random(self):
1913
# test randomising by listing a number of tests.
1914
output_123 = self.run_selftest(test_suite_factory=self.factory,
1915
list_only=True, random_seed="123")
1916
output_234 = self.run_selftest(test_suite_factory=self.factory,
1917
list_only=True, random_seed="234")
1918
self.assertNotEqual(output_123, output_234)
1919
# "Randominzing test order..\n\n
1920
self.assertLength(5, output_123.readlines())
1921
self.assertLength(5, output_234.readlines())
1923
def test_random_reuse_is_same_order(self):
1924
# test randomising by listing a number of tests.
1925
expected = self.run_selftest(test_suite_factory=self.factory,
1926
list_only=True, random_seed="123")
1927
repeated = self.run_selftest(test_suite_factory=self.factory,
1928
list_only=True, random_seed="123")
1929
self.assertEqual(expected.getvalue(), repeated.getvalue())
1931
def test_runner_class(self):
1932
self.requireFeature(SubUnitFeature)
1933
from subunit import ProtocolTestCase
1934
stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1935
test_suite_factory=self.factory)
1936
test = ProtocolTestCase(stream)
1937
result = unittest.TestResult()
1939
self.assertEqual(3, result.testsRun)
1941
def test_starting_with_single_argument(self):
1942
output = self.run_selftest(test_suite_factory=self.factory,
1943
starting_with=['bzrlib.tests.test_selftest.Test.a'],
1945
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1948
def test_starting_with_multiple_argument(self):
1949
output = self.run_selftest(test_suite_factory=self.factory,
1950
starting_with=['bzrlib.tests.test_selftest.Test.a',
1951
'bzrlib.tests.test_selftest.Test.b'],
1953
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1954
'bzrlib.tests.test_selftest.Test.b\n',
1957
def check_transport_set(self, transport_server):
1958
captured_transport = []
1959
def seen_transport(a_transport):
1960
captured_transport.append(a_transport)
1961
class Capture(tests.TestCase):
1963
seen_transport(bzrlib.tests.default_transport)
1965
return TestUtil.TestSuite([Capture("a")])
1966
self.run_selftest(transport=transport_server, test_suite_factory=factory)
1967
self.assertEqual(transport_server, captured_transport[0])
1969
def test_transport_sftp(self):
1971
import bzrlib.transport.sftp
1972
except errors.ParamikoNotPresent:
1973
raise tests.TestSkipped("Paramiko not present")
1974
self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
1976
def test_transport_memory(self):
1977
self.check_transport_set(bzrlib.transport.memory.MemoryServer)
1980
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
1981
# Does IO: reads test.list
1983
def test_load_list(self):
1984
# Provide a list with one test - this test.
1985
test_id_line = '%s\n' % self.id()
1986
self.build_tree_contents([('test.list', test_id_line)])
1987
# And generate a list of the tests in the suite.
1988
stream = self.run_selftest(load_list='test.list', list_only=True)
1989
self.assertEqual(test_id_line, stream.getvalue())
1991
def test_load_unknown(self):
1992
# Provide a list with one test - this test.
1993
# And generate a list of the tests in the suite.
1994
err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
1995
load_list='missing file name', list_only=True)
1998
class TestRunBzr(tests.TestCase):
2003
def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
2005
"""Override _run_bzr_core to test how it is invoked by run_bzr.
2007
Attempts to run bzr from inside this class don't actually run it.
2009
We test how run_bzr actually invokes bzr in another location.
2010
Here we only need to test that it is run_bzr passes the right
2011
parameters to run_bzr.
2013
self.argv = list(argv)
2014
self.retcode = retcode
2015
self.encoding = encoding
2017
self.working_dir = working_dir
2018
return self.out, self.err
2020
def test_run_bzr_error(self):
2021
self.out = "It sure does!\n"
2022
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
2023
self.assertEqual(['rocks'], self.argv)
2024
self.assertEqual(34, self.retcode)
2025
self.assertEqual(out, 'It sure does!\n')
2027
def test_run_bzr_error_regexes(self):
2029
self.err = "bzr: ERROR: foobarbaz is not versioned"
2030
out, err = self.run_bzr_error(
2031
["bzr: ERROR: foobarbaz is not versioned"],
2032
['file-id', 'foobarbaz'])
2034
def test_encoding(self):
2035
"""Test that run_bzr passes encoding to _run_bzr_core"""
2036
self.run_bzr('foo bar')
2037
self.assertEqual(None, self.encoding)
2038
self.assertEqual(['foo', 'bar'], self.argv)
2040
self.run_bzr('foo bar', encoding='baz')
2041
self.assertEqual('baz', self.encoding)
2042
self.assertEqual(['foo', 'bar'], self.argv)
2044
def test_retcode(self):
2045
"""Test that run_bzr passes retcode to _run_bzr_core"""
2046
# Default is retcode == 0
2047
self.run_bzr('foo bar')
2048
self.assertEqual(0, self.retcode)
2049
self.assertEqual(['foo', 'bar'], self.argv)
2051
self.run_bzr('foo bar', retcode=1)
2052
self.assertEqual(1, self.retcode)
2053
self.assertEqual(['foo', 'bar'], self.argv)
2055
self.run_bzr('foo bar', retcode=None)
2056
self.assertEqual(None, self.retcode)
2057
self.assertEqual(['foo', 'bar'], self.argv)
2059
self.run_bzr(['foo', 'bar'], retcode=3)
2060
self.assertEqual(3, self.retcode)
2061
self.assertEqual(['foo', 'bar'], self.argv)
2063
def test_stdin(self):
2064
# test that the stdin keyword to run_bzr is passed through to
2065
# _run_bzr_core as-is. We do this by overriding
2066
# _run_bzr_core in this class, and then calling run_bzr,
2067
# which is a convenience function for _run_bzr_core, so
2069
self.run_bzr('foo bar', stdin='gam')
2070
self.assertEqual('gam', self.stdin)
2071
self.assertEqual(['foo', 'bar'], self.argv)
2073
self.run_bzr('foo bar', stdin='zippy')
2074
self.assertEqual('zippy', self.stdin)
2075
self.assertEqual(['foo', 'bar'], self.argv)
2077
def test_working_dir(self):
2078
"""Test that run_bzr passes working_dir to _run_bzr_core"""
2079
self.run_bzr('foo bar')
2080
self.assertEqual(None, self.working_dir)
2081
self.assertEqual(['foo', 'bar'], self.argv)
2083
self.run_bzr('foo bar', working_dir='baz')
2084
self.assertEqual('baz', self.working_dir)
2085
self.assertEqual(['foo', 'bar'], self.argv)
2087
def test_reject_extra_keyword_arguments(self):
2088
self.assertRaises(TypeError, self.run_bzr, "foo bar",
2089
error_regex=['error message'])
2092
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2093
# Does IO when testing the working_dir parameter.
2095
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2096
a_callable=None, *args, **kwargs):
2098
self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2099
self.factory = bzrlib.ui.ui_factory
2100
self.working_dir = osutils.getcwd()
2101
stdout.write('foo\n')
2102
stderr.write('bar\n')
2105
def test_stdin(self):
2106
# test that the stdin keyword to _run_bzr_core is passed through to
2107
# apply_redirected as a StringIO. We do this by overriding
2108
# apply_redirected in this class, and then calling _run_bzr_core,
2109
# which calls apply_redirected.
2110
self.run_bzr(['foo', 'bar'], stdin='gam')
2111
self.assertEqual('gam', self.stdin.read())
2112
self.assertTrue(self.stdin is self.factory_stdin)
2113
self.run_bzr(['foo', 'bar'], stdin='zippy')
2114
self.assertEqual('zippy', self.stdin.read())
2115
self.assertTrue(self.stdin is self.factory_stdin)
2117
def test_ui_factory(self):
2118
# each invocation of self.run_bzr should get its
2119
# own UI factory, which is an instance of TestUIFactory,
2120
# with stdin, stdout and stderr attached to the stdin,
2121
# stdout and stderr of the invoked run_bzr
2122
current_factory = bzrlib.ui.ui_factory
2123
self.run_bzr(['foo'])
2124
self.failIf(current_factory is self.factory)
2125
self.assertNotEqual(sys.stdout, self.factory.stdout)
2126
self.assertNotEqual(sys.stderr, self.factory.stderr)
2127
self.assertEqual('foo\n', self.factory.stdout.getvalue())
2128
self.assertEqual('bar\n', self.factory.stderr.getvalue())
2129
self.assertIsInstance(self.factory, tests.TestUIFactory)
2131
def test_working_dir(self):
2132
self.build_tree(['one/', 'two/'])
2133
cwd = osutils.getcwd()
2135
# Default is to work in the current directory
2136
self.run_bzr(['foo', 'bar'])
2137
self.assertEqual(cwd, self.working_dir)
2139
self.run_bzr(['foo', 'bar'], working_dir=None)
2140
self.assertEqual(cwd, self.working_dir)
2142
# The function should be run in the alternative directory
2143
# but afterwards the current working dir shouldn't be changed
2144
self.run_bzr(['foo', 'bar'], working_dir='one')
2145
self.assertNotEqual(cwd, self.working_dir)
2146
self.assertEndsWith(self.working_dir, 'one')
2147
self.assertEqual(cwd, osutils.getcwd())
2149
self.run_bzr(['foo', 'bar'], working_dir='two')
2150
self.assertNotEqual(cwd, self.working_dir)
2151
self.assertEndsWith(self.working_dir, 'two')
2152
self.assertEqual(cwd, osutils.getcwd())
2155
class StubProcess(object):
2156
"""A stub process for testing run_bzr_subprocess."""
2158
def __init__(self, out="", err="", retcode=0):
2161
self.returncode = retcode
2163
def communicate(self):
2164
return self.out, self.err
2167
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2168
"""Base class for tests testing how we might run bzr."""
2171
tests.TestCaseWithTransport.setUp(self)
2172
self.subprocess_calls = []
2174
def start_bzr_subprocess(self, process_args, env_changes=None,
2175
skip_if_plan_to_signal=False,
2177
allow_plugins=False):
2178
"""capture what run_bzr_subprocess tries to do."""
2179
self.subprocess_calls.append({'process_args':process_args,
2180
'env_changes':env_changes,
2181
'skip_if_plan_to_signal':skip_if_plan_to_signal,
2182
'working_dir':working_dir, 'allow_plugins':allow_plugins})
2183
return self.next_subprocess
2186
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2188
def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2189
"""Run run_bzr_subprocess with args and kwargs using a stubbed process.
2191
Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2192
that will return static results. This assertion method populates those
2193
results and also checks the arguments run_bzr_subprocess generates.
2195
self.next_subprocess = process
2197
result = self.run_bzr_subprocess(*args, **kwargs)
2199
self.next_subprocess = None
2200
for key, expected in expected_args.iteritems():
2201
self.assertEqual(expected, self.subprocess_calls[-1][key])
2204
self.next_subprocess = None
2205
for key, expected in expected_args.iteritems():
2206
self.assertEqual(expected, self.subprocess_calls[-1][key])
2209
def test_run_bzr_subprocess(self):
2210
"""The run_bzr_helper_external command behaves nicely."""
2211
self.assertRunBzrSubprocess({'process_args':['--version']},
2212
StubProcess(), '--version')
2213
self.assertRunBzrSubprocess({'process_args':['--version']},
2214
StubProcess(), ['--version'])
2215
# retcode=None disables retcode checking
2216
result = self.assertRunBzrSubprocess({},
2217
StubProcess(retcode=3), '--version', retcode=None)
2218
result = self.assertRunBzrSubprocess({},
2219
StubProcess(out="is free software"), '--version')
2220
self.assertContainsRe(result[0], 'is free software')
2221
# Running a subcommand that is missing errors
2222
self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2223
{'process_args':['--versionn']}, StubProcess(retcode=3),
2225
# Unless it is told to expect the error from the subprocess
2226
result = self.assertRunBzrSubprocess({},
2227
StubProcess(retcode=3), '--versionn', retcode=3)
2228
# Or to ignore retcode checking
2229
result = self.assertRunBzrSubprocess({},
2230
StubProcess(err="unknown command", retcode=3), '--versionn',
2232
self.assertContainsRe(result[1], 'unknown command')
2234
def test_env_change_passes_through(self):
2235
self.assertRunBzrSubprocess(
2236
{'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2238
env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2240
def test_no_working_dir_passed_as_None(self):
2241
self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2243
def test_no_working_dir_passed_through(self):
2244
self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2247
def test_run_bzr_subprocess_no_plugins(self):
2248
self.assertRunBzrSubprocess({'allow_plugins': False},
2251
def test_allow_plugins(self):
2252
self.assertRunBzrSubprocess({'allow_plugins': True},
2253
StubProcess(), '', allow_plugins=True)
2256
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2258
def test_finish_bzr_subprocess_with_error(self):
2259
"""finish_bzr_subprocess allows specification of the desired exit code.
2261
process = StubProcess(err="unknown command", retcode=3)
2262
result = self.finish_bzr_subprocess(process, retcode=3)
2263
self.assertEqual('', result[0])
2264
self.assertContainsRe(result[1], 'unknown command')
2266
def test_finish_bzr_subprocess_ignoring_retcode(self):
2267
"""finish_bzr_subprocess allows the exit code to be ignored."""
2268
process = StubProcess(err="unknown command", retcode=3)
2269
result = self.finish_bzr_subprocess(process, retcode=None)
2270
self.assertEqual('', result[0])
2271
self.assertContainsRe(result[1], 'unknown command')
2273
def test_finish_subprocess_with_unexpected_retcode(self):
2274
"""finish_bzr_subprocess raises self.failureException if the retcode is
2275
not the expected one.
2277
process = StubProcess(err="unknown command", retcode=3)
2278
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2282
class _DontSpawnProcess(Exception):
2283
"""A simple exception which just allows us to skip unnecessary steps"""
2286
class TestStartBzrSubProcess(tests.TestCase):
2288
def check_popen_state(self):
2289
"""Replace to make assertions when popen is called."""
2291
def _popen(self, *args, **kwargs):
2292
"""Record the command that is run, so that we can ensure it is correct"""
2293
self.check_popen_state()
2294
self._popen_args = args
2295
self._popen_kwargs = kwargs
2296
raise _DontSpawnProcess()
2298
def test_run_bzr_subprocess_no_plugins(self):
2299
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2300
command = self._popen_args[0]
2301
self.assertEqual(sys.executable, command[0])
2302
self.assertEqual(self.get_bzr_path(), command[1])
2303
self.assertEqual(['--no-plugins'], command[2:])
2305
def test_allow_plugins(self):
2306
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2308
command = self._popen_args[0]
2309
self.assertEqual([], command[2:])
2311
def test_set_env(self):
2312
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2314
def check_environment():
2315
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2316
self.check_popen_state = check_environment
2317
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2318
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2319
# not set in theparent
2320
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2322
def test_run_bzr_subprocess_env_del(self):
2323
"""run_bzr_subprocess can remove environment variables too."""
2324
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2325
def check_environment():
2326
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2327
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2328
self.check_popen_state = check_environment
2329
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2330
env_changes={'EXISTANT_ENV_VAR':None})
2331
# Still set in parent
2332
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2333
del os.environ['EXISTANT_ENV_VAR']
2335
def test_env_del_missing(self):
2336
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2337
def check_environment():
2338
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2339
self.check_popen_state = check_environment
2340
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2341
env_changes={'NON_EXISTANT_ENV_VAR':None})
2343
def test_working_dir(self):
2344
"""Test that we can specify the working dir for the child"""
2345
orig_getcwd = osutils.getcwd
2346
orig_chdir = os.chdir
2354
osutils.getcwd = getcwd
2356
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2359
osutils.getcwd = orig_getcwd
2361
os.chdir = orig_chdir
2362
self.assertEqual(['foo', 'current'], chdirs)
2365
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2366
"""Tests that really need to do things with an external bzr."""
2368
def test_start_and_stop_bzr_subprocess_send_signal(self):
2369
"""finish_bzr_subprocess raises self.failureException if the retcode is
2370
not the expected one.
2372
process = self.start_bzr_subprocess(['wait-until-signalled'],
2373
skip_if_plan_to_signal=True)
2374
self.assertEqual('running\n', process.stdout.readline())
2375
result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2377
self.assertEqual('', result[0])
2378
self.assertEqual('bzr: interrupted\n', result[1])
1817
2381
class TestKnownFailure(tests.TestCase):