1725
1910
test_suite_factory=factory)
1726
1911
self.assertEqual([True], factory_called)
1914
"""A test suite factory."""
1915
class Test(tests.TestCase):
1922
return TestUtil.TestSuite([Test("a"), Test("b"), Test("c")])
1924
def test_list_only(self):
1925
output = self.run_selftest(test_suite_factory=self.factory,
1927
self.assertEqual(3, len(output.readlines()))
1929
def test_list_only_filtered(self):
1930
output = self.run_selftest(test_suite_factory=self.factory,
1931
list_only=True, pattern="Test.b")
1932
self.assertEndsWith(output.getvalue(), "Test.b\n")
1933
self.assertLength(1, output.readlines())
1935
def test_list_only_excludes(self):
1936
output = self.run_selftest(test_suite_factory=self.factory,
1937
list_only=True, exclude_pattern="Test.b")
1938
self.assertNotContainsRe("Test.b", output.getvalue())
1939
self.assertLength(2, output.readlines())
1941
def test_lsprof_tests(self):
1942
self.requireFeature(test_lsprof.LSProfFeature)
1945
def __call__(test, result):
1947
def run(test, result):
1948
self.assertIsInstance(result, tests.ForwardingResult)
1949
calls.append("called")
1950
def countTestCases(self):
1952
self.run_selftest(test_suite_factory=Test, lsprof_tests=True)
1953
self.assertLength(1, calls)
1955
def test_random(self):
1956
# test randomising by listing a number of tests.
1957
output_123 = self.run_selftest(test_suite_factory=self.factory,
1958
list_only=True, random_seed="123")
1959
output_234 = self.run_selftest(test_suite_factory=self.factory,
1960
list_only=True, random_seed="234")
1961
self.assertNotEqual(output_123, output_234)
1962
# "Randominzing test order..\n\n
1963
self.assertLength(5, output_123.readlines())
1964
self.assertLength(5, output_234.readlines())
1966
def test_random_reuse_is_same_order(self):
1967
# test randomising by listing a number of tests.
1968
expected = self.run_selftest(test_suite_factory=self.factory,
1969
list_only=True, random_seed="123")
1970
repeated = self.run_selftest(test_suite_factory=self.factory,
1971
list_only=True, random_seed="123")
1972
self.assertEqual(expected.getvalue(), repeated.getvalue())
1974
def test_runner_class(self):
1975
self.requireFeature(SubUnitFeature)
1976
from subunit import ProtocolTestCase
1977
stream = self.run_selftest(runner_class=tests.SubUnitBzrRunner,
1978
test_suite_factory=self.factory)
1979
test = ProtocolTestCase(stream)
1980
result = unittest.TestResult()
1982
self.assertEqual(3, result.testsRun)
1984
def test_starting_with_single_argument(self):
1985
output = self.run_selftest(test_suite_factory=self.factory,
1986
starting_with=['bzrlib.tests.test_selftest.Test.a'],
1988
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n',
1991
def test_starting_with_multiple_argument(self):
1992
output = self.run_selftest(test_suite_factory=self.factory,
1993
starting_with=['bzrlib.tests.test_selftest.Test.a',
1994
'bzrlib.tests.test_selftest.Test.b'],
1996
self.assertEqual('bzrlib.tests.test_selftest.Test.a\n'
1997
'bzrlib.tests.test_selftest.Test.b\n',
2000
def check_transport_set(self, transport_server):
2001
captured_transport = []
2002
def seen_transport(a_transport):
2003
captured_transport.append(a_transport)
2004
class Capture(tests.TestCase):
2006
seen_transport(bzrlib.tests.default_transport)
2008
return TestUtil.TestSuite([Capture("a")])
2009
self.run_selftest(transport=transport_server, test_suite_factory=factory)
2010
self.assertEqual(transport_server, captured_transport[0])
2012
def test_transport_sftp(self):
2014
import bzrlib.transport.sftp
2015
except errors.ParamikoNotPresent:
2016
raise tests.TestSkipped("Paramiko not present")
2017
self.check_transport_set(bzrlib.transport.sftp.SFTPAbsoluteServer)
2019
def test_transport_memory(self):
2020
self.check_transport_set(bzrlib.transport.memory.MemoryServer)
2023
class TestSelftestWithIdList(tests.TestCaseInTempDir, SelfTestHelper):
2024
# Does IO: reads test.list
2026
def test_load_list(self):
2027
# Provide a list with one test - this test.
2028
test_id_line = '%s\n' % self.id()
2029
self.build_tree_contents([('test.list', test_id_line)])
2030
# And generate a list of the tests in the suite.
2031
stream = self.run_selftest(load_list='test.list', list_only=True)
2032
self.assertEqual(test_id_line, stream.getvalue())
2034
def test_load_unknown(self):
2035
# Provide a list with one test - this test.
2036
# And generate a list of the tests in the suite.
2037
err = self.assertRaises(errors.NoSuchFile, self.run_selftest,
2038
load_list='missing file name', list_only=True)
2041
class TestRunBzr(tests.TestCase):
2046
def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
2048
"""Override _run_bzr_core to test how it is invoked by run_bzr.
2050
Attempts to run bzr from inside this class don't actually run it.
2052
We test how run_bzr actually invokes bzr in another location. Here we
2053
only need to test that it passes the right parameters to run_bzr.
2055
self.argv = list(argv)
2056
self.retcode = retcode
2057
self.encoding = encoding
2059
self.working_dir = working_dir
2060
return self.retcode, self.out, self.err
2062
def test_run_bzr_error(self):
2063
self.out = "It sure does!\n"
2064
out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=34)
2065
self.assertEqual(['rocks'], self.argv)
2066
self.assertEqual(34, self.retcode)
2067
self.assertEqual('It sure does!\n', out)
2068
self.assertEquals(out, self.out)
2069
self.assertEqual('', err)
2070
self.assertEquals(err, self.err)
2072
def test_run_bzr_error_regexes(self):
2074
self.err = "bzr: ERROR: foobarbaz is not versioned"
2075
out, err = self.run_bzr_error(
2076
["bzr: ERROR: foobarbaz is not versioned"],
2077
['file-id', 'foobarbaz'])
2079
def test_encoding(self):
2080
"""Test that run_bzr passes encoding to _run_bzr_core"""
2081
self.run_bzr('foo bar')
2082
self.assertEqual(None, self.encoding)
2083
self.assertEqual(['foo', 'bar'], self.argv)
2085
self.run_bzr('foo bar', encoding='baz')
2086
self.assertEqual('baz', self.encoding)
2087
self.assertEqual(['foo', 'bar'], self.argv)
2089
def test_retcode(self):
2090
"""Test that run_bzr passes retcode to _run_bzr_core"""
2091
# Default is retcode == 0
2092
self.run_bzr('foo bar')
2093
self.assertEqual(0, self.retcode)
2094
self.assertEqual(['foo', 'bar'], self.argv)
2096
self.run_bzr('foo bar', retcode=1)
2097
self.assertEqual(1, self.retcode)
2098
self.assertEqual(['foo', 'bar'], self.argv)
2100
self.run_bzr('foo bar', retcode=None)
2101
self.assertEqual(None, self.retcode)
2102
self.assertEqual(['foo', 'bar'], self.argv)
2104
self.run_bzr(['foo', 'bar'], retcode=3)
2105
self.assertEqual(3, self.retcode)
2106
self.assertEqual(['foo', 'bar'], self.argv)
2108
def test_stdin(self):
2109
# test that the stdin keyword to run_bzr is passed through to
2110
# _run_bzr_core as-is. We do this by overriding
2111
# _run_bzr_core in this class, and then calling run_bzr,
2112
# which is a convenience function for _run_bzr_core, so
2114
self.run_bzr('foo bar', stdin='gam')
2115
self.assertEqual('gam', self.stdin)
2116
self.assertEqual(['foo', 'bar'], self.argv)
2118
self.run_bzr('foo bar', stdin='zippy')
2119
self.assertEqual('zippy', self.stdin)
2120
self.assertEqual(['foo', 'bar'], self.argv)
2122
def test_working_dir(self):
2123
"""Test that run_bzr passes working_dir to _run_bzr_core"""
2124
self.run_bzr('foo bar')
2125
self.assertEqual(None, self.working_dir)
2126
self.assertEqual(['foo', 'bar'], self.argv)
2128
self.run_bzr('foo bar', working_dir='baz')
2129
self.assertEqual('baz', self.working_dir)
2130
self.assertEqual(['foo', 'bar'], self.argv)
2132
def test_reject_extra_keyword_arguments(self):
2133
self.assertRaises(TypeError, self.run_bzr, "foo bar",
2134
error_regex=['error message'])
2137
class TestRunBzrCaptured(tests.TestCaseWithTransport):
2138
# Does IO when testing the working_dir parameter.
2140
def apply_redirected(self, stdin=None, stdout=None, stderr=None,
2141
a_callable=None, *args, **kwargs):
2143
self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
2144
self.factory = bzrlib.ui.ui_factory
2145
self.working_dir = osutils.getcwd()
2146
stdout.write('foo\n')
2147
stderr.write('bar\n')
2150
def test_stdin(self):
2151
# test that the stdin keyword to _run_bzr_core is passed through to
2152
# apply_redirected as a StringIO. We do this by overriding
2153
# apply_redirected in this class, and then calling _run_bzr_core,
2154
# which calls apply_redirected.
2155
self.run_bzr(['foo', 'bar'], stdin='gam')
2156
self.assertEqual('gam', self.stdin.read())
2157
self.assertTrue(self.stdin is self.factory_stdin)
2158
self.run_bzr(['foo', 'bar'], stdin='zippy')
2159
self.assertEqual('zippy', self.stdin.read())
2160
self.assertTrue(self.stdin is self.factory_stdin)
2162
def test_ui_factory(self):
2163
# each invocation of self.run_bzr should get its
2164
# own UI factory, which is an instance of TestUIFactory,
2165
# with stdin, stdout and stderr attached to the stdin,
2166
# stdout and stderr of the invoked run_bzr
2167
current_factory = bzrlib.ui.ui_factory
2168
self.run_bzr(['foo'])
2169
self.failIf(current_factory is self.factory)
2170
self.assertNotEqual(sys.stdout, self.factory.stdout)
2171
self.assertNotEqual(sys.stderr, self.factory.stderr)
2172
self.assertEqual('foo\n', self.factory.stdout.getvalue())
2173
self.assertEqual('bar\n', self.factory.stderr.getvalue())
2174
self.assertIsInstance(self.factory, tests.TestUIFactory)
2176
def test_working_dir(self):
2177
self.build_tree(['one/', 'two/'])
2178
cwd = osutils.getcwd()
2180
# Default is to work in the current directory
2181
self.run_bzr(['foo', 'bar'])
2182
self.assertEqual(cwd, self.working_dir)
2184
self.run_bzr(['foo', 'bar'], working_dir=None)
2185
self.assertEqual(cwd, self.working_dir)
2187
# The function should be run in the alternative directory
2188
# but afterwards the current working dir shouldn't be changed
2189
self.run_bzr(['foo', 'bar'], working_dir='one')
2190
self.assertNotEqual(cwd, self.working_dir)
2191
self.assertEndsWith(self.working_dir, 'one')
2192
self.assertEqual(cwd, osutils.getcwd())
2194
self.run_bzr(['foo', 'bar'], working_dir='two')
2195
self.assertNotEqual(cwd, self.working_dir)
2196
self.assertEndsWith(self.working_dir, 'two')
2197
self.assertEqual(cwd, osutils.getcwd())
2200
class StubProcess(object):
2201
"""A stub process for testing run_bzr_subprocess."""
2203
def __init__(self, out="", err="", retcode=0):
2206
self.returncode = retcode
2208
def communicate(self):
2209
return self.out, self.err
2212
class TestWithFakedStartBzrSubprocess(tests.TestCaseWithTransport):
2213
"""Base class for tests testing how we might run bzr."""
2216
tests.TestCaseWithTransport.setUp(self)
2217
self.subprocess_calls = []
2219
def start_bzr_subprocess(self, process_args, env_changes=None,
2220
skip_if_plan_to_signal=False,
2222
allow_plugins=False):
2223
"""capture what run_bzr_subprocess tries to do."""
2224
self.subprocess_calls.append({'process_args':process_args,
2225
'env_changes':env_changes,
2226
'skip_if_plan_to_signal':skip_if_plan_to_signal,
2227
'working_dir':working_dir, 'allow_plugins':allow_plugins})
2228
return self.next_subprocess
2231
class TestRunBzrSubprocess(TestWithFakedStartBzrSubprocess):
2233
def assertRunBzrSubprocess(self, expected_args, process, *args, **kwargs):
2234
"""Run run_bzr_subprocess with args and kwargs using a stubbed process.
2236
Inside TestRunBzrSubprocessCommands we use a stub start_bzr_subprocess
2237
that will return static results. This assertion method populates those
2238
results and also checks the arguments run_bzr_subprocess generates.
2240
self.next_subprocess = process
2242
result = self.run_bzr_subprocess(*args, **kwargs)
2244
self.next_subprocess = None
2245
for key, expected in expected_args.iteritems():
2246
self.assertEqual(expected, self.subprocess_calls[-1][key])
2249
self.next_subprocess = None
2250
for key, expected in expected_args.iteritems():
2251
self.assertEqual(expected, self.subprocess_calls[-1][key])
2254
def test_run_bzr_subprocess(self):
2255
"""The run_bzr_helper_external command behaves nicely."""
2256
self.assertRunBzrSubprocess({'process_args':['--version']},
2257
StubProcess(), '--version')
2258
self.assertRunBzrSubprocess({'process_args':['--version']},
2259
StubProcess(), ['--version'])
2260
# retcode=None disables retcode checking
2261
result = self.assertRunBzrSubprocess({},
2262
StubProcess(retcode=3), '--version', retcode=None)
2263
result = self.assertRunBzrSubprocess({},
2264
StubProcess(out="is free software"), '--version')
2265
self.assertContainsRe(result[0], 'is free software')
2266
# Running a subcommand that is missing errors
2267
self.assertRaises(AssertionError, self.assertRunBzrSubprocess,
2268
{'process_args':['--versionn']}, StubProcess(retcode=3),
2270
# Unless it is told to expect the error from the subprocess
2271
result = self.assertRunBzrSubprocess({},
2272
StubProcess(retcode=3), '--versionn', retcode=3)
2273
# Or to ignore retcode checking
2274
result = self.assertRunBzrSubprocess({},
2275
StubProcess(err="unknown command", retcode=3), '--versionn',
2277
self.assertContainsRe(result[1], 'unknown command')
2279
def test_env_change_passes_through(self):
2280
self.assertRunBzrSubprocess(
2281
{'env_changes':{'new':'value', 'changed':'newvalue', 'deleted':None}},
2283
env_changes={'new':'value', 'changed':'newvalue', 'deleted':None})
2285
def test_no_working_dir_passed_as_None(self):
2286
self.assertRunBzrSubprocess({'working_dir': None}, StubProcess(), '')
2288
def test_no_working_dir_passed_through(self):
2289
self.assertRunBzrSubprocess({'working_dir': 'dir'}, StubProcess(), '',
2292
def test_run_bzr_subprocess_no_plugins(self):
2293
self.assertRunBzrSubprocess({'allow_plugins': False},
2296
def test_allow_plugins(self):
2297
self.assertRunBzrSubprocess({'allow_plugins': True},
2298
StubProcess(), '', allow_plugins=True)
2301
class TestFinishBzrSubprocess(TestWithFakedStartBzrSubprocess):
2303
def test_finish_bzr_subprocess_with_error(self):
2304
"""finish_bzr_subprocess allows specification of the desired exit code.
2306
process = StubProcess(err="unknown command", retcode=3)
2307
result = self.finish_bzr_subprocess(process, retcode=3)
2308
self.assertEqual('', result[0])
2309
self.assertContainsRe(result[1], 'unknown command')
2311
def test_finish_bzr_subprocess_ignoring_retcode(self):
2312
"""finish_bzr_subprocess allows the exit code to be ignored."""
2313
process = StubProcess(err="unknown command", retcode=3)
2314
result = self.finish_bzr_subprocess(process, retcode=None)
2315
self.assertEqual('', result[0])
2316
self.assertContainsRe(result[1], 'unknown command')
2318
def test_finish_subprocess_with_unexpected_retcode(self):
2319
"""finish_bzr_subprocess raises self.failureException if the retcode is
2320
not the expected one.
2322
process = StubProcess(err="unknown command", retcode=3)
2323
self.assertRaises(self.failureException, self.finish_bzr_subprocess,
2327
class _DontSpawnProcess(Exception):
2328
"""A simple exception which just allows us to skip unnecessary steps"""
2331
class TestStartBzrSubProcess(tests.TestCase):
2333
def check_popen_state(self):
2334
"""Replace to make assertions when popen is called."""
2336
def _popen(self, *args, **kwargs):
2337
"""Record the command that is run, so that we can ensure it is correct"""
2338
self.check_popen_state()
2339
self._popen_args = args
2340
self._popen_kwargs = kwargs
2341
raise _DontSpawnProcess()
2343
def test_run_bzr_subprocess_no_plugins(self):
2344
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [])
2345
command = self._popen_args[0]
2346
self.assertEqual(sys.executable, command[0])
2347
self.assertEqual(self.get_bzr_path(), command[1])
2348
self.assertEqual(['--no-plugins'], command[2:])
2350
def test_allow_plugins(self):
2351
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2353
command = self._popen_args[0]
2354
self.assertEqual([], command[2:])
2356
def test_set_env(self):
2357
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2359
def check_environment():
2360
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2361
self.check_popen_state = check_environment
2362
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2363
env_changes={'EXISTANT_ENV_VAR':'set variable'})
2364
# not set in theparent
2365
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2367
def test_run_bzr_subprocess_env_del(self):
2368
"""run_bzr_subprocess can remove environment variables too."""
2369
self.failIf('EXISTANT_ENV_VAR' in os.environ)
2370
def check_environment():
2371
self.assertFalse('EXISTANT_ENV_VAR' in os.environ)
2372
os.environ['EXISTANT_ENV_VAR'] = 'set variable'
2373
self.check_popen_state = check_environment
2374
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2375
env_changes={'EXISTANT_ENV_VAR':None})
2376
# Still set in parent
2377
self.assertEqual('set variable', os.environ['EXISTANT_ENV_VAR'])
2378
del os.environ['EXISTANT_ENV_VAR']
2380
def test_env_del_missing(self):
2381
self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
2382
def check_environment():
2383
self.assertFalse('NON_EXISTANT_ENV_VAR' in os.environ)
2384
self.check_popen_state = check_environment
2385
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2386
env_changes={'NON_EXISTANT_ENV_VAR':None})
2388
def test_working_dir(self):
2389
"""Test that we can specify the working dir for the child"""
2390
orig_getcwd = osutils.getcwd
2391
orig_chdir = os.chdir
2399
osutils.getcwd = getcwd
2401
self.assertRaises(_DontSpawnProcess, self.start_bzr_subprocess, [],
2404
osutils.getcwd = orig_getcwd
2406
os.chdir = orig_chdir
2407
self.assertEqual(['foo', 'current'], chdirs)
2410
class TestActuallyStartBzrSubprocess(tests.TestCaseWithTransport):
2411
"""Tests that really need to do things with an external bzr."""
2413
def test_start_and_stop_bzr_subprocess_send_signal(self):
2414
"""finish_bzr_subprocess raises self.failureException if the retcode is
2415
not the expected one.
2417
self.disable_missing_extensions_warning()
2418
process = self.start_bzr_subprocess(['wait-until-signalled'],
2419
skip_if_plan_to_signal=True)
2420
self.assertEqual('running\n', process.stdout.readline())
2421
result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
2423
self.assertEqual('', result[0])
2424
self.assertEqual('bzr: interrupted\n', result[1])
1729
2427
class TestKnownFailure(tests.TestCase):