1770
1904
test_suite_factory=factory)
1771
1905
self.assertEqual([True], factory_called)
1908
"""A test suite factory."""
1909
class Test(tests.TestCase):
1916
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1918
def test_list_only(self):
1919
output = self.run_selftest(test_suite_factory=self.factory,
1921
self.assertEqual(3, len(output.readlines()))
1923
def test_list_only_filtered(self):
1924
output = self.run_selftest(test_suite_factory=self.factory,
1925
list_only=True, pattern="Test.b")
1926
self.assertEndsWith(output.getvalue(), "Test.b\n")
1927
self.assertLength(1, output.readlines())
1929
def test_list_only_excludes(self):
1930
output = self.run_selftest(test_suite_factory=self.factory,
1931
list_only=True, exclude_pattern="Test.b")
1932
self.assertNotContainsRe("Test.b", output.getvalue())
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)
1949
def test_random(self):
1950
# test randomising by listing a number of tests.
1951
output_123 = self.run_selftest(test_suite_factory=self.factory,
1952
list_only=True, random_seed="123")
1953
output_234 = self.run_selftest(test_suite_factory=self.factory,
1954
list_only=True, random_seed="234")
1955
self.assertNotEqual(output_123, output_234)
1956
# "Randominzing test order..\n\n
1957
self.assertLength(5, output_123.readlines())
1958
self.assertLength(5, output_234.readlines())
1960
def test_random_reuse_is_same_order(self):
1961
# test randomising by listing a number of tests.
1962
expected = self.run_selftest(test_suite_factory=self.factory,
1963
list_only=True, random_seed="123")
1964
repeated = self.run_selftest(test_suite_factory=self.factory,
1965
list_only=True, random_seed="123")
1966
self.assertEqual(expected.getvalue(), repeated.getvalue())
1968
def test_runner_class(self):
1969
self.requireFeature(SubUnitFeature)
1970
from subunit import ProtocolTestCase
1971
stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1972
test_suite_factory=self.factory)
1973
test = ProtocolTestCase(stream)
1974
result = unittest.TestResult()
1976
self.assertEqual(3, result.testsRun)
1978
def test_starting_with_single_argument(self):
1979
output = self.run_selftest(test_suite_factory=self.factory,
1980
starting_with=['bzrlib.tests.test_selftest.Test.a'],
1982
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1985
def test_starting_with_multiple_argument(self):
1986
output = self.run_selftest(test_suite_factory=self.factory,
1987
starting_with=['bzrlib.tests.test_selftest.Test.a',
1988
'bzrlib.tests.test_selftest.Test.b'],
1990
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1991
'bzrlib.tests.test_selftest.Test.b\n',
1994
def check_transport_set(self, transport_server):
1995
captured_transport = []
1996
def seen_transport(a_transport):
1997
captured_transport.append(a_transport)
1998
class Capture(tests.TestCase):
2000
seen_transport(bzrlib.tests.default_transport)
2002
return TestUtil.TestSuite([Capture("a")])
2003
self.run_selftest(transport=transport_server, test_suite_factory=factory)
2004
self.assertEqual(transport_server, captured_transport[0])
2006
def test_transport_sftp(self):
2008
import bzrlib.transport.sftp
2009
except errors.ParamikoNotPresent:
2010
raise tests.TestSkipped("Paramiko not present")
2011
self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
2013
def test_transport_memory(self):
2014
self.check_transport_set(bzrlib.transport.memory.MemoryServer)
2017
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
2018
# Does IO: reads test.list
2020
def test_load_list(self):
2021
# Provide a list with one test - this test.
2022
test_id_line = '%s\n' % self.id()
2023
self.build_tree_contents([('test.list', test_id_line)])
2024
# And generate a list of the tests in the suite.
2025
stream = self.run_selftest(load_list='test.list', list_only=True)
2026
self.assertEqual(test_id_line, stream.getvalue())
2028
def test_load_unknown(self):
2029
# Provide a list with one test - this test.
2030
# And generate a list of the tests in the suite.
2031
err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
2032
load_list='missing file name', list_only=True)
2035
class TestRunBzr(tests.TestCase):
2040
def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
2042
"""Override _run_bzr_core to test how it is invoked by run_bzr.
2044
Attempts to run bzr from inside this class don't actually run it.
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.
2049
self.argv = list(argv)
2050
self.retcode = retcode
2051
self.encoding = encoding
2053
self.working_dir = working_dir
2054
return self.retcode, self.out, self.err
2056
def test_run_bzr_error(self):
2057
self.out = "It sure does!\n"
2058
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
2059
self.assertEqual(['rocks'], self.argv)
2060
self.assertEqual(34, self.retcode)
2061
self.assertEqual('It sure does!\n', out)
2062
self.assertEquals(out, self.out)
2063
self.assertEqual('', err)
2064
self.assertEquals(err, self.err)
2066
def test_run_bzr_error_regexes(self):
2068
self.err = "bzr: ERROR: foobarbaz is not versioned"
2069
out, err = self.run_bzr_error(
2070
["bzr: ERROR: foobarbaz is not versioned"],
2071
['file-id', 'foobarbaz'])
2073
def test_encoding(self):
2074
"""Test that run_bzr passes encoding to _run_bzr_core"""
2075
self.run_bzr('foo bar')
2076
self.assertEqual(None, self.encoding)
2077
self.assertEqual(['foo', 'bar'], self.argv)
2079
self.run_bzr('foo bar', encoding='baz')
2080
self.assertEqual('baz', self.encoding)
2081
self.assertEqual(['foo', 'bar'], self.argv)
2083
def test_retcode(self):
2084
"""Test that run_bzr passes retcode to _run_bzr_core"""
2085
# Default is retcode == 0
2086
self.run_bzr('foo bar')
2087
self.assertEqual(0, self.retcode)
2088
self.assertEqual(['foo', 'bar'], self.argv)
2090
self.run_bzr('foo bar', retcode=1)
2091
self.assertEqual(1, self.retcode)
2092
self.assertEqual(['foo', 'bar'], self.argv)
2094
self.run_bzr('foo bar', retcode=None)
2095
self.assertEqual(None, self.retcode)
2096
self.assertEqual(['foo', 'bar'], self.argv)
2098
self.run_bzr(['foo', 'bar'], retcode=3)
2099
self.assertEqual(3, self.retcode)
2100
self.assertEqual(['foo', 'bar'], self.argv)
2102
def test_stdin(self):
2103
# test that the stdin keyword to run_bzr is passed through to
2104
# _run_bzr_core as-is. We do this by overriding
2105
# _run_bzr_core in this class, and then calling run_bzr,
2106
# which is a convenience function for _run_bzr_core, so
2108
self.run_bzr('foo bar', stdin='gam')
2109
self.assertEqual('gam', self.stdin)
2110
self.assertEqual(['foo', 'bar'], self.argv)
2112
self.run_bzr('foo bar', stdin='zippy')
2113
self.assertEqual('zippy', self.stdin)
2114
self.assertEqual(['foo', 'bar'], self.argv)
2116
def test_working_dir(self):
2117
"""Test that run_bzr passes working_dir to _run_bzr_core"""
2118
self.run_bzr('foo bar')
2119
self.assertEqual(None, self.working_dir)
2120
self.assertEqual(['foo', 'bar'], self.argv)
2122
self.run_bzr('foo bar', working_dir='baz')
2123
self.assertEqual('baz', self.working_dir)
2124
self.assertEqual(['foo', 'bar'], self.argv)
2126
def test_reject_extra_keyword_arguments(self):
2127
self.assertRaises(TypeError, self.run_bzr, "foo bar",
2128
error_regex=['error message'])
2131
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2132
# Does IO when testing the working_dir parameter.
2134
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2135
a_callable=None, *args, **kwargs):
2137
self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2138
self.factory = bzrlib.ui.ui_factory
2139
self.working_dir = osutils.getcwd()
2140
stdout.write('foo\n')
2141
stderr.write('bar\n')
2144
def test_stdin(self):
2145
# test that the stdin keyword to _run_bzr_core is passed through to
2146
# apply_redirected as a StringIO. We do this by overriding
2147
# apply_redirected in this class, and then calling _run_bzr_core,
2148
# which calls apply_redirected.
2149
self.run_bzr(['foo', 'bar'], stdin='gam')
2150
self.assertEqual('gam', self.stdin.read())
2151
self.assertTrue(self.stdin is self.factory_stdin)
2152
self.run_bzr(['foo', 'bar'], stdin='zippy')
2153
self.assertEqual('zippy', self.stdin.read())
2154
self.assertTrue(self.stdin is self.factory_stdin)
2156
def test_ui_factory(self):
2157
# each invocation of self.run_bzr should get its
2158
# own UI factory, which is an instance of TestUIFactory,
2159
# with stdin, stdout and stderr attached to the stdin,
2160
# stdout and stderr of the invoked run_bzr
2161
current_factory = bzrlib.ui.ui_factory
2162
self.run_bzr(['foo'])
2163
self.failIf(current_factory is self.factory)
2164
self.assertNotEqual(sys.stdout, self.factory.stdout)
2165
self.assertNotEqual(sys.stderr, self.factory.stderr)
2166
self.assertEqual('foo\n', self.factory.stdout.getvalue())
2167
self.assertEqual('bar\n', self.factory.stderr.getvalue())
2168
self.assertIsInstance(self.factory, tests.TestUIFactory)
2170
def test_working_dir(self):
2171
self.build_tree(['one/', 'two/'])
2172
cwd = osutils.getcwd()
2174
# Default is to work in the current directory
2175
self.run_bzr(['foo', 'bar'])
2176
self.assertEqual(cwd, self.working_dir)
2178
self.run_bzr(['foo', 'bar'], working_dir=None)
2179
self.assertEqual(cwd, self.working_dir)
2181
# The function should be run in the alternative directory
2182
# but afterwards the current working dir shouldn't be changed
2183
self.run_bzr(['foo', 'bar'], working_dir='one')
2184
self.assertNotEqual(cwd, self.working_dir)
2185
self.assertEndsWith(self.working_dir, 'one')
2186
self.assertEqual(cwd, osutils.getcwd())
2188
self.run_bzr(['foo', 'bar'], working_dir='two')
2189
self.assertNotEqual(cwd, self.working_dir)
2190
self.assertEndsWith(self.working_dir, 'two')
2191
self.assertEqual(cwd, osutils.getcwd())
2194
class StubProcess(object):
2195
"""A stub process for testing run_bzr_subprocess."""
2197
def __init__(self, out="", err="", retcode=0):
2200
self.returncode = retcode
2202
def communicate(self):
2203
return self.out, self.err
2206
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2207
"""Base class for tests testing how we might run bzr."""
2210
tests.TestCaseWithTransport.setUp(self)
2211
self.subprocess_calls = []
2213
def start_bzr_subprocess(self, process_args, env_changes=None,
2214
skip_if_plan_to_signal=False,
2216
allow_plugins=False):
2217
"""capture what run_bzr_subprocess tries to do."""
2218
self.subprocess_calls.append({'process_args':process_args,
2219
'env_changes':env_changes,
2220
'skip_if_plan_to_signal':skip_if_plan_to_signal,
2221
'working_dir':working_dir, 'allow_plugins':allow_plugins})
2222
return self.next_subprocess
2225
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2227
def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2228
"""Run run_bzr_subprocess with args and kwargs using a stubbed process.
2230
Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2231
that will return static results. This assertion method populates those
2232
results and also checks the arguments run_bzr_subprocess generates.
2234
self.next_subprocess = process
2236
result = self.run_bzr_subprocess(*args, **kwargs)
2238
self.next_subprocess = None
2239
for key, expected in expected_args.iteritems():
2240
self.assertEqual(expected, self.subprocess_calls[-1][key])
2243
self.next_subprocess = None
2244
for key, expected in expected_args.iteritems():
2245
self.assertEqual(expected, self.subprocess_calls[-1][key])
2248
def test_run_bzr_subprocess(self):
2249
"""The run_bzr_helper_external command behaves nicely."""
2250
self.assertRunBzrSubprocess({'process_args':['--version']},
2251
StubProcess(), '--version')
2252
self.assertRunBzrSubprocess({'process_args':['--version']},
2253
StubProcess(), ['--version'])
2254
# retcode=None disables retcode checking
2255
result = self.assertRunBzrSubprocess({},
2256
StubProcess(retcode=3), '--version', retcode=None)
2257
result = self.assertRunBzrSubprocess({},
2258
StubProcess(out="is free software"), '--version')
2259
self.assertContainsRe(result[0], 'is free software')
2260
# Running a subcommand that is missing errors
2261
self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2262
{'process_args':['--versionn']}, StubProcess(retcode=3),
2264
# Unless it is told to expect the error from the subprocess
2265
result = self.assertRunBzrSubprocess({},
2266
StubProcess(retcode=3), '--versionn', retcode=3)
2267
# Or to ignore retcode checking
2268
result = self.assertRunBzrSubprocess({},
2269
StubProcess(err="unknown command", retcode=3), '--versionn',
2271
self.assertContainsRe(result[1], 'unknown command')
2273
def test_env_change_passes_through(self):
2274
self.assertRunBzrSubprocess(
2275
{'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2277
env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2279
def test_no_working_dir_passed_as_None(self):
2280
self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2282
def test_no_working_dir_passed_through(self):
2283
self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2286
def test_run_bzr_subprocess_no_plugins(self):
2287
self.assertRunBzrSubprocess({'allow_plugins': False},
2290
def test_allow_plugins(self):
2291
self.assertRunBzrSubprocess({'allow_plugins': True},
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,
2321
class _DontSpawnProcess(Exception):
2322
"""A simple exception which just allows us to skip unnecessary steps"""
2325
class TestStartBzrSubProcess(tests.TestCase):
2327
def check_popen_state(self):
2328
"""Replace to make assertions when popen is called."""
2330
def _popen(self, *args, **kwargs):
2331
"""Record the command that is run, so that we can ensure it is correct"""
2332
self.check_popen_state()
2333
self._popen_args = args
2334
self._popen_kwargs = kwargs
2335
raise _DontSpawnProcess()
2337
def test_run_bzr_subprocess_no_plugins(self):
2338
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2339
command = self._popen_args[0]
2340
self.assertEqual(sys.executable, command[0])
2341
self.assertEqual(self.get_bzr_path(), command[1])
2342
self.assertEqual(['--no-plugins'], command[2:])
2344
def test_allow_plugins(self):
2345
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2347
command = self._popen_args[0]
2348
self.assertEqual([], command[2:])
2350
def test_set_env(self):
2351
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2353
def check_environment():
2354
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2355
self.check_popen_state = check_environment
2356
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2357
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2358
# not set in theparent
2359
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2361
def test_run_bzr_subprocess_env_del(self):
2362
"""run_bzr_subprocess can remove environment variables too."""
2363
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2364
def check_environment():
2365
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2366
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2367
self.check_popen_state = check_environment
2368
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2369
env_changes={'EXISTANT_ENV_VAR':None})
2370
# Still set in parent
2371
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2372
del os.environ['EXISTANT_ENV_VAR']
2374
def test_env_del_missing(self):
2375
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2376
def check_environment():
2377
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2378
self.check_popen_state = check_environment
2379
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2380
env_changes={'NON_EXISTANT_ENV_VAR':None})
2382
def test_working_dir(self):
2383
"""Test that we can specify the working dir for the child"""
2384
orig_getcwd = osutils.getcwd
2385
orig_chdir = os.chdir
2393
osutils.getcwd = getcwd
2395
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2398
osutils.getcwd = orig_getcwd
2400
os.chdir = orig_chdir
2401
self.assertEqual(['foo', 'current'], chdirs)
2404
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2405
"""Tests that really need to do things with an external bzr."""
2407
def test_start_and_stop_bzr_subprocess_send_signal(self):
2408
"""finish_bzr_subprocess raises self.failureException if the retcode is
2409
not the expected one.
2411
self.disable_missing_extensions_warning()
2412
process = self.start_bzr_subprocess(['wait-until-signalled'],
2413
skip_if_plan_to_signal=True)
2414
self.assertEqual('running\n', process.stdout.readline())
2415
result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2417
self.assertEqual('', result[0])
2418
self.assertEqual('bzr: interrupted\n', result[1])
1774
2421
class TestKnownFailure(tests.TestCase):