Fix numerous style issues.
[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
44     def setUp(self):
45         self._environ = {}
46         self._req = HTTPGitRequest(self._environ, self._start_response)
47         self._status = None
48         self._headers = []
49
50     def _start_response(self, status, headers):
51         self._status = status
52         self._headers = list(headers)
53
54
55 class DumbHandlersTestCase(WebTestCase):
56
57     def test_send_file_not_found(self):
58         list(send_file(self._req, None, 'text/plain'))
59         self.assertEquals(HTTP_NOT_FOUND, self._status)
60
61     def test_send_file(self):
62         f = StringIO('foobar')
63         output = ''.join(send_file(self._req, f, 'text/plain'))
64         self.assertEquals('foobar', output)
65         self.assertEquals(HTTP_OK, self._status)
66         self.assertTrue(('Content-Type', 'text/plain') in self._headers)
67         self.assertTrue(f.closed)
68
69     def test_send_file_buffered(self):
70         bufsize = 10240
71         xs = 'x' * bufsize
72         f = StringIO(2 * xs)
73         self.assertEquals([xs, xs],
74                           list(send_file(self._req, f, 'text/plain')))
75         self.assertEquals(HTTP_OK, self._status)
76         self.assertTrue(('Content-Type', 'text/plain') in self._headers)
77         self.assertTrue(f.closed)
78
79     def test_send_file_error(self):
80         class TestFile(object):
81             def __init__(self):
82                 self.closed = False
83
84             def read(self, size=-1):
85                 raise IOError
86
87             def close(self):
88                 self.closed = True
89
90         f = TestFile()
91         list(send_file(self._req, f, 'text/plain'))
92         self.assertEquals(HTTP_NOT_FOUND, self._status)
93         self.assertTrue(f.closed)
94
95     def test_get_info_refs(self):
96         self._environ['QUERY_STRING'] = ''
97
98         class TestTag(object):
99             def __init__(self, sha, obj_class, obj_sha):
100                 self.sha = lambda: sha
101                 self.object = (obj_class, obj_sha)
102
103         class TestBlob(object):
104             def __init__(self, sha):
105                 self.sha = lambda: sha
106
107         blob1 = TestBlob('111')
108         blob2 = TestBlob('222')
109         blob3 = TestBlob('333')
110
111         tag1 = TestTag('aaa', Blob, '222')
112
113         class TestRepo(object):
114
115             def __init__(self, objects, peeled):
116                 self._objects = dict((o.sha(), o) for o in objects)
117                 self._peeled = peeled
118
119             def get_peeled(self, sha):
120                 return self._peeled[sha]
121
122             def __getitem__(self, sha):
123                 return self._objects[sha]
124
125             def get_refs(self):
126                 return {
127                     'HEAD': '000',
128                     'refs/heads/master': blob1.sha(),
129                     'refs/tags/tag-tag': tag1.sha(),
130                     'refs/tags/blob-tag': blob3.sha(),
131                     }
132
133         class TestBackend(object):
134             def __init__(self):
135                 objects = [blob1, blob2, blob3, tag1]
136                 self.repo = TestRepo(objects, {
137                   'HEAD': '000',
138                   'refs/heads/master': blob1.sha(),
139                   'refs/tags/tag-tag': blob2.sha(),
140                   'refs/tags/blob-tag': blob3.sha(),
141                   })
142
143             def open_repository(self, path):
144                 assert path == '/'
145                 return self.repo
146
147             def get_refs(self):
148                 return {
149                   'HEAD': '000',
150                   'refs/heads/master': blob1.sha(),
151                   'refs/tags/tag-tag': tag1.sha(),
152                   'refs/tags/blob-tag': blob3.sha(),
153                   }
154
155         mat = re.search('.*', '//info/refs')
156         self.assertEquals(['111\trefs/heads/master\n',
157                            '333\trefs/tags/blob-tag\n',
158                            'aaa\trefs/tags/tag-tag\n',
159                            '222\trefs/tags/tag-tag^{}\n'],
160                           list(get_info_refs(self._req, TestBackend(), mat)))
161
162
163 class SmartHandlersTestCase(WebTestCase):
164
165     class _TestUploadPackHandler(object):
166         def __init__(self, backend, args, proto, stateless_rpc=False,
167                      advertise_refs=False):
168             self.args = args
169             self.proto = proto
170             self.stateless_rpc = stateless_rpc
171             self.advertise_refs = advertise_refs
172
173         def handle(self):
174             self.proto.write('handled input: %s' % self.proto.recv(1024))
175
176     def _make_handler(self, *args, **kwargs):
177         self._handler = self._TestUploadPackHandler(*args, **kwargs)
178         return self._handler
179
180     def services(self):
181         return {'git-upload-pack': self._make_handler}
182
183     def test_handle_service_request_unknown(self):
184         mat = re.search('.*', '/git-evil-handler')
185         list(handle_service_request(self._req, 'backend', mat))
186         self.assertEquals(HTTP_FORBIDDEN, self._status)
187
188     def test_handle_service_request(self):
189         self._environ['wsgi.input'] = StringIO('foo')
190         mat = re.search('.*', '/git-upload-pack')
191         output = ''.join(handle_service_request(self._req, 'backend', mat,
192                                                 services=self.services()))
193         self.assertEqual('handled input: foo', output)
194         response_type = 'application/x-git-upload-pack-response'
195         self.assertTrue(('Content-Type', response_type) in self._headers)
196         self.assertFalse(self._handler.advertise_refs)
197         self.assertTrue(self._handler.stateless_rpc)
198
199     def test_handle_service_request_with_length(self):
200         self._environ['wsgi.input'] = StringIO('foobar')
201         self._environ['CONTENT_LENGTH'] = 3
202         mat = re.search('.*', '/git-upload-pack')
203         output = ''.join(handle_service_request(self._req, 'backend', mat,
204                                                 services=self.services()))
205         self.assertEqual('handled input: foo', output)
206         response_type = 'application/x-git-upload-pack-response'
207         self.assertTrue(('Content-Type', response_type) in self._headers)
208
209     def test_get_info_refs_unknown(self):
210         self._environ['QUERY_STRING'] = 'service=git-evil-handler'
211         list(get_info_refs(self._req, 'backend', None,
212                            services=self.services()))
213         self.assertEquals(HTTP_FORBIDDEN, self._status)
214
215     def test_get_info_refs(self):
216         self._environ['wsgi.input'] = StringIO('foo')
217         self._environ['QUERY_STRING'] = 'service=git-upload-pack'
218
219         mat = re.search('.*', '/git-upload-pack')
220         output = ''.join(get_info_refs(self._req, 'backend', mat,
221                                        services=self.services()))
222         self.assertEquals(('001e# service=git-upload-pack\n'
223                            '0000'
224                            # input is ignored by the handler
225                            'handled input: '), output)
226         self.assertTrue(self._handler.advertise_refs)
227         self.assertTrue(self._handler.stateless_rpc)
228
229
230 class LengthLimitedFileTestCase(TestCase):
231     def test_no_cutoff(self):
232         f = _LengthLimitedFile(StringIO('foobar'), 1024)
233         self.assertEquals('foobar', f.read())
234
235     def test_cutoff(self):
236         f = _LengthLimitedFile(StringIO('foobar'), 3)
237         self.assertEquals('foo', f.read())
238         self.assertEquals('', f.read())
239
240     def test_multiple_reads(self):
241         f = _LengthLimitedFile(StringIO('foobar'), 3)
242         self.assertEquals('fo', f.read(2))
243         self.assertEquals('o', f.read(2))
244         self.assertEquals('', f.read())
245
246
247 class HTTPGitRequestTestCase(WebTestCase):
248     def test_not_found(self):
249         self._req.cache_forever()  # cache headers should be discarded
250         message = 'Something not found'
251         self.assertEquals(message, self._req.not_found(message))
252         self.assertEquals(HTTP_NOT_FOUND, self._status)
253         self.assertEquals(set([('Content-Type', 'text/plain')]),
254                           set(self._headers))
255
256     def test_forbidden(self):
257         self._req.cache_forever()  # cache headers should be discarded
258         message = 'Something not found'
259         self.assertEquals(message, self._req.forbidden(message))
260         self.assertEquals(HTTP_FORBIDDEN, self._status)
261         self.assertEquals(set([('Content-Type', 'text/plain')]),
262                           set(self._headers))
263
264     def test_respond_ok(self):
265         self._req.respond()
266         self.assertEquals([], self._headers)
267         self.assertEquals(HTTP_OK, self._status)
268
269     def test_respond(self):
270         self._req.nocache()
271         self._req.respond(status=402, content_type='some/type',
272                           headers=[('X-Foo', 'foo'), ('X-Bar', 'bar')])
273         self.assertEquals(set([
274           ('X-Foo', 'foo'),
275           ('X-Bar', 'bar'),
276           ('Content-Type', 'some/type'),
277           ('Expires', 'Fri, 01 Jan 1980 00:00:00 GMT'),
278           ('Pragma', 'no-cache'),
279           ('Cache-Control', 'no-cache, max-age=0, must-revalidate'),
280           ]), set(self._headers))
281         self.assertEquals(402, self._status)
282
283
284 class HTTPGitApplicationTestCase(TestCase):
285     def setUp(self):
286         self._app = HTTPGitApplication('backend')
287
288     def test_call(self):
289         def test_handler(req, backend, mat):
290             # tests interface used by all handlers
291             self.assertEquals(environ, req.environ)
292             self.assertEquals('backend', backend)
293             self.assertEquals('/foo', mat.group(0))
294             return 'output'
295
296         self._app.services = {
297           ('GET', re.compile('/foo$')): test_handler,
298         }
299         environ = {
300           'PATH_INFO': '/foo',
301           'REQUEST_METHOD': 'GET',
302           }
303         self.assertEquals('output', self._app(environ, None))