c9d7d7015a3ba3f3ff873a7c2f71c7c66a339f60
[jelmer/dulwich-libgit2.git] / dulwich / tests / test_web.py
1 # test_web.py -- Tests for the git HTTP server
2 # Copryight (C) 2010 Google, Inc.
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; version 2
7 # or (at your option) any later version of the License.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
17 # MA  02110-1301, USA.
18
19 """Tests for the Git HTTP server."""
20
21 from cStringIO import StringIO
22 import re
23 from unittest import TestCase
24
25 from dulwich.objects import (
26     Blob,
27     )
28 from dulwich.web import (
29     HTTP_OK,
30     HTTP_NOT_FOUND,
31     HTTP_FORBIDDEN,
32     send_file,
33     get_info_refs,
34     handle_service_request,
35     _LengthLimitedFile,
36     HTTPGitRequest,
37     HTTPGitApplication,
38     )
39
40
41 class WebTestCase(TestCase):
42     """Base TestCase that sets up some useful instance vars."""
43     def setUp(self):
44         self._environ = {}
45         self._req = HTTPGitRequest(self._environ, self._start_response)
46         self._status = None
47         self._headers = []
48
49     def _start_response(self, status, headers):
50         self._status = status
51         self._headers = list(headers)
52
53
54 class DumbHandlersTestCase(WebTestCase):
55
56     def test_send_file_not_found(self):
57         list(send_file(self._req, None, 'text/plain'))
58         self.assertEquals(HTTP_NOT_FOUND, self._status)
59
60     def test_send_file(self):
61         f = StringIO('foobar')
62         output = ''.join(send_file(self._req, f, 'text/plain'))
63         self.assertEquals('foobar', output)
64         self.assertEquals(HTTP_OK, self._status)
65         self.assertTrue(('Content-Type', 'text/plain') in self._headers)
66         self.assertTrue(f.closed)
67
68     def test_send_file_buffered(self):
69         bufsize = 10240
70         xs = 'x' * bufsize
71         f = StringIO(2 * xs)
72         self.assertEquals([xs, xs],
73                           list(send_file(self._req, f, 'text/plain')))
74         self.assertEquals(HTTP_OK, self._status)
75         self.assertTrue(('Content-Type', 'text/plain') in self._headers)
76         self.assertTrue(f.closed)
77
78     def test_send_file_error(self):
79         class TestFile(object):
80             def __init__(self):
81                 self.closed = False
82
83             def read(self, size=-1):
84                 raise IOError
85
86             def close(self):
87                 self.closed = True
88
89         f = TestFile()
90         list(send_file(self._req, f, 'text/plain'))
91         self.assertEquals(HTTP_NOT_FOUND, self._status)
92         self.assertTrue(f.closed)
93
94     def test_get_info_refs(self):
95         self._environ['QUERY_STRING'] = ''
96
97         class TestTag(object):
98             def __init__(self, sha, obj_class, obj_sha):
99                 self.sha = lambda: sha
100                 self.object = (obj_class, obj_sha)
101
102         class TestBlob(object):
103             def __init__(self, sha):
104                 self.sha = lambda: sha
105
106         blob1 = TestBlob('111')
107         blob2 = TestBlob('222')
108         blob3 = TestBlob('333')
109
110         tag1 = TestTag('aaa', Blob, '222')
111
112         class TestRepo(object):
113
114             def __init__(self, objects, peeled):
115                 self._objects = dict((o.sha(), o) for o in objects)
116                 self._peeled = peeled
117
118             def get_peeled(self, sha):
119                 return self._peeled[sha]
120
121             def __getitem__(self, sha):
122                 return self._objects[sha]
123
124             def get_refs(self):
125                 return {
126                     'HEAD': '000',
127                     'refs/heads/master': blob1.sha(),
128                     'refs/tags/tag-tag': tag1.sha(),
129                     'refs/tags/blob-tag': blob3.sha(),
130                     }
131
132         class TestBackend(object):
133             def __init__(self):
134                 objects = [blob1, blob2, blob3, tag1]
135                 self.repo = TestRepo(objects, {
136                     'HEAD': '000',
137                     'refs/heads/master': blob1.sha(),
138                     'refs/tags/tag-tag': blob2.sha(),
139                     'refs/tags/blob-tag': blob3.sha(),
140                     })
141
142             def open_repository(self, path):
143                 assert path == '/'
144                 return self.repo
145
146         mat = re.search('.*', '//info/refs')
147         self.assertEquals(['111\trefs/heads/master\n',
148                            '333\trefs/tags/blob-tag\n',
149                            'aaa\trefs/tags/tag-tag\n',
150                            '222\trefs/tags/tag-tag^{}\n'],
151                           list(get_info_refs(self._req, TestBackend(), mat)))
152
153
154 class SmartHandlersTestCase(WebTestCase):
155
156     class _TestUploadPackHandler(object):
157         def __init__(self, backend, args, proto, stateless_rpc=False,
158                      advertise_refs=False):
159             self.args = args
160             self.proto = proto
161             self.stateless_rpc = stateless_rpc
162             self.advertise_refs = advertise_refs
163
164         def handle(self):
165             self.proto.write('handled input: %s' % self.proto.recv(1024))
166
167     def _MakeHandler(self, *args, **kwargs):
168         self._handler = self._TestUploadPackHandler(*args, **kwargs)
169         return self._handler
170
171     def services(self):
172         return {'git-upload-pack': self._MakeHandler}
173
174     def test_handle_service_request_unknown(self):
175         mat = re.search('.*', '/git-evil-handler')
176         list(handle_service_request(self._req, 'backend', mat))
177         self.assertEquals(HTTP_FORBIDDEN, self._status)
178
179     def test_handle_service_request(self):
180         self._environ['wsgi.input'] = StringIO('foo')
181         mat = re.search('.*', '/git-upload-pack')
182         output = ''.join(handle_service_request(self._req, 'backend', mat,
183                                                 services=self.services()))
184         self.assertEqual('handled input: foo', output)
185         response_type = 'application/x-git-upload-pack-response'
186         self.assertTrue(('Content-Type', response_type) in self._headers)
187         self.assertFalse(self._handler.advertise_refs)
188         self.assertTrue(self._handler.stateless_rpc)
189
190     def test_handle_service_request_with_length(self):
191         self._environ['wsgi.input'] = StringIO('foobar')
192         self._environ['CONTENT_LENGTH'] = 3
193         mat = re.search('.*', '/git-upload-pack')
194         output = ''.join(handle_service_request(self._req, 'backend', mat,
195                                                 services=self.services()))
196         self.assertEqual('handled input: foo', output)
197         response_type = 'application/x-git-upload-pack-response'
198         self.assertTrue(('Content-Type', response_type) in self._headers)
199
200     def test_get_info_refs_unknown(self):
201         self._environ['QUERY_STRING'] = 'service=git-evil-handler'
202         list(get_info_refs(self._req, 'backend', None,
203                            services=self.services()))
204         self.assertEquals(HTTP_FORBIDDEN, self._status)
205
206     def test_get_info_refs(self):
207         self._environ['wsgi.input'] = StringIO('foo')
208         self._environ['QUERY_STRING'] = 'service=git-upload-pack'
209
210         mat = re.search('.*', '/git-upload-pack')
211         output = ''.join(get_info_refs(self._req, 'backend', mat,
212                                        services=self.services()))
213         self.assertEquals(('001e# service=git-upload-pack\n'
214                            '0000'
215                            # input is ignored by the handler
216                            'handled input: '), output)
217         self.assertTrue(self._handler.advertise_refs)
218         self.assertTrue(self._handler.stateless_rpc)
219
220
221 class LengthLimitedFileTestCase(TestCase):
222     def test_no_cutoff(self):
223         f = _LengthLimitedFile(StringIO('foobar'), 1024)
224         self.assertEquals('foobar', f.read())
225
226     def test_cutoff(self):
227         f = _LengthLimitedFile(StringIO('foobar'), 3)
228         self.assertEquals('foo', f.read())
229         self.assertEquals('', f.read())
230
231     def test_multiple_reads(self):
232         f = _LengthLimitedFile(StringIO('foobar'), 3)
233         self.assertEquals('fo', f.read(2))
234         self.assertEquals('o', f.read(2))
235         self.assertEquals('', f.read())
236
237
238 class HTTPGitRequestTestCase(WebTestCase):
239     def test_not_found(self):
240         self._req.cache_forever()  # cache headers should be discarded
241         message = 'Something not found'
242         self.assertEquals(message, self._req.not_found(message))
243         self.assertEquals(HTTP_NOT_FOUND, self._status)
244         self.assertEquals(set([('Content-Type', 'text/plain')]),
245                           set(self._headers))
246
247     def test_forbidden(self):
248         self._req.cache_forever()  # cache headers should be discarded
249         message = 'Something not found'
250         self.assertEquals(message, self._req.forbidden(message))
251         self.assertEquals(HTTP_FORBIDDEN, self._status)
252         self.assertEquals(set([('Content-Type', 'text/plain')]),
253                           set(self._headers))
254
255     def test_respond_ok(self):
256         self._req.respond()
257         self.assertEquals([], self._headers)
258         self.assertEquals(HTTP_OK, self._status)
259
260     def test_respond(self):
261         self._req.nocache()
262         self._req.respond(status=402, content_type='some/type',
263                           headers=[('X-Foo', 'foo'), ('X-Bar', 'bar')])
264         self.assertEquals(set([
265             ('X-Foo', 'foo'),
266             ('X-Bar', 'bar'),
267             ('Content-Type', 'some/type'),
268             ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
269             ('Pragma', 'no-cache'),
270             ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
271             ]), set(self._headers))
272         self.assertEquals(402, self._status)
273
274
275 class HTTPGitApplicationTestCase(TestCase):
276     def setUp(self):
277         self._app = HTTPGitApplication('backend')
278
279     def test_call(self):
280         def test_handler(req, backend, mat):
281             # tests interface used by all handlers
282             self.assertEquals(environ, req.environ)
283             self.assertEquals('backend', backend)
284             self.assertEquals('/foo', mat.group(0))
285             return 'output'
286
287         self._app.services = {
288             ('GET', re.compile('/foo$')): test_handler,
289         }
290         environ = {
291             'PATH_INFO': '/foo',
292             'REQUEST_METHOD': 'GET',
293             }
294         self.assertEquals('output', self._app(environ, None))