~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

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

  • Committer: Robey Pointer
  • Date: 2006-09-08 18:46:29 UTC
  • mto: This revision was merged to the branch mainline in revision 1996.
  • Revision ID: robey@lag.net-20060908184629-e3fc4c61ca21508c
pychecker is on crack; go back to using 'is None'.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2005 by Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
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.
 
4
# it under the terms of the GNU General Public License version 2 as published by
 
5
# the Free Software Foundation.
7
6
#
8
7
# This program is distributed in the hope that it will be useful,
9
8
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
11
#
13
12
# You should have received a copy of the GNU General Public License
14
13
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
14
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
15
 
17
16
"""UI tests for the test framework."""
18
17
 
 
18
import os
 
19
import sys
 
20
 
 
21
import bzrlib
19
22
from bzrlib import (
20
 
    benchmarks,
21
 
    tests,
 
23
    osutils,
22
24
    )
 
25
from bzrlib.errors import ParamikoNotPresent
23
26
from bzrlib.tests import (
24
 
    features,
25
 
    )
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]
 
27
                          TestCase,
 
28
                          TestCaseInTempDir,
 
29
                          TestCaseWithTransport,
 
30
                          TestSkipped,
 
31
                          )
 
32
from bzrlib.tests.blackbox import ExternalBase
 
33
 
 
34
 
 
35
class TestOptions(TestCase):
 
36
 
 
37
    current_test = None
 
38
 
 
39
    def test_transport_set_to_sftp(self):
 
40
        # test the --transport option has taken effect from within the
 
41
        # test_transport test
 
42
        try:
 
43
            import bzrlib.transport.sftp
 
44
        except ParamikoNotPresent:
 
45
            raise TestSkipped("Paramiko not present")
 
46
        if TestOptions.current_test != "test_transport_set_to_sftp":
 
47
            return
 
48
        self.assertEqual(bzrlib.transport.sftp.SFTPAbsoluteServer,
 
49
                         bzrlib.tests.default_transport)
 
50
 
 
51
    def test_transport_set_to_memory(self):
 
52
        # test the --transport option has taken effect from within the
 
53
        # test_transport test
 
54
        import bzrlib.transport.memory
 
55
        if TestOptions.current_test != "test_transport_set_to_memory":
 
56
            return
 
57
        self.assertEqual(bzrlib.transport.memory.MemoryServer,
 
58
                         bzrlib.tests.default_transport)
 
59
 
 
60
    def test_transport(self):
 
61
        # test that --transport=sftp works
 
62
        try:
 
63
            import bzrlib.transport.sftp
 
64
        except ParamikoNotPresent:
 
65
            raise TestSkipped("Paramiko not present")
 
66
        old_transport = bzrlib.tests.default_transport
 
67
        old_root = TestCaseInTempDir.TEST_ROOT
 
68
        TestCaseInTempDir.TEST_ROOT = None
 
69
        try:
 
70
            TestOptions.current_test = "test_transport_set_to_sftp"
 
71
            stdout = self.capture('selftest --transport=sftp test_transport_set_to_sftp')
 
72
            
 
73
            self.assertContainsRe(stdout, 'Ran 1 test')
 
74
            self.assertEqual(old_transport, bzrlib.tests.default_transport)
 
75
 
 
76
            TestOptions.current_test = "test_transport_set_to_memory"
 
77
            stdout = self.capture('selftest --transport=memory test_transport_set_to_memory')
 
78
            self.assertContainsRe(stdout, 'Ran 1 test')
 
79
            self.assertEqual(old_transport, bzrlib.tests.default_transport)
45
80
        finally:
46
 
            tests.selftest = original_selftest
47
 
 
48
 
 
49
 
class TestOptionsWritingToDisk(tests.TestCaseInTempDir, SelfTestPatch):
 
81
            bzrlib.tests.default_transport = old_transport
 
82
            TestOptions.current_test = None
 
83
            TestCaseInTempDir.TEST_ROOT = old_root
 
84
 
 
85
 
 
86
class TestRunBzr(ExternalBase):
 
87
 
 
88
    def run_bzr_captured(self, argv, retcode=0, encoding=None, stdin=None):
 
89
        self.stdin = stdin
 
90
 
 
91
    def test_stdin(self):
 
92
        # test that the stdin keyword to run_bzr is passed through to
 
93
        # run_bzr_captured as-is. We do this by overriding
 
94
        # run_bzr_captured in this class, and then calling run_bzr,
 
95
        # which is a convenience function for run_bzr_captured, so 
 
96
        # should invoke it.
 
97
        self.run_bzr('foo', 'bar', stdin='gam')
 
98
        self.assertEqual('gam', self.stdin)
 
99
        self.run_bzr('foo', 'bar', stdin='zippy')
 
100
        self.assertEqual('zippy', self.stdin)
 
101
 
 
102
 
 
103
class TestBenchmarkTests(TestCaseWithTransport):
50
104
 
51
105
    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'])
 
106
        """bzr selftest --benchmark should not run the default test suite."""
 
107
        # We test this by passing a regression test name to --benchmark, which
 
108
        # should result in 0 rests run.
 
109
        old_root = TestCaseInTempDir.TEST_ROOT
 
110
        try:
 
111
            TestCaseInTempDir.TEST_ROOT = None
 
112
            out, err = self.run_bzr('selftest', '--benchmark', 'workingtree_implementations')
 
113
        finally:
 
114
            TestCaseInTempDir.TEST_ROOT = old_root
 
115
        self.assertContainsRe(out, 'Ran 0 tests.*\n\nOK')
 
116
        self.assertEqual(
 
117
            'running tests...\ntests passed\n',
 
118
            err)
57
119
        benchfile = open(".perf_history", "rt")
58
120
        try:
59
121
            lines = benchfile.readlines()
60
122
        finally:
61
123
            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):
115
 
        "Parse a list of lines into a tuple of 3 lists (header,body,footer)."
116
 
        in_header = newlines_in_header != 0
117
 
        in_footer = False
118
 
        header = []
119
 
        body = []
120
 
        footer = []
121
 
        header_newlines_found = 0
122
 
        for line in lines:
123
 
            if in_header:
124
 
                if line == '':
125
 
                    header_newlines_found += 1
126
 
                    if header_newlines_found >= newlines_in_header:
127
 
                        in_header = False
128
 
                        continue
129
 
                header.append(line)
130
 
            elif not in_footer:
131
 
                if line.startswith('-------'):
132
 
                    in_footer = True
133
 
                else:
134
 
                    body.append(line)
135
 
            else:
136
 
                footer.append(line)
137
 
        # If the last body line is blank, drop it off the list
138
 
        if len(body) > 0 and body[-1] == '':
139
 
            body.pop()
140
 
        return (header,body,footer)
141
 
 
142
 
    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
 
124
        self.assertEqual(1, len(lines))
 
125
        self.assertContainsRe(lines[0], "--date [0-9.]+")
 
126
 
 
127
 
 
128
class TestRunBzrCaptured(ExternalBase):
 
129
 
 
130
    def apply_redirected(self, stdin=None, stdout=None, stderr=None,
 
131
                         a_callable=None, *args, **kwargs):
 
132
        self.stdin = stdin
 
133
        self.factory_stdin = getattr(bzrlib.ui.ui_factory, "stdin", None)
 
134
        self.factory = bzrlib.ui.ui_factory
 
135
        stdout.write('foo\n')
 
136
        stderr.write('bar\n')
 
137
        return 0
 
138
 
 
139
    def test_stdin(self):
 
140
        # test that the stdin keyword to run_bzr_captured is passed through to
 
141
        # apply_redirected as a StringIO. We do this by overriding
 
142
        # apply_redirected in this class, and then calling run_bzr_captured,
 
143
        # which calls apply_redirected. 
 
144
        self.run_bzr_captured(['foo', 'bar'], stdin='gam')
 
145
        self.assertEqual('gam', self.stdin.read())
 
146
        self.assertTrue(self.stdin is self.factory_stdin)
 
147
        self.run_bzr_captured(['foo', 'bar'], stdin='zippy')
 
148
        self.assertEqual('zippy', self.stdin.read())
 
149
        self.assertTrue(self.stdin is self.factory_stdin)
 
150
 
 
151
    def test_ui_factory(self):
 
152
        # each invocation of self.run_bzr_captured should get its own UI
 
153
        # factory, which is an instance of TestUIFactory, with stdout and
 
154
        # stderr attached to the stdout and stderr of the invoked
 
155
        # run_bzr_captured
 
156
        current_factory = bzrlib.ui.ui_factory
 
157
        self.run_bzr_captured(['foo'])
 
158
        self.failIf(current_factory is self.factory)
 
159
        self.assertNotEqual(sys.stdout, self.factory.stdout)
 
160
        self.assertNotEqual(sys.stderr, self.factory.stderr)
 
161
        self.assertEqual('foo\n', self.factory.stdout.getvalue())
 
162
        self.assertEqual('bar\n', self.factory.stderr.getvalue())
 
163
        self.assertIsInstance(self.factory, bzrlib.tests.blackbox.TestUIFactory)
 
164
 
 
165
    def test_run_bzr_subprocess(self):
 
166
        """The run_bzr_helper_external comand behaves nicely."""
 
167
        result = self.run_bzr_subprocess('--version')
 
168
        result = self.run_bzr_subprocess('--version', retcode=None)
 
169
        self.assertContainsRe(result[0], 'is free software')
 
170
        self.assertRaises(AssertionError, self.run_bzr_subprocess, 
 
171
                          '--versionn')
 
172
        result = self.run_bzr_subprocess('--versionn', retcode=3)
 
173
        result = self.run_bzr_subprocess('--versionn', retcode=None)
 
174
        self.assertContainsRe(result[1], 'unknown command')
 
175
        err = self.run_bzr_subprocess('merge', '--merge-type', 'magic merge', 
 
176
                                      retcode=3)[1]
 
177
        self.assertContainsRe(err, 'No known merge type magic merge')
 
178
 
 
179
    def test_run_bzr_subprocess_env(self):
 
180
        """run_bzr_subprocess can set environment variables in the child only.
 
181
 
 
182
        These changes should not change the running process, only the child.
 
183
        """
 
184
        # The test suite should unset this variable
 
185
        self.assertEqual(None, os.environ.get('BZR_EMAIL'))
 
186
        out, err = self.run_bzr_subprocess('whoami', env_changes={
 
187
                                            'BZR_EMAIL':'Joe Foo <joe@foo.com>'
 
188
                                          })
 
189
        self.assertEqual('', err)
 
190
        self.assertEqual('Joe Foo <joe@foo.com>\n', out)
 
191
        # And it should not be modified
 
192
        self.assertEqual(None, os.environ.get('BZR_EMAIL'))
 
193
 
 
194
        # Do it again with a different address, just to make sure
 
195
        # it is actually changing
 
196
        out, err = self.run_bzr_subprocess('whoami', env_changes={
 
197
                                            'BZR_EMAIL':'Barry <bar@foo.com>'
 
198
                                          })
 
199
        self.assertEqual('', err)
 
200
        self.assertEqual('Barry <bar@foo.com>\n', out)
 
201
        self.assertEqual(None, os.environ.get('BZR_EMAIL'))
 
202
 
 
203
    def test_run_bzr_subprocess_env_del(self):
 
204
        """run_bzr_subprocess can remove environment variables too."""
 
205
        # Create a random email, so we are sure this won't collide
 
206
        rand_bzr_email = 'John Doe <jdoe@%s.com>' % (osutils.rand_chars(20),)
 
207
        rand_email = 'Jane Doe <jdoe@%s.com>' % (osutils.rand_chars(20),)
 
208
        os.environ['BZR_EMAIL'] = rand_bzr_email
 
209
        os.environ['EMAIL'] = rand_email
160
210
        try:
161
 
            outputs_nothing('selftest --list-only')
162
 
            outputs_nothing('selftest --list-only selftest')
163
 
            outputs_nothing(['selftest', '--list-only', '--exclude', 'selftest'])
 
211
            # By default, the child will inherit the current env setting
 
212
            out, err = self.run_bzr_subprocess('whoami')
 
213
            self.assertEqual('', err)
 
214
            self.assertEqual(rand_bzr_email + '\n', out)
 
215
 
 
216
            # Now that BZR_EMAIL is not set, it should fall back to EMAIL
 
217
            out, err = self.run_bzr_subprocess('whoami',
 
218
                                               env_changes={'BZR_EMAIL':None})
 
219
            self.assertEqual('', err)
 
220
            self.assertEqual(rand_email + '\n', out)
 
221
 
 
222
            # This switches back to the default email guessing logic
 
223
            # Which shouldn't match either of the above addresses
 
224
            out, err = self.run_bzr_subprocess('whoami',
 
225
                           env_changes={'BZR_EMAIL':None, 'EMAIL':None})
 
226
 
 
227
            self.assertEqual('', err)
 
228
            self.assertNotEqual(rand_bzr_email + '\n', out)
 
229
            self.assertNotEqual(rand_email + '\n', out)
164
230
        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"])
 
231
            # TestCase cleans up BZR_EMAIL, and EMAIL at startup
 
232
            del os.environ['BZR_EMAIL']
 
233
            del os.environ['EMAIL']
 
234
 
 
235
class TestRunBzrError(ExternalBase):
 
236
 
 
237
    def test_run_bzr_error(self):
 
238
        out, err = self.run_bzr_error(['^$'], 'rocks', retcode=0)
 
239
        self.assertEqual(out, 'it sure does!\n')
 
240
 
 
241
        out, err = self.run_bzr_error(["'foobarbaz' is not a versioned file"],
 
242
                                      'file-id', 'foobarbaz')