~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

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

  • Committer: Aaron Bentley
  • Date: 2007-06-20 22:06:22 UTC
  • mto: (2520.5.2 bzr.mpbundle)
  • mto: This revision was merged to the branch mainline in revision 2631.
  • Revision ID: abentley@panoramicfeedback.com-20070620220622-9lasxr96rr0e0xvn
Use a fresh versionedfile each time

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006 Canonical Ltd
 
2
#
 
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.
 
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
 
 
18
"""Tests of the bzr serve command."""
 
19
 
 
20
import os
 
21
import signal
 
22
import subprocess
 
23
import sys
 
24
import threading
 
25
 
 
26
from bzrlib import (
 
27
    errors,
 
28
    osutils,
 
29
    )
 
30
from bzrlib.branch import Branch
 
31
from bzrlib.bzrdir import BzrDir
 
32
from bzrlib.errors import ParamikoNotPresent
 
33
from bzrlib.smart import medium
 
34
from bzrlib.tests import TestCaseWithTransport, TestSkipped
 
35
from bzrlib.transport import get_transport, remote
 
36
 
 
37
 
 
38
class TestBzrServe(TestCaseWithTransport):
 
39
 
 
40
    def assertInetServerShutsdownCleanly(self, process):
 
41
        """Shutdown the server process looking for errors."""
 
42
        # Shutdown the server: the server should shut down when it cannot read
 
43
        # from stdin anymore.
 
44
        process.stdin.close()
 
45
        # Hide stdin from the subprocess module, so it won't fail to close it.
 
46
        process.stdin = None
 
47
        result = self.finish_bzr_subprocess(process, retcode=0)
 
48
        self.assertEqual('', result[0])
 
49
        self.assertEqual('', result[1])
 
50
    
 
51
    def assertServerFinishesCleanly(self, process):
 
52
        """Shutdown the bzr serve instance process looking for errors."""
 
53
        # Shutdown the server
 
54
        result = self.finish_bzr_subprocess(process, retcode=3,
 
55
                                            send_signal=signal.SIGINT)
 
56
        self.assertEqual('', result[0])
 
57
        self.assertEqual('bzr: interrupted\n', result[1])
 
58
 
 
59
    def start_server_inet(self, extra_options=()):
 
60
        """Start a bzr server subprocess using the --inet option.
 
61
 
 
62
        :param extra_options: extra options to give the server.
 
63
        :return: a tuple with the bzr process handle for passing to
 
64
            finish_bzr_subprocess, a client for the server, and a transport.
 
65
        """
 
66
        # Serve from the current directory
 
67
        process = self.start_bzr_subprocess(['serve', '--inet'])
 
68
 
 
69
        # Connect to the server
 
70
        # We use this url because while this is no valid URL to connect to this
 
71
        # server instance, the transport needs a URL.
 
72
        client_medium = medium.SmartSimplePipesClientMedium(
 
73
            process.stdout, process.stdin)
 
74
        transport = remote.RemoteTransport(
 
75
            'bzr://localhost/', medium=client_medium)
 
76
        return process, transport
 
77
 
 
78
    def start_server_port(self, extra_options=()):
 
79
        """Start a bzr server subprocess.
 
80
 
 
81
        :param extra_options: extra options to give the server.
 
82
        :return: a tuple with the bzr process handle for passing to
 
83
            finish_bzr_subprocess, and the base url for the server.
 
84
        """
 
85
        # Serve from the current directory
 
86
        args = ['serve', '--port', 'localhost:0']
 
87
        args.extend(extra_options)
 
88
        process = self.start_bzr_subprocess(args, skip_if_plan_to_signal=True)
 
89
        port_line = process.stdout.readline()
 
90
        prefix = 'listening on port: '
 
91
        self.assertStartsWith(port_line, prefix)
 
92
        port = int(port_line[len(prefix):])
 
93
        return process,'bzr://localhost:%d/' % port
 
94
 
 
95
    def test_bzr_serve_inet_readonly(self):
 
96
        """bzr server should provide a read only filesystem by default."""
 
97
        process, transport = self.start_server_inet()
 
98
        self.assertRaises(errors.TransportNotPossible, transport.mkdir, 'adir')
 
99
        self.assertInetServerShutsdownCleanly(process)
 
100
 
 
101
    def test_bzr_serve_inet_readwrite(self):
 
102
        # Make a branch
 
103
        self.make_branch('.')
 
104
 
 
105
        process, transport = self.start_server_inet(['--allow-writes'])
 
106
 
 
107
        # We get a working branch
 
108
        branch = BzrDir.open_from_transport(transport).open_branch()
 
109
        branch.repository.get_revision_graph()
 
110
        self.assertEqual(None, branch.last_revision())
 
111
        self.assertInetServerShutsdownCleanly(process)
 
112
 
 
113
    def test_bzr_serve_port_readonly(self):
 
114
        """bzr server should provide a read only filesystem by default."""
 
115
        process, url = self.start_server_port()
 
116
        transport = get_transport(url)
 
117
        self.assertRaises(errors.TransportNotPossible, transport.mkdir, 'adir')
 
118
        self.assertServerFinishesCleanly(process)
 
119
 
 
120
    def test_bzr_serve_port_readwrite(self):
 
121
        # Make a branch
 
122
        self.make_branch('.')
 
123
 
 
124
        process, url = self.start_server_port(['--allow-writes'])
 
125
 
 
126
        # Connect to the server
 
127
        branch = Branch.open(url)
 
128
 
 
129
        # We get a working branch
 
130
        branch.repository.get_revision_graph()
 
131
        self.assertEqual(None, branch.last_revision())
 
132
 
 
133
        self.assertServerFinishesCleanly(process)
 
134
 
 
135
    def test_bzr_connect_to_bzr_ssh(self):
 
136
        """User acceptance that get_transport of a bzr+ssh:// behaves correctly.
 
137
 
 
138
        bzr+ssh:// should cause bzr to run a remote bzr smart server over SSH.
 
139
        """
 
140
        try:
 
141
            from bzrlib.transport.sftp import SFTPServer
 
142
        except ParamikoNotPresent:
 
143
            raise TestSkipped('Paramiko not installed')
 
144
        from bzrlib.tests.stub_sftp import StubServer
 
145
        
 
146
        # Make a branch
 
147
        self.make_branch('a_branch')
 
148
 
 
149
        # Start an SSH server
 
150
        self.command_executed = []
 
151
        # XXX: This is horrible -- we define a really dumb SSH server that
 
152
        # executes commands, and manage the hooking up of stdin/out/err to the
 
153
        # SSH channel ourselves.  Surely this has already been implemented
 
154
        # elsewhere?
 
155
        class StubSSHServer(StubServer):
 
156
 
 
157
            test = self
 
158
 
 
159
            def check_channel_exec_request(self, channel, command):
 
160
                self.test.command_executed.append(command)
 
161
                proc = subprocess.Popen(
 
162
                    command, shell=True, stdin=subprocess.PIPE,
 
163
                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
164
                
 
165
                # XXX: horribly inefficient, not to mention ugly.
 
166
                # Start a thread for each of stdin/out/err, and relay bytes from
 
167
                # the subprocess to channel and vice versa.
 
168
                def ferry_bytes(read, write, close):
 
169
                    while True:
 
170
                        bytes = read(1)
 
171
                        if bytes == '':
 
172
                            close()
 
173
                            break
 
174
                        write(bytes)
 
175
 
 
176
                file_functions = [
 
177
                    (channel.recv, proc.stdin.write, proc.stdin.close),
 
178
                    (proc.stdout.read, channel.sendall, channel.close),
 
179
                    (proc.stderr.read, channel.sendall_stderr, channel.close)]
 
180
                for read, write, close in file_functions:
 
181
                    t = threading.Thread(
 
182
                        target=ferry_bytes, args=(read, write, close))
 
183
                    t.start()
 
184
 
 
185
                return True
 
186
 
 
187
        ssh_server = SFTPServer(StubSSHServer)
 
188
        # XXX: We *don't* want to override the default SSH vendor, so we set
 
189
        # _vendor to what _get_ssh_vendor returns.
 
190
        ssh_server.setUp()
 
191
        self.addCleanup(ssh_server.tearDown)
 
192
        port = ssh_server._listener.port
 
193
 
 
194
        # Access the branch via a bzr+ssh URL.  The BZR_REMOTE_PATH environment
 
195
        # variable is used to tell bzr what command to run on the remote end.
 
196
        path_to_branch = osutils.abspath('a_branch')
 
197
        
 
198
        orig_bzr_remote_path = os.environ.get('BZR_REMOTE_PATH')
 
199
        bzr_remote_path = self.get_bzr_path()
 
200
        if sys.platform == 'win32':
 
201
            bzr_remote_path = sys.executable + ' ' + self.get_bzr_path()
 
202
        os.environ['BZR_REMOTE_PATH'] = bzr_remote_path
 
203
        try:
 
204
            if sys.platform == 'win32':
 
205
                path_to_branch = os.path.splitdrive(path_to_branch)[1]
 
206
            branch = Branch.open(
 
207
                'bzr+ssh://fred:secret@localhost:%d%s' % (port, path_to_branch))
 
208
            
 
209
            branch.repository.get_revision_graph()
 
210
            self.assertEqual(None, branch.last_revision())
 
211
            # Check we can perform write operations
 
212
            branch.bzrdir.root_transport.mkdir('foo')
 
213
        finally:
 
214
            # Restore the BZR_REMOTE_PATH environment variable back to its
 
215
            # original state.
 
216
            if orig_bzr_remote_path is None:
 
217
                del os.environ['BZR_REMOTE_PATH']
 
218
            else:
 
219
                os.environ['BZR_REMOTE_PATH'] = orig_bzr_remote_path
 
220
 
 
221
        self.assertEqual(
 
222
            ['%s serve --inet --directory=/ --allow-writes'
 
223
             % bzr_remote_path],
 
224
            self.command_executed)
 
225