/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/blackbox/test_selftest.py

  • Committer: Aaron Bentley
  • Date: 2007-08-03 02:52:23 UTC
  • mto: This revision was merged to the branch mainline in revision 2700.
  • Revision ID: aaron.bentley@utoronto.ca-20070803025223-u0dfa0rwptw0gxy2
teach run_bzr_subprocess to accept either a list of strings or a string

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""UI tests for the test framework."""
18
18
 
 
19
import os
 
20
import re
 
21
import signal
 
22
import sys
 
23
 
 
24
import bzrlib
19
25
from bzrlib import (
20
 
    benchmarks,
21
 
    tests,
 
26
    osutils,
22
27
    )
 
28
from bzrlib.errors import ParamikoNotPresent
23
29
from bzrlib.tests import (
24
 
    features,
 
30
                          TestCase,
 
31
                          TestCaseInTempDir,
 
32
                          TestCaseWithMemoryTransport,
 
33
                          TestCaseWithTransport,
 
34
                          TestUIFactory,
 
35
                          TestSkipped,
 
36
                          )
 
37
from bzrlib.symbol_versioning import (
 
38
    zero_eighteen,
25
39
    )
26
 
from bzrlib.transport import memory
27
 
 
28
 
class SelfTestPatch:
29
 
 
30
 
    def get_params_passed_to_core(self, cmdline):
31
 
        params = []
32
 
        def selftest(*args, **kwargs):
33
 
            """Capture the arguments selftest was run with."""
34
 
            params.append((args, kwargs))
35
 
            return True
36
 
        # Yes this prevents using threads to run the test suite in parallel,
37
 
        # however we don't have a clean dependency injector for commands, 
38
 
        # and even if we did - we'd still be testing that the glue is wired
39
 
        # up correctly. XXX: TODO: Solve this testing problem.
40
 
        original_selftest = tests.selftest
41
 
        tests.selftest = selftest
42
 
        try:
43
 
            self.run_bzr(cmdline)
44
 
            return params[0]
 
40
from bzrlib.tests.blackbox import ExternalBase
 
41
 
 
42
 
 
43
class TestOptions(TestCase):
 
44
 
 
45
    current_test = None
 
46
 
 
47
    def test_transport_set_to_sftp(self):
 
48
        # test the --transport option has taken effect from within the
 
49
        # test_transport test
 
50
        try:
 
51
            import bzrlib.transport.sftp
 
52
        except ParamikoNotPresent:
 
53
            raise TestSkipped("Paramiko not present")
 
54
        if TestOptions.current_test != "test_transport_set_to_sftp":
 
55
            return
 
56
        self.assertEqual(bzrlib.transport.sftp.SFTPAbsoluteServer,
 
57
                         bzrlib.tests.default_transport)
 
58
 
 
59
    def test_transport_set_to_memory(self):
 
60
        # test the --transport option has taken effect from within the
 
61
        # test_transport test
 
62
        import bzrlib.transport.memory
 
63
        if TestOptions.current_test != "test_transport_set_to_memory":
 
64
            return
 
65
        self.assertEqual(bzrlib.transport.memory.MemoryServer,
 
66
                         bzrlib.tests.default_transport)
 
67
 
 
68
    def test_transport(self):
 
69
        # test that --transport=sftp works
 
70
        try:
 
71
            import bzrlib.transport.sftp
 
72
        except ParamikoNotPresent:
 
73
            raise TestSkipped("Paramiko not present")
 
74
        old_transport = bzrlib.tests.default_transport
 
75
        old_root = TestCaseWithMemoryTransport.TEST_ROOT
 
76
        TestCaseWithMemoryTransport.TEST_ROOT = None
 
77
        try:
 
78
            TestOptions.current_test = "test_transport_set_to_sftp"
 
79
            stdout = self.run_bzr(
 
80
                'selftest --transport=sftp test_transport_set_to_sftp')[0]
 
81
            self.assertContainsRe(stdout, 'Ran 1 test')
 
82
            self.assertEqual(old_transport, bzrlib.tests.default_transport)
 
83
 
 
84
            TestOptions.current_test = "test_transport_set_to_memory"
 
85
            stdout = self.run_bzr(
 
86
                'selftest --transport=memory test_transport_set_to_memory')[0]
 
87
            self.assertContainsRe(stdout, 'Ran 1 test')
 
88
            self.assertEqual(old_transport, bzrlib.tests.default_transport)
45
89
        finally:
46
 
            tests.selftest = original_selftest
47
 
 
48
 
 
49
 
class TestOptionsWritingToDisk(tests.TestCaseInTempDir, SelfTestPatch):
 
90
            bzrlib.tests.default_transport = old_transport
 
91
            TestOptions.current_test = None
 
92
            TestCaseWithMemoryTransport.TEST_ROOT = old_root
 
93
 
 
94
 
 
95
class TestRunBzr(ExternalBase):
 
96
 
 
97
    def _run_bzr_core(self, argv, retcode=0, encoding=None, stdin=None,
 
98
                         working_dir=None):
 
99
        """Override _run_bzr_core to test how it is invoked by run_bzr.
 
100
 
 
101
        Attempts to run bzr from inside this class don't actually run it.
 
102
 
 
103
        We test how run_bzr actually invokes bzr in another location.
 
104
        Here we only need to test that it is run_bzr passes the right
 
105
        parameters to run_bzr.
 
106
        """
 
107
        self.argv = list(argv)
 
108
        self.retcode = retcode
 
109
        self.encoding = encoding
 
110
        self.stdin = stdin
 
111
        self.working_dir = working_dir
 
112
        return '', ''
 
113
 
 
114
    def test_args(self):
 
115
        """Test that run_bzr passes args correctly to _run_bzr_core"""
 
116
        self.callDeprecated(
 
117
                ['passing varargs to run_bzr was deprecated in version 0.18.'],
 
118
                self.run_bzr,
 
119
                'arg1', 'arg2', 'arg3', retcode=1)
 
120
        self.assertEqual(['arg1', 'arg2', 'arg3'], self.argv)
 
121
 
 
122
    def test_encoding(self):
 
123
        """Test that run_bzr passes encoding to _run_bzr_core"""
 
124
        self.run_bzr('foo bar')
 
125
        self.assertEqual(None, self.encoding)
 
126
        self.assertEqual(['foo', 'bar'], self.argv)
 
127
 
 
128
        self.run_bzr('foo bar', encoding='baz')
 
129
        self.assertEqual('baz', self.encoding)
 
130
        self.assertEqual(['foo', 'bar'], self.argv)
 
131
 
 
132
    def test_retcode(self):
 
133
        """Test that run_bzr passes retcode to _run_bzr_core"""
 
134
        # Default is retcode == 0
 
135
        self.run_bzr('foo bar')
 
136
        self.assertEqual(0, self.retcode)
 
137
        self.assertEqual(['foo', 'bar'], self.argv)
 
138
 
 
139
        self.run_bzr('foo bar', retcode=1)
 
140
        self.assertEqual(1, self.retcode)
 
141
        self.assertEqual(['foo', 'bar'], self.argv)
 
142
 
 
143
        self.run_bzr('foo bar', retcode=None)
 
144
        self.assertEqual(None, self.retcode)
 
145
        self.assertEqual(['foo', 'bar'], self.argv)
 
146
 
 
147
        self.run_bzr(['foo', 'bar'], retcode=3)
 
148
        self.assertEqual(3, self.retcode)
 
149
        self.assertEqual(['foo', 'bar'], self.argv)
 
150
 
 
151
    def test_stdin(self):
 
152
        # test that the stdin keyword to run_bzr is passed through to
 
153
        # _run_bzr_core as-is. We do this by overriding
 
154
        # _run_bzr_core in this class, and then calling run_bzr,
 
155
        # which is a convenience function for _run_bzr_core, so 
 
156
        # should invoke it.
 
157
        self.run_bzr('foo bar', stdin='gam')
 
158
        self.assertEqual('gam', self.stdin)
 
159
        self.assertEqual(['foo', 'bar'], self.argv)
 
160
 
 
161
        self.run_bzr('foo bar', stdin='zippy')
 
162
        self.assertEqual('zippy', self.stdin)
 
163
        self.assertEqual(['foo', 'bar'], self.argv)
 
164
 
 
165
    def test_working_dir(self):
 
166
        """Test that run_bzr passes working_dir to _run_bzr_core"""
 
167
        self.run_bzr('foo bar')
 
168
        self.assertEqual(None, self.working_dir)
 
169
        self.assertEqual(['foo', 'bar'], self.argv)
 
170
 
 
171
        self.run_bzr('foo bar', working_dir='baz')
 
172
        self.assertEqual('baz', self.working_dir)
 
173
        self.assertEqual(['foo', 'bar'], self.argv)
 
174
 
 
175
 
 
176
class TestBenchmarkTests(TestCaseWithTransport):
50
177
 
51
178
    def test_benchmark_runs_benchmark_tests(self):
52
 
        """selftest --benchmark should change the suite factory."""
53
 
        params = self.get_params_passed_to_core('selftest --benchmark')
54
 
        self.assertEqual(benchmarks.test_suite,
55
 
            params[1]['test_suite_factory'])
56
 
        self.assertNotEqual(None, params[1]['bench_history'])
 
179
        """bzr selftest --benchmark should not run the default test suite."""
 
180
        # We test this by passing a regression test name to --benchmark, which
 
181
        # should result in 0 rests run.
 
182
        old_root = TestCaseWithMemoryTransport.TEST_ROOT
 
183
        try:
 
184
            TestCaseWithMemoryTransport.TEST_ROOT = None
 
185
            out, err = self.run_bzr('selftest --benchmark'
 
186
                                    ' workingtree_implementations')
 
187
        finally:
 
188
            TestCaseWithMemoryTransport.TEST_ROOT = old_root
 
189
        self.assertContainsRe(out, 'Ran 0 tests.*\n\nOK')
 
190
        self.assertEqual(
 
191
            'tests passed\n',
 
192
            err)
57
193
        benchfile = open(".perf_history", "rt")
58
194
        try:
59
195
            lines = benchfile.readlines()
60
196
        finally:
61
197
            benchfile.close()
62
 
        # Because we don't run the actual test code no output is made to the
63
 
        # file.
64
 
        self.assertEqual(0, len(lines))
65
 
 
66
 
 
67
 
class TestOptions(tests.TestCase, SelfTestPatch):
68
 
 
69
 
    def test_load_list(self):
70
 
        params = self.get_params_passed_to_core('selftest --load-list foo')
71
 
        self.assertEqual('foo', params[1]['load_list'])
72
 
 
73
 
    def test_transport_set_to_sftp(self):
74
 
        # Test that we can pass a transport to the selftest core - sftp
75
 
        # version.
76
 
        self.requireFeature(features.paramiko)
77
 
        from bzrlib.tests import stub_sftp
78
 
        params = self.get_params_passed_to_core('selftest --transport=sftp')
79
 
        self.assertEqual(stub_sftp.SFTPAbsoluteServer,
80
 
            params[1]["transport"])
81
 
 
82
 
    def test_transport_set_to_memory(self):
83
 
        # Test that we can pass a transport to the selftest core - memory
84
 
        # version.
85
 
        params = self.get_params_passed_to_core('selftest --transport=memory')
86
 
        self.assertEqual(memory.MemoryServer, params[1]["transport"])
87
 
 
88
 
    def test_parameters_passed_to_core(self):
89
 
        params = self.get_params_passed_to_core('selftest --list-only')
90
 
        self.assertTrue("list_only" in params[1])
91
 
        params = self.get_params_passed_to_core('selftest --list-only selftest')
92
 
        self.assertTrue("list_only" in params[1])
93
 
        params = self.get_params_passed_to_core(['selftest', '--list-only',
94
 
            '--exclude', 'selftest'])
95
 
        self.assertTrue("list_only" in params[1])
96
 
        params = self.get_params_passed_to_core(['selftest', '--list-only',
97
 
            'selftest', '--randomize', 'now'])
98
 
        self.assertSubset(["list_only", "random_seed"], params[1])
99
 
 
100
 
    def test_starting_with(self):
101
 
        params = self.get_params_passed_to_core('selftest --starting-with foo')
102
 
        self.assertEqual(['foo'], params[1]['starting_with'])
103
 
 
104
 
    def test_starting_with_multiple_argument(self):
105
 
        params = self.get_params_passed_to_core(
106
 
            'selftest --starting-with foo --starting-with bar')
107
 
        self.assertEqual(['foo', 'bar'], params[1]['starting_with'])
108
 
 
109
 
    def test_subunit(self):
110
 
        self.requireFeature(features.subunit)
111
 
        params = self.get_params_passed_to_core('selftest --subunit')
112
 
        self.assertEqual(tests.SubUnitBzrRunner, params[1]['runner_class'])
113
 
 
114
 
    def _parse_test_list(self, lines, newlines_in_header=0):
 
198
        self.assertEqual(1, len(lines))
 
199
        self.assertContainsRe(lines[0], "--date [0-9.]+")
 
200
 
 
201
 
 
202
class TestRunBzrCaptured(ExternalBase):
 
203
 
 
204
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
205
                         a_callable=None, *args, **kwargs):
 
206
        self.stdin = stdin
 
207
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
 
208
        self.factory = bzrlib.ui.ui_factory
 
209
        self.working_dir = osutils.getcwd()
 
210
        stdout.write('foo\n')
 
211
        stderr.write('bar\n')
 
212
        return 0
 
213
 
 
214
    def test_stdin(self):
 
215
        # test that the stdin keyword to _run_bzr_core is passed through to
 
216
        # apply_redirected as a StringIO. We do this by overriding
 
217
        # apply_redirected in this class, and then calling _run_bzr_core,
 
218
        # which calls apply_redirected. 
 
219
        self.run_bzr(['foo', 'bar'], stdin='gam')
 
220
        self.assertEqual('gam', self.stdin.read())
 
221
        self.assertTrue(self.stdin is self.factory_stdin)
 
222
        self.run_bzr(['foo', 'bar'], stdin='zippy')
 
223
        self.assertEqual('zippy', self.stdin.read())
 
224
        self.assertTrue(self.stdin is self.factory_stdin)
 
225
 
 
226
    def test_ui_factory(self):
 
227
        # each invocation of self.run_bzr should get its
 
228
        # own UI factory, which is an instance of TestUIFactory,
 
229
        # with stdin, stdout and stderr attached to the stdin,
 
230
        # stdout and stderr of the invoked run_bzr
 
231
        current_factory = bzrlib.ui.ui_factory
 
232
        self.run_bzr(['foo'])
 
233
        self.failIf(current_factory is self.factory)
 
234
        self.assertNotEqual(sys.stdout, self.factory.stdout)
 
235
        self.assertNotEqual(sys.stderr, self.factory.stderr)
 
236
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
 
237
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
 
238
        self.assertIsInstance(self.factory, TestUIFactory)
 
239
 
 
240
    def test_working_dir(self):
 
241
        self.build_tree(['one/', 'two/'])
 
242
        cwd = osutils.getcwd()
 
243
 
 
244
        # Default is to work in the current directory
 
245
        self.run_bzr(['foo', 'bar'])
 
246
        self.assertEqual(cwd, self.working_dir)
 
247
 
 
248
        self.run_bzr(['foo', 'bar'], working_dir=None)
 
249
        self.assertEqual(cwd, self.working_dir)
 
250
 
 
251
        # The function should be run in the alternative directory
 
252
        # but afterwards the current working dir shouldn't be changed
 
253
        self.run_bzr(['foo', 'bar'], working_dir='one')
 
254
        self.assertNotEqual(cwd, self.working_dir)
 
255
        self.assertEndsWith(self.working_dir, 'one')
 
256
        self.assertEqual(cwd, osutils.getcwd())
 
257
 
 
258
        self.run_bzr(['foo', 'bar'], working_dir='two')
 
259
        self.assertNotEqual(cwd, self.working_dir)
 
260
        self.assertEndsWith(self.working_dir, 'two')
 
261
        self.assertEqual(cwd, osutils.getcwd())
 
262
 
 
263
 
 
264
class TestRunBzrSubprocess(TestCaseWithTransport):
 
265
 
 
266
    def test_run_bzr_subprocess(self):
 
267
        """The run_bzr_helper_external comand behaves nicely."""
 
268
        result = self.run_bzr_subprocess('--version')
 
269
        result = self.run_bzr_subprocess(['--version'])
 
270
        result = self.run_bzr_subprocess('--version', retcode=None)
 
271
        self.assertContainsRe(result[0], 'is free software')
 
272
        self.assertRaises(AssertionError, self.run_bzr_subprocess, 
 
273
                          '--versionn')
 
274
        result = self.run_bzr_subprocess('--versionn', retcode=3)
 
275
        result = self.run_bzr_subprocess('--versionn', retcode=None)
 
276
        self.assertContainsRe(result[1], 'unknown command')
 
277
        err = self.run_bzr_subprocess('merge --merge-type magic\ merge',
 
278
                                      retcode=3)[1]
 
279
        self.assertContainsRe(err, 'Bad value "magic merge" for option'
 
280
                              ' "merge-type"')
 
281
 
 
282
    def test_run_bzr_subprocess_env(self):
 
283
        """run_bzr_subprocess can set environment variables in the child only.
 
284
 
 
285
        These changes should not change the running process, only the child.
 
286
        """
 
287
        # The test suite should unset this variable
 
288
        self.assertEqual(None, os.environ.get('BZR_EMAIL'))
 
289
        out, err = self.run_bzr_subprocess('whoami', env_changes={
 
290
                                            'BZR_EMAIL':'Joe Foo <joe@foo.com>'
 
291
                                          }, universal_newlines=True)
 
292
        self.assertEqual('', err)
 
293
        self.assertEqual('Joe Foo <joe@foo.com>\n', out)
 
294
        # And it should not be modified
 
295
        self.assertEqual(None, os.environ.get('BZR_EMAIL'))
 
296
 
 
297
        # Do it again with a different address, just to make sure
 
298
        # it is actually changing
 
299
        out, err = self.run_bzr_subprocess('whoami', env_changes={
 
300
                                            'BZR_EMAIL':'Barry <bar@foo.com>'
 
301
                                          }, universal_newlines=True)
 
302
        self.assertEqual('', err)
 
303
        self.assertEqual('Barry <bar@foo.com>\n', out)
 
304
        self.assertEqual(None, os.environ.get('BZR_EMAIL'))
 
305
 
 
306
    def test_run_bzr_subprocess_env_del(self):
 
307
        """run_bzr_subprocess can remove environment variables too."""
 
308
        # Create a random email, so we are sure this won't collide
 
309
        rand_bzr_email = 'John Doe <jdoe@%s.com>' % (osutils.rand_chars(20),)
 
310
        rand_email = 'Jane Doe <jdoe@%s.com>' % (osutils.rand_chars(20),)
 
311
        os.environ['BZR_EMAIL'] = rand_bzr_email
 
312
        os.environ['EMAIL'] = rand_email
 
313
        try:
 
314
            # By default, the child will inherit the current env setting
 
315
            out, err = self.run_bzr_subprocess('whoami', universal_newlines=True)
 
316
            self.assertEqual('', err)
 
317
            self.assertEqual(rand_bzr_email + '\n', out)
 
318
 
 
319
            # Now that BZR_EMAIL is not set, it should fall back to EMAIL
 
320
            out, err = self.run_bzr_subprocess('whoami',
 
321
                                               env_changes={'BZR_EMAIL':None},
 
322
                                               universal_newlines=True)
 
323
            self.assertEqual('', err)
 
324
            self.assertEqual(rand_email + '\n', out)
 
325
 
 
326
            # This switches back to the default email guessing logic
 
327
            # Which shouldn't match either of the above addresses
 
328
            out, err = self.run_bzr_subprocess('whoami',
 
329
                           env_changes={'BZR_EMAIL':None, 'EMAIL':None},
 
330
                           universal_newlines=True)
 
331
 
 
332
            self.assertEqual('', err)
 
333
            self.assertNotEqual(rand_bzr_email + '\n', out)
 
334
            self.assertNotEqual(rand_email + '\n', out)
 
335
        finally:
 
336
            # TestCase cleans up BZR_EMAIL, and EMAIL at startup
 
337
            del os.environ['BZR_EMAIL']
 
338
            del os.environ['EMAIL']
 
339
 
 
340
    def test_run_bzr_subprocess_env_del_missing(self):
 
341
        """run_bzr_subprocess won't fail if deleting a nonexistant env var"""
 
342
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
 
343
        out, err = self.run_bzr_subprocess('rocks',
 
344
                        env_changes={'NON_EXISTANT_ENV_VAR':None},
 
345
                        universal_newlines=True)
 
346
        self.assertEqual('It sure does!\n', out)
 
347
        self.assertEqual('', err)
 
348
 
 
349
    def test_run_bzr_subprocess_working_dir(self):
 
350
        """Test that we can specify the working dir for the child"""
 
351
        cwd = osutils.getcwd()
 
352
 
 
353
        self.make_branch_and_tree('.')
 
354
        self.make_branch_and_tree('one')
 
355
        self.make_branch_and_tree('two')
 
356
 
 
357
        def get_root(**kwargs):
 
358
            """Spawn a process to get the 'root' of the tree.
 
359
 
 
360
            You can pass in arbitrary new arguments. This just makes
 
361
            sure that the returned path doesn't have trailing whitespace.
 
362
            """
 
363
            return self.run_bzr_subprocess('root', **kwargs)[0].rstrip()
 
364
 
 
365
        self.assertEqual(cwd, get_root())
 
366
        self.assertEqual(cwd, get_root(working_dir=None))
 
367
        # Has our path changed?
 
368
        self.assertEqual(cwd, osutils.getcwd())
 
369
 
 
370
        dir1 = get_root(working_dir='one')
 
371
        self.assertEndsWith(dir1, 'one')
 
372
        self.assertEqual(cwd, osutils.getcwd())
 
373
 
 
374
        dir2 = get_root(working_dir='two')
 
375
        self.assertEndsWith(dir2, 'two')
 
376
        self.assertEqual(cwd, osutils.getcwd())
 
377
 
 
378
 
 
379
class _DontSpawnProcess(Exception):
 
380
    """A simple exception which just allows us to skip unnecessary steps"""
 
381
 
 
382
 
 
383
class TestRunBzrSubprocessCommands(TestCaseWithTransport):
 
384
 
 
385
    def _popen(self, *args, **kwargs):
 
386
        """Record the command that is run, so that we can ensure it is correct"""
 
387
        self._popen_args = args
 
388
        self._popen_kwargs = kwargs
 
389
        raise _DontSpawnProcess()
 
390
 
 
391
    def test_run_bzr_subprocess_no_plugins(self):
 
392
        self.assertRaises(_DontSpawnProcess, self.run_bzr_subprocess, '')
 
393
        command = self._popen_args[0]
 
394
        self.assertEqual(sys.executable, command[0])
 
395
        self.assertEqual(self.get_bzr_path(), command[1])
 
396
        self.assertEqual(['--no-plugins'], command[2:])
 
397
 
 
398
    def test_allow_plugins(self):
 
399
        self.assertRaises(_DontSpawnProcess,
 
400
                          self.run_bzr_subprocess, '', allow_plugins=True)
 
401
        command = self._popen_args[0]
 
402
        self.assertEqual([], command[2:])
 
403
 
 
404
 
 
405
class TestBzrSubprocess(TestCaseWithTransport):
 
406
 
 
407
    def test_start_and_stop_bzr_subprocess(self):
 
408
        """We can start and perform other test actions while that process is
 
409
        still alive.
 
410
        """
 
411
        process = self.start_bzr_subprocess(['--version'])
 
412
        result = self.finish_bzr_subprocess(process)
 
413
        self.assertContainsRe(result[0], 'is free software')
 
414
        self.assertEqual('', result[1])
 
415
 
 
416
    def test_start_and_stop_bzr_subprocess_with_error(self):
 
417
        """finish_bzr_subprocess allows specification of the desired exit code.
 
418
        """
 
419
        process = self.start_bzr_subprocess(['--versionn'])
 
420
        result = self.finish_bzr_subprocess(process, retcode=3)
 
421
        self.assertEqual('', result[0])
 
422
        self.assertContainsRe(result[1], 'unknown command')
 
423
 
 
424
    def test_start_and_stop_bzr_subprocess_ignoring_retcode(self):
 
425
        """finish_bzr_subprocess allows the exit code to be ignored."""
 
426
        process = self.start_bzr_subprocess(['--versionn'])
 
427
        result = self.finish_bzr_subprocess(process, retcode=None)
 
428
        self.assertEqual('', result[0])
 
429
        self.assertContainsRe(result[1], 'unknown command')
 
430
 
 
431
    def test_start_and_stop_bzr_subprocess_with_unexpected_retcode(self):
 
432
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
433
        not the expected one.
 
434
        """
 
435
        process = self.start_bzr_subprocess(['--versionn'])
 
436
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
 
437
                          process)
 
438
        
 
439
    def test_start_and_stop_bzr_subprocess_send_signal(self):
 
440
        """finish_bzr_subprocess raises self.failureException if the retcode is
 
441
        not the expected one.
 
442
        """
 
443
        process = self.start_bzr_subprocess(['wait-until-signalled'],
 
444
                                            skip_if_plan_to_signal=True)
 
445
        self.assertEqual('running\n', process.stdout.readline())
 
446
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
 
447
                                            retcode=3)
 
448
        self.assertEqual('', result[0])
 
449
        self.assertEqual('bzr: interrupted\n', result[1])
 
450
 
 
451
    def test_start_and_stop_working_dir(self):
 
452
        cwd = osutils.getcwd()
 
453
 
 
454
        self.make_branch_and_tree('one')
 
455
 
 
456
        process = self.start_bzr_subprocess(['root'], working_dir='one')
 
457
        result = self.finish_bzr_subprocess(process, universal_newlines=True)
 
458
        self.assertEndsWith(result[0], 'one\n')
 
459
        self.assertEqual('', result[1])
 
460
 
 
461
 
 
462
class TestRunBzrError(ExternalBase):
 
463
 
 
464
    def test_run_bzr_error(self):
 
465
        # retcode=0 is specially needed here because run_bzr_error expects
 
466
        # an error (oddly enough) but we want to test the case of not
 
467
        # actually getting one
 
468
        out, err = self.run_bzr_error(['^$'], ['rocks'], retcode=0)
 
469
        self.assertEqual(out, 'It sure does!\n')
 
470
        # now test actually getting an error
 
471
        out, err = self.run_bzr_error(
 
472
                ["bzr: ERROR: foobarbaz is not versioned"],
 
473
                ['file-id', 'foobarbaz'])
 
474
 
 
475
 
 
476
class TestSelftestListOnly(TestCase):
 
477
 
 
478
    @staticmethod
 
479
    def _parse_test_list(lines, newlines_in_header=1):
115
480
        "Parse a list of lines into a tuple of 3 lists (header,body,footer)."
116
 
        in_header = newlines_in_header != 0
 
481
 
 
482
        in_header = True
117
483
        in_footer = False
118
484
        header = []
119
485
        body = []
120
486
        footer = []
121
 
        header_newlines_found = 0
 
487
        header_newlines_found = 0 
122
488
        for line in lines:
123
489
            if in_header:
124
490
                if line == '':
136
502
                footer.append(line)
137
503
        # If the last body line is blank, drop it off the list
138
504
        if len(body) > 0 and body[-1] == '':
139
 
            body.pop()
 
505
            body.pop()                
140
506
        return (header,body,footer)
141
507
 
142
508
    def test_list_only(self):
143
 
        # check that bzr selftest --list-only outputs no ui noise
144
 
        def selftest(*args, **kwargs):
145
 
            """Capture the arguments selftest was run with."""
146
 
            return True
147
 
        def outputs_nothing(cmdline):
148
 
            out,err = self.run_bzr(cmdline)
149
 
            (header,body,footer) = self._parse_test_list(out.splitlines())
150
 
            num_tests = len(body)
151
 
            self.assertLength(0, header)
152
 
            self.assertLength(0, footer)
153
 
            self.assertEqual('', err)
154
 
        # Yes this prevents using threads to run the test suite in parallel,
155
 
        # however we don't have a clean dependency injector for commands, 
156
 
        # and even if we did - we'd still be testing that the glue is wired
157
 
        # up correctly. XXX: TODO: Solve this testing problem.
158
 
        original_selftest = tests.selftest
159
 
        tests.selftest = selftest
160
 
        try:
161
 
            outputs_nothing('selftest --list-only')
162
 
            outputs_nothing('selftest --list-only selftest')
163
 
            outputs_nothing(['selftest', '--list-only', '--exclude', 'selftest'])
164
 
        finally:
165
 
            tests.selftest = original_selftest
166
 
 
167
 
    def test_lsprof_tests(self):
168
 
        params = self.get_params_passed_to_core('selftest --lsprof-tests')
169
 
        self.assertEqual(True, params[1]["lsprof_tests"])
 
509
        # check that bzr selftest --list-only works correctly
 
510
        out,err = self.run_bzr('selftest selftest --list-only')
 
511
        self.assertEndsWith(err, 'tests passed\n')
 
512
        (header,body,footer) = self._parse_test_list(out.splitlines())
 
513
        num_tests = len(body)
 
514
        self.assertContainsRe(footer[0], 'Listed %s tests in' % num_tests)
 
515
 
 
516
    def test_list_only_filtered(self):
 
517
        # check that a filtered --list-only works, both include and exclude
 
518
        out_all,err_all = self.run_bzr('selftest --list-only')
 
519
        tests_all = self._parse_test_list(out_all.splitlines())[1]
 
520
        out_incl,err_incl = self.run_bzr('selftest --list-only selftest')
 
521
        tests_incl = self._parse_test_list(out_incl.splitlines())[1]
 
522
        self.assertSubset(tests_incl, tests_all)
 
523
        out_excl,err_excl = self.run_bzr(['selftest', '--list-only',
 
524
                                          '--exclude', 'selftest'])
 
525
        tests_excl = self._parse_test_list(out_excl.splitlines())[1]
 
526
        self.assertSubset(tests_excl, tests_all)
 
527
        set_incl = set(tests_incl)
 
528
        set_excl = set(tests_excl)
 
529
        intersection = set_incl.intersection(set_excl)
 
530
        self.assertEquals(0, len(intersection))
 
531
        self.assertEquals(len(tests_all), len(tests_incl) + len(tests_excl))
 
532
 
 
533
    def test_list_only_random(self):
 
534
        # check that --randomize works correctly
 
535
        out_all,err_all = self.run_bzr('selftest --list-only selftest')
 
536
        tests_all = self._parse_test_list(out_all.splitlines())[1]
 
537
        # XXX: It looks like there are some orders for generating tests that
 
538
        # fail as of 20070504 - maybe because of import order dependencies.
 
539
        # So unfortunately this will rarely intermittently fail at the moment.
 
540
        # -- mbp 20070504
 
541
        out_rand,err_rand = self.run_bzr(['selftest', '--list-only',
 
542
                                          'selftest', '--randomize', 'now'])
 
543
        (header_rand,tests_rand,dummy) = self._parse_test_list(
 
544
            out_rand.splitlines(), 2)
 
545
        self.assertNotEqual(tests_all, tests_rand)
 
546
        self.assertEqual(sorted(tests_all), sorted(tests_rand))
 
547
        # Check that the seed can be reused to get the exact same order
 
548
        seed_re = re.compile('Randomizing test order using seed (\w+)')
 
549
        match_obj = seed_re.search(header_rand[-1])
 
550
        seed = match_obj.group(1)
 
551
        out_rand2,err_rand2 = self.run_bzr(['selftest', '--list-only',
 
552
                                            'selftest', '--randomize', seed])
 
553
        (header_rand2,tests_rand2,dummy) = self._parse_test_list(
 
554
            out_rand2.splitlines(), 2)
 
555
        self.assertEqual(tests_rand, tests_rand2)
 
556