~bzr-pqm/bzr/bzr.dev

2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2005 Canonical Ltd
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
2
#
3
# This program is free software; you can redistribute it and/or modify
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""UI tests for the test framework."""
18
1963.1.1 by John Arbash Meinel
run_bzr_subprocess() can take an env_changes parameter
19
import os
2394.2.5 by Ian Clatworthy
list-only working, include test not
20
import re
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
21
import signal
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
22
import sys
23
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
24
import bzrlib
1963.1.2 by John Arbash Meinel
Cleanups suggested by Martin, add test that env_changes can remove an env variable
25
from bzrlib import (
26
    osutils,
27
    )
2394.2.3 by Ian Clatworthy
Backed out test junk
28
from bzrlib.errors import ParamikoNotPresent
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
29
from bzrlib.tests import (
30
                          TestCase,
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
31
                          TestCaseInTempDir,
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
32
                          TestCaseWithMemoryTransport,
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
33
                          TestCaseWithTransport,
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
34
                          TestUIFactory,
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
35
                          TestSkipped,
36
                          )
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
37
from bzrlib.tests.blackbox import ExternalBase
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
38
39
40
class TestOptions(TestCase):
41
42
    current_test = None
43
44
    def test_transport_set_to_sftp(self):
45
        # test the --transport option has taken effect from within the
46
        # test_transport test
1551.2.47 by abentley
Fixed test_selftest's use of sftp
47
        try:
48
            import bzrlib.transport.sftp
49
        except ParamikoNotPresent:
50
            raise TestSkipped("Paramiko not present")
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
51
        if TestOptions.current_test != "test_transport_set_to_sftp":
52
            return
53
        self.assertEqual(bzrlib.transport.sftp.SFTPAbsoluteServer,
54
                         bzrlib.tests.default_transport)
55
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
56
    def test_transport_set_to_memory(self):
57
        # test the --transport option has taken effect from within the
58
        # test_transport test
59
        import bzrlib.transport.memory
60
        if TestOptions.current_test != "test_transport_set_to_memory":
61
            return
62
        self.assertEqual(bzrlib.transport.memory.MemoryServer,
63
                         bzrlib.tests.default_transport)
64
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
65
    def test_transport(self):
66
        # test that --transport=sftp works
1551.2.47 by abentley
Fixed test_selftest's use of sftp
67
        try:
68
            import bzrlib.transport.sftp
69
        except ParamikoNotPresent:
70
            raise TestSkipped("Paramiko not present")
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
71
        old_transport = bzrlib.tests.default_transport
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
72
        old_root = TestCaseWithMemoryTransport.TEST_ROOT
73
        TestCaseWithMemoryTransport.TEST_ROOT = None
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
74
        try:
75
            TestOptions.current_test = "test_transport_set_to_sftp"
76
            stdout = self.capture('selftest --transport=sftp test_transport_set_to_sftp')
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
77
            
78
            self.assertContainsRe(stdout, 'Ran 1 test')
79
            self.assertEqual(old_transport, bzrlib.tests.default_transport)
80
81
            TestOptions.current_test = "test_transport_set_to_memory"
82
            stdout = self.capture('selftest --transport=memory test_transport_set_to_memory')
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
83
            self.assertContainsRe(stdout, 'Ran 1 test')
84
            self.assertEqual(old_transport, bzrlib.tests.default_transport)
85
        finally:
86
            bzrlib.tests.default_transport = old_transport
87
            TestOptions.current_test = None
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
88
            TestCaseWithMemoryTransport.TEST_ROOT = old_root
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
89
90
91
class TestRunBzr(ExternalBase):
92
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
93
    def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None,
94
                         working_dir=None):
2027.5.3 by John Arbash Meinel
Add docstring to why run_bzr_captured is overridden
95
        """Override run_bzr_captured to test how it is invoked by run_bzr.
96
97
        We test how run_bzr_captured actually invokes bzr in another location.
98
        Here we only need to test that it is run_bzr passes the right
99
        parameters to run_bzr_captured.
100
        """
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
101
        self.argv = argv
102
        self.retcode = retcode
103
        self.encoding = encoding
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
104
        self.stdin = stdin
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
105
        self.working_dir = working_dir
2292.1.28 by Marius Kruger
* NEWS
106
        return '', ''
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
107
108
    def test_args(self):
109
        """Test that run_bzr passes args correctly to run_bzr_captured"""
110
        self.run_bzr('arg1', 'arg2', 'arg3', retcode=1)
111
        self.assertEqual(('arg1', 'arg2', 'arg3'), self.argv)
112
113
    def test_encoding(self):
114
        """Test that run_bzr passes encoding to run_bzr_captured"""
115
        self.run_bzr('foo', 'bar')
116
        self.assertEqual(None, self.encoding)
117
        self.assertEqual(('foo', 'bar'), self.argv)
118
119
        self.run_bzr('foo', 'bar', encoding='baz')
120
        self.assertEqual('baz', self.encoding)
121
        self.assertEqual(('foo', 'bar'), self.argv)
122
123
    def test_retcode(self):
124
        """Test that run_bzr passes retcode to run_bzr_captured"""
125
        # Default is retcode == 0
126
        self.run_bzr('foo', 'bar')
127
        self.assertEqual(0, self.retcode)
128
        self.assertEqual(('foo', 'bar'), self.argv)
129
130
        self.run_bzr('foo', 'bar', retcode=1)
131
        self.assertEqual(1, self.retcode)
132
        self.assertEqual(('foo', 'bar'), self.argv)
133
134
        self.run_bzr('foo', 'bar', retcode=None)
135
        self.assertEqual(None, self.retcode)
136
        self.assertEqual(('foo', 'bar'), self.argv)
137
138
        self.run_bzr('foo', 'bar', retcode=3)
139
        self.assertEqual(3, self.retcode)
140
        self.assertEqual(('foo', 'bar'), self.argv)
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
141
142
    def test_stdin(self):
143
        # test that the stdin keyword to run_bzr is passed through to
1687.1.15 by Robert Collins
Review comments.
144
        # run_bzr_captured as-is. We do this by overriding
145
        # run_bzr_captured in this class, and then calling run_bzr,
146
        # which is a convenience function for run_bzr_captured, so 
147
        # should invoke it.
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
148
        self.run_bzr('foo', 'bar', stdin='gam')
149
        self.assertEqual('gam', self.stdin)
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
150
        self.assertEqual(('foo', 'bar'), self.argv)
151
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
152
        self.run_bzr('foo', 'bar', stdin='zippy')
153
        self.assertEqual('zippy', self.stdin)
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
154
        self.assertEqual(('foo', 'bar'), self.argv)
155
156
    def test_working_dir(self):
157
        """Test that run_bzr passes working_dir to run_bzr_captured"""
158
        self.run_bzr('foo', 'bar')
159
        self.assertEqual(None, self.working_dir)
160
        self.assertEqual(('foo', 'bar'), self.argv)
161
162
        self.run_bzr('foo', 'bar', working_dir='baz')
163
        self.assertEqual('baz', self.working_dir)
164
        self.assertEqual(('foo', 'bar'), self.argv)
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
165
166
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
167
class TestBenchmarkTests(TestCaseWithTransport):
168
169
    def test_benchmark_runs_benchmark_tests(self):
170
        """bzr selftest --benchmark should not run the default test suite."""
171
        # We test this by passing a regression test name to --benchmark, which
172
        # should result in 0 rests run.
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
173
        old_root = TestCaseWithMemoryTransport.TEST_ROOT
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
174
        try:
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
175
            TestCaseWithMemoryTransport.TEST_ROOT = None
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
176
            out, err = self.run_bzr('selftest', '--benchmark', 'workingtree_implementations')
177
        finally:
1986.2.3 by Robert Collins
New test base class TestCaseWithMemoryTransport offers memory-only
178
            TestCaseWithMemoryTransport.TEST_ROOT = old_root
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
179
        self.assertContainsRe(out, 'Ran 0 tests.*\n\nOK')
180
        self.assertEqual(
2095.4.1 by Martin Pool
Better progress bars during tests
181
            'tests passed\n',
1819.1.3 by Carl Friedrich Bolz
(lifeless, cfbolz): Add recording of benchmark results to the benchmark history
182
            err)
183
        benchfile = open(".perf_history", "rt")
184
        try:
185
            lines = benchfile.readlines()
186
        finally:
187
            benchfile.close()
188
        self.assertEqual(1, len(lines))
189
        self.assertContainsRe(lines[0], "--date [0-9.]+")
190
191
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
192
class TestRunBzrCaptured(ExternalBase):
193
194
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
195
                         a_callable=None, *args, **kwargs):
196
        self.stdin = stdin
1687.1.11 by Robert Collins
Teach TestCase.run_bzr_captured about the ui factories.
197
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
198
        self.factory = bzrlib.ui.ui_factory
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
199
        self.working_dir = osutils.getcwd()
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
200
        stdout.write('foo\n')
201
        stderr.write('bar\n')
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
202
        return 0
203
204
    def test_stdin(self):
205
        # test that the stdin keyword to run_bzr_captured is passed through to
1687.1.15 by Robert Collins
Review comments.
206
        # apply_redirected as a StringIO. We do this by overriding
207
        # apply_redirected in this class, and then calling run_bzr_captured,
208
        # which calls apply_redirected. 
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
209
        self.run_bzr_captured(['foo', 'bar'], stdin='gam')
210
        self.assertEqual('gam', self.stdin.read())
1687.1.11 by Robert Collins
Teach TestCase.run_bzr_captured about the ui factories.
211
        self.assertTrue(self.stdin is self.factory_stdin)
1687.1.2 by Robert Collins
Add stdin parameter to run_bzr and run_bzr_captured.
212
        self.run_bzr_captured(['foo', 'bar'], stdin='zippy')
213
        self.assertEqual('zippy', self.stdin.read())
1687.1.11 by Robert Collins
Teach TestCase.run_bzr_captured about the ui factories.
214
        self.assertTrue(self.stdin is self.factory_stdin)
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
215
216
    def test_ui_factory(self):
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
217
        # each invocation of self.run_bzr_captured should get its
218
        # own UI factory, which is an instance of TestUIFactory,
219
        # with stdin, stdout and stderr attached to the stdin,
220
        # stdout and stderr of the invoked run_bzr_captured
1692.3.3 by Robert Collins
Get run_bzr in tests to always assign a new, clean ui factory.
221
        current_factory = bzrlib.ui.ui_factory
222
        self.run_bzr_captured(['foo'])
223
        self.failIf(current_factory is self.factory)
224
        self.assertNotEqual(sys.stdout, self.factory.stdout)
225
        self.assertNotEqual(sys.stderr, self.factory.stderr)
226
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
227
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
2294.4.4 by Vincent Ladeuil
Provide a better implementation for testing passwords.
228
        self.assertIsInstance(self.factory, TestUIFactory)
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
229
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
230
    def test_working_dir(self):
231
        self.build_tree(['one/', 'two/'])
232
        cwd = osutils.getcwd()
233
234
        # Default is to work in the current directory
235
        self.run_bzr_captured(['foo', 'bar'])
236
        self.assertEqual(cwd, self.working_dir)
237
238
        self.run_bzr_captured(['foo', 'bar'], working_dir=None)
239
        self.assertEqual(cwd, self.working_dir)
240
2027.5.2 by John Arbash Meinel
add tests that the working directory is preserved, cleanup run_bzr_subprocess
241
        # The function should be run in the alternative directory
242
        # but afterwards the current working dir shouldn't be changed
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
243
        self.run_bzr_captured(['foo', 'bar'], working_dir='one')
244
        self.assertNotEqual(cwd, self.working_dir)
245
        self.assertEndsWith(self.working_dir, 'one')
2027.5.2 by John Arbash Meinel
add tests that the working directory is preserved, cleanup run_bzr_subprocess
246
        self.assertEqual(cwd, osutils.getcwd())
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
247
248
        self.run_bzr_captured(['foo', 'bar'], working_dir='two')
249
        self.assertNotEqual(cwd, self.working_dir)
250
        self.assertEndsWith(self.working_dir, 'two')
2027.5.2 by John Arbash Meinel
add tests that the working directory is preserved, cleanup run_bzr_subprocess
251
        self.assertEqual(cwd, osutils.getcwd())
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
252
253
254
class TestRunBzrSubprocess(TestCaseWithTransport):
255
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
256
    def test_run_bzr_subprocess(self):
257
        """The run_bzr_helper_external comand behaves nicely."""
258
        result = self.run_bzr_subprocess('--version')
259
        result = self.run_bzr_subprocess('--version', retcode=None)
260
        self.assertContainsRe(result[0], 'is free software')
261
        self.assertRaises(AssertionError, self.run_bzr_subprocess, 
262
                          '--versionn')
263
        result = self.run_bzr_subprocess('--versionn', retcode=3)
264
        result = self.run_bzr_subprocess('--versionn', retcode=None)
265
        self.assertContainsRe(result[1], 'unknown command')
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
266
        err = self.run_bzr_subprocess('merge', '--merge-type', 'magic merge', 
267
                                      retcode=3)[1]
2221.4.15 by Aaron Bentley
Use RegistryOption for merge type
268
        self.assertContainsRe(err, 'Bad value "magic merge" for option'
269
                              ' "merge-type"')
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
270
1963.1.1 by John Arbash Meinel
run_bzr_subprocess() can take an env_changes parameter
271
    def test_run_bzr_subprocess_env(self):
272
        """run_bzr_subprocess can set environment variables in the child only.
273
274
        These changes should not change the running process, only the child.
275
        """
276
        # The test suite should unset this variable
277
        self.assertEqual(None, os.environ.get('BZR_EMAIL'))
278
        out, err = self.run_bzr_subprocess('whoami', env_changes={
279
                                            'BZR_EMAIL':'Joe Foo <joe@foo.com>'
1963.1.11 by John Arbash Meinel
Add a universal_newlines flag to run_bzr_subprocess, so we can be line-ending independent for tests
280
                                          }, universal_newlines=True)
1963.1.1 by John Arbash Meinel
run_bzr_subprocess() can take an env_changes parameter
281
        self.assertEqual('', err)
282
        self.assertEqual('Joe Foo <joe@foo.com>\n', out)
283
        # And it should not be modified
284
        self.assertEqual(None, os.environ.get('BZR_EMAIL'))
285
286
        # Do it again with a different address, just to make sure
287
        # it is actually changing
288
        out, err = self.run_bzr_subprocess('whoami', env_changes={
289
                                            'BZR_EMAIL':'Barry <bar@foo.com>'
1963.1.11 by John Arbash Meinel
Add a universal_newlines flag to run_bzr_subprocess, so we can be line-ending independent for tests
290
                                          }, universal_newlines=True)
1963.1.1 by John Arbash Meinel
run_bzr_subprocess() can take an env_changes parameter
291
        self.assertEqual('', err)
292
        self.assertEqual('Barry <bar@foo.com>\n', out)
293
        self.assertEqual(None, os.environ.get('BZR_EMAIL'))
294
1963.1.2 by John Arbash Meinel
Cleanups suggested by Martin, add test that env_changes can remove an env variable
295
    def test_run_bzr_subprocess_env_del(self):
296
        """run_bzr_subprocess can remove environment variables too."""
297
        # Create a random email, so we are sure this won't collide
298
        rand_bzr_email = 'John Doe <jdoe@%s.com>' % (osutils.rand_chars(20),)
299
        rand_email = 'Jane Doe <jdoe@%s.com>' % (osutils.rand_chars(20),)
300
        os.environ['BZR_EMAIL'] = rand_bzr_email
301
        os.environ['EMAIL'] = rand_email
302
        try:
303
            # By default, the child will inherit the current env setting
1963.1.11 by John Arbash Meinel
Add a universal_newlines flag to run_bzr_subprocess, so we can be line-ending independent for tests
304
            out, err = self.run_bzr_subprocess('whoami', universal_newlines=True)
1963.1.2 by John Arbash Meinel
Cleanups suggested by Martin, add test that env_changes can remove an env variable
305
            self.assertEqual('', err)
306
            self.assertEqual(rand_bzr_email + '\n', out)
307
308
            # Now that BZR_EMAIL is not set, it should fall back to EMAIL
309
            out, err = self.run_bzr_subprocess('whoami',
1963.1.11 by John Arbash Meinel
Add a universal_newlines flag to run_bzr_subprocess, so we can be line-ending independent for tests
310
                                               env_changes={'BZR_EMAIL':None},
311
                                               universal_newlines=True)
1963.1.2 by John Arbash Meinel
Cleanups suggested by Martin, add test that env_changes can remove an env variable
312
            self.assertEqual('', err)
313
            self.assertEqual(rand_email + '\n', out)
314
315
            # This switches back to the default email guessing logic
316
            # Which shouldn't match either of the above addresses
317
            out, err = self.run_bzr_subprocess('whoami',
1963.1.11 by John Arbash Meinel
Add a universal_newlines flag to run_bzr_subprocess, so we can be line-ending independent for tests
318
                           env_changes={'BZR_EMAIL':None, 'EMAIL':None},
319
                           universal_newlines=True)
1963.1.2 by John Arbash Meinel
Cleanups suggested by Martin, add test that env_changes can remove an env variable
320
321
            self.assertEqual('', err)
322
            self.assertNotEqual(rand_bzr_email + '\n', out)
323
            self.assertNotEqual(rand_email + '\n', out)
324
        finally:
325
            # TestCase cleans up BZR_EMAIL, and EMAIL at startup
326
            del os.environ['BZR_EMAIL']
327
            del os.environ['EMAIL']
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
328
1963.1.4 by John Arbash Meinel
env_changes={} should be safe to remove variables that aren't there
329
    def test_run_bzr_subprocess_env_del_missing(self):
330
        """run_bzr_subprocess won't fail if deleting a nonexistant env var"""
331
        self.failIf('NON_EXISTANT_ENV_VAR' in os.environ)
332
        out, err = self.run_bzr_subprocess('rocks',
1963.1.11 by John Arbash Meinel
Add a universal_newlines flag to run_bzr_subprocess, so we can be line-ending independent for tests
333
                        env_changes={'NON_EXISTANT_ENV_VAR':None},
334
                        universal_newlines=True)
2227.4.1 by v.ladeuil+lp at free
Fix #78026.
335
        self.assertEqual('It sure does!\n', out)
1963.1.11 by John Arbash Meinel
Add a universal_newlines flag to run_bzr_subprocess, so we can be line-ending independent for tests
336
        self.assertEqual('', err)
1963.1.4 by John Arbash Meinel
env_changes={} should be safe to remove variables that aren't there
337
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
338
    def test_run_bzr_subprocess_working_dir(self):
2027.5.2 by John Arbash Meinel
add tests that the working directory is preserved, cleanup run_bzr_subprocess
339
        """Test that we can specify the working dir for the child"""
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
340
        cwd = osutils.getcwd()
341
342
        self.make_branch_and_tree('.')
343
        self.make_branch_and_tree('one')
344
        self.make_branch_and_tree('two')
345
2027.5.2 by John Arbash Meinel
add tests that the working directory is preserved, cleanup run_bzr_subprocess
346
        def get_root(**kwargs):
347
            """Spawn a process to get the 'root' of the tree.
348
349
            You can pass in arbitrary new arguments. This just makes
350
            sure that the returned path doesn't have trailing whitespace.
351
            """
352
            return self.run_bzr_subprocess('root', **kwargs)[0].rstrip()
353
354
        self.assertEqual(cwd, get_root())
355
        self.assertEqual(cwd, get_root(working_dir=None))
356
        # Has our path changed?
357
        self.assertEqual(cwd, osutils.getcwd())
358
359
        dir1 = get_root(working_dir='one')
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
360
        self.assertEndsWith(dir1, 'one')
2027.5.2 by John Arbash Meinel
add tests that the working directory is preserved, cleanup run_bzr_subprocess
361
        self.assertEqual(cwd, osutils.getcwd())
362
363
        dir2 = get_root(working_dir='two')
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
364
        self.assertEndsWith(dir2, 'two')
2027.5.2 by John Arbash Meinel
add tests that the working directory is preserved, cleanup run_bzr_subprocess
365
        self.assertEqual(cwd, osutils.getcwd())
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
366
367
2067.2.2 by John Arbash Meinel
Review comments from Robert
368
class _DontSpawnProcess(Exception):
369
    """A simple exception which just allows us to skip unnecessary steps"""
370
371
372
class TestRunBzrSubprocessCommands(TestCaseWithTransport):
373
374
    def _popen(self, *args, **kwargs):
375
        """Record the command that is run, so that we can ensure it is correct"""
376
        self._popen_args = args
377
        self._popen_kwargs = kwargs
378
        raise _DontSpawnProcess()
379
380
    def test_run_bzr_subprocess_no_plugins(self):
381
        self.assertRaises(_DontSpawnProcess, self.run_bzr_subprocess)
382
        command = self._popen_args[0]
383
        self.assertEqual(sys.executable, command[0])
384
        self.assertEqual(self.get_bzr_path(), command[1])
385
        self.assertEqual(['--no-plugins'], command[2:])
386
387
    def test_allow_plugins(self):
2067.2.4 by John Arbash Meinel
fixup one test
388
        self.assertRaises(_DontSpawnProcess,
389
                          self.run_bzr_subprocess, allow_plugins=True)
2067.2.2 by John Arbash Meinel
Review comments from Robert
390
        command = self._popen_args[0]
391
        self.assertEqual([], command[2:])
392
393
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
394
class TestBzrSubprocess(TestCaseWithTransport):
395
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
396
    def test_start_and_stop_bzr_subprocess(self):
397
        """We can start and perform other test actions while that process is
398
        still alive.
399
        """
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
400
        process = self.start_bzr_subprocess(['--version'])
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
401
        result = self.finish_bzr_subprocess(process)
402
        self.assertContainsRe(result[0], 'is free software')
403
        self.assertEqual('', result[1])
404
405
    def test_start_and_stop_bzr_subprocess_with_error(self):
406
        """finish_bzr_subprocess allows specification of the desired exit code.
407
        """
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
408
        process = self.start_bzr_subprocess(['--versionn'])
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
409
        result = self.finish_bzr_subprocess(process, retcode=3)
410
        self.assertEqual('', result[0])
411
        self.assertContainsRe(result[1], 'unknown command')
412
413
    def test_start_and_stop_bzr_subprocess_ignoring_retcode(self):
414
        """finish_bzr_subprocess allows the exit code to be ignored."""
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
415
        process = self.start_bzr_subprocess(['--versionn'])
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
416
        result = self.finish_bzr_subprocess(process, retcode=None)
417
        self.assertEqual('', result[0])
418
        self.assertContainsRe(result[1], 'unknown command')
419
420
    def test_start_and_stop_bzr_subprocess_with_unexpected_retcode(self):
421
        """finish_bzr_subprocess raises self.failureException if the retcode is
422
        not the expected one.
423
        """
1910.17.8 by Andrew Bennetts
Refactor run_bzr_subprocess to use start_bzr_subprocess and finish_bzr_subprocess.
424
        process = self.start_bzr_subprocess(['--versionn'])
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
425
        self.assertRaises(self.failureException, self.finish_bzr_subprocess,
426
                          process, retcode=0)
427
        
428
    def test_start_and_stop_bzr_subprocess_send_signal(self):
429
        """finish_bzr_subprocess raises self.failureException if the retcode is
430
        not the expected one.
431
        """
1910.17.9 by Andrew Bennetts
Add skip_if_plan_to_signal flag to start_bzr_subprocess.
432
        process = self.start_bzr_subprocess(['wait-until-signalled'],
433
                                            skip_if_plan_to_signal=True)
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
434
        self.assertEqual('running\n', process.stdout.readline())
435
        result = self.finish_bzr_subprocess(process, send_signal=signal.SIGINT,
436
                                            retcode=3)
437
        self.assertEqual('', result[0])
438
        self.assertEqual('bzr: interrupted\n', result[1])
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
439
440
    def test_start_and_stop_working_dir(self):
441
        cwd = osutils.getcwd()
442
443
        self.make_branch_and_tree('one')
444
445
        process = self.start_bzr_subprocess(['root'], working_dir='one')
2156.1.1 by v.ladeuil+lp at free
Make the test compatible with windows.
446
        result = self.finish_bzr_subprocess(process, universal_newlines=True)
2027.5.1 by John Arbash Meinel
Add working_dir=XX to run_bzr_* functions, and clean up tests
447
        self.assertEndsWith(result[0], 'one\n')
448
        self.assertEqual('', result[1])
2156.1.1 by v.ladeuil+lp at free
Make the test compatible with windows.
449
1963.1.4 by John Arbash Meinel
env_changes={} should be safe to remove variables that aren't there
450
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
451
class TestRunBzrError(ExternalBase):
452
453
    def test_run_bzr_error(self):
454
        out, err = self.run_bzr_error(['^$'], 'rocks', retcode=0)
2227.4.1 by v.ladeuil+lp at free
Fix #78026.
455
        self.assertEqual(out, 'It sure does!\n')
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
456
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
457
        out, err = self.run_bzr_error(["bzr: ERROR: foobarbaz is not versioned"],
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
458
                                      'file-id', 'foobarbaz')
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
459
460
461
class TestSelftestCleanOutput(TestCaseInTempDir):
462
463
    def test_clean_output(self):
464
        # check that 'bzr selftest --clean-output' works correct
465
        dirs = ('test0000.tmp', 'test0001.tmp', 'bzrlib', 'tests')
466
        files = ('bzr', 'setup.py', 'test9999.tmp')
467
        for i in dirs:
468
            os.mkdir(i)
469
        for i in files:
470
            f = file(i, 'wb')
471
            f.write('content of ')
472
            f.write(i)
473
            f.close()
474
475
        root = os.getcwdu()
476
        before = os.listdir(root)
2172.4.5 by Alexander Belchenko
Small fix: output of os.listdir() should be sorted manually
477
        before.sort()
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
478
        self.assertEquals(['bzr','bzrlib','setup.py',
479
                           'test0000.tmp','test0001.tmp',
480
                           'test9999.tmp','tests'],
481
                           before)
482
483
        out,err = self.run_bzr_captured(['selftest','--clean-output'],
484
                                        working_dir=root)
485
2193.1.1 by Martin Pool
test_clean_output: don't depend on directories being cleaned up in order.
486
        self.assertEquals(['delete directory: test0000.tmp',
487
                          'delete directory: test0001.tmp'],
488
                          sorted(out.splitlines()))
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
489
        self.assertEquals('', err)
490
491
        after = os.listdir(root)
2172.4.5 by Alexander Belchenko
Small fix: output of os.listdir() should be sorted manually
492
        after.sort()
2172.4.3 by Alexander Belchenko
Change name of option to '--clean-output' and provide tests
493
        self.assertEquals(['bzr','bzrlib','setup.py',
494
                           'test9999.tmp','tests'],
495
                           after)
2394.2.5 by Ian Clatworthy
list-only working, include test not
496
497
2394.2.6 by Ian Clatworthy
completed blackbox tests
498
class TestSelftestListOnly(TestCase):
2394.2.5 by Ian Clatworthy
list-only working, include test not
499
500
    @staticmethod
2394.2.6 by Ian Clatworthy
completed blackbox tests
501
    def _parse_test_list(lines, newlines_in_header=1):
2394.2.5 by Ian Clatworthy
list-only working, include test not
502
        "Parse a list of lines into a tuple of 3 lists (header,body,footer)."
503
504
        in_header = True
505
        in_footer = False
506
        header = []
507
        body = []
2394.2.6 by Ian Clatworthy
completed blackbox tests
508
        footer = []
509
        header_newlines_found = 0 
2394.2.5 by Ian Clatworthy
list-only working, include test not
510
        for line in lines:
511
            if in_header:
512
                if line == '':
2394.2.6 by Ian Clatworthy
completed blackbox tests
513
                    header_newlines_found += 1
514
                    if header_newlines_found >= newlines_in_header:
515
                        in_header = False
516
                        continue
517
                header.append(line)
2394.2.5 by Ian Clatworthy
list-only working, include test not
518
            elif not in_footer:
519
                if line.startswith('-------'):
520
                    in_footer = True
521
                else:
522
                    body.append(line)
523
            else:
524
                footer.append(line)
525
        # If the last body line is blank, drop it off the list
526
        if len(body) > 0 and body[-1] == '':
527
            body.pop()                
528
        return (header,body,footer)
529
530
    def test_list_only(self):
531
        # check that bzr selftest --list-only works correctly
532
        out,err = self.run_bzr_captured(['selftest', 'selftest',
533
            '--list-only'])
2394.2.6 by Ian Clatworthy
completed blackbox tests
534
        self.assertEndsWith(err, 'tests passed\n')
2394.2.5 by Ian Clatworthy
list-only working, include test not
535
        (header,body,footer) = self._parse_test_list(out.splitlines())
2394.2.8 by Ian Clatworthy
incorporate feedback from jam
536
        num_tests = len(body)
537
        self.assertContainsRe(footer[0], 'Listed %s tests in' % num_tests)
2394.2.5 by Ian Clatworthy
list-only working, include test not
538
2394.2.6 by Ian Clatworthy
completed blackbox tests
539
    def test_list_only_filtered(self):
540
        # check that a filtered --list-only works, both include and exclude
2394.2.5 by Ian Clatworthy
list-only working, include test not
541
        out_all,err_all = self.run_bzr_captured(['selftest', '--list-only'])
542
        tests_all = self._parse_test_list(out_all.splitlines())[1]
2394.2.6 by Ian Clatworthy
completed blackbox tests
543
        out_incl,err_incl = self.run_bzr_captured(['selftest', '--list-only',
544
          'selftest'])
545
        tests_incl = self._parse_test_list(out_incl.splitlines())[1]
546
        self.assertSubset(tests_incl, tests_all)
547
        out_excl,err_excl = self.run_bzr_captured(['selftest', '--list-only',
548
          '--exclude', 'selftest'])
549
        tests_excl = self._parse_test_list(out_excl.splitlines())[1]
550
        self.assertSubset(tests_excl, tests_all)
551
        set_incl = set(tests_incl)
552
        set_excl = set(tests_excl)
553
        intersection = set_incl.intersection(set_excl)
554
        self.assertEquals(0, len(intersection))
555
        self.assertEquals(len(tests_all), len(tests_incl) + len(tests_excl))
556
557
    def test_list_only_random(self):
558
        # check that --randomize works correctly
559
        out_all,err_all = self.run_bzr_captured(['selftest', '--list-only',
560
            'selftest'])
561
        tests_all = self._parse_test_list(out_all.splitlines())[1]
2477.1.6 by Martin Pool
doc
562
        # XXX: It looks like there are some orders for generating tests that
563
        # fail as of 20070504 - maybe because of import order dependencies.
564
        # So unfortunately this will rarely intermittently fail at the moment.
565
        # -- mbp 20070504
2394.2.6 by Ian Clatworthy
completed blackbox tests
566
        out_rand,err_rand = self.run_bzr_captured(['selftest', '--list-only',
567
            'selftest', '--randomize', 'now'])
568
        (header_rand,tests_rand,dummy) = self._parse_test_list(
569
            out_rand.splitlines(), 2)
570
        self.assertNotEqual(tests_all, tests_rand)
571
        self.assertEqual(sorted(tests_all), sorted(tests_rand))
572
        # Check that the seed can be reused to get the exact same order
573
        seed_re = re.compile('Randomizing test order using seed (\w+)')
574
        match_obj = seed_re.search(header_rand[-1])
575
        seed = match_obj.group(1)
576
        out_rand2,err_rand2 = self.run_bzr_captured(['selftest', '--list-only',
577
            'selftest', '--randomize', seed])
578
        (header_rand2,tests_rand2,dummy) = self._parse_test_list(
579
            out_rand2.splitlines(), 2)
580
        self.assertEqual(tests_rand, tests_rand2)
2394.2.5 by Ian Clatworthy
list-only working, include test not
581