Krzysztof Szukiełojć | 15b62b7 | 2017-02-15 08:58:18 +0100 | [diff] [blame] | 1 | # Copyright 2012 Canonical Ltd. This software is licensed under the |
| 2 | # GNU Affero General Public License version 3 (see the file LICENSE). |
| 3 | |
| 4 | """A proxy that looks like MAASClient. |
| 5 | |
| 6 | This actually passes the requests on to a django.test.client.Client, to avoid |
| 7 | having to go via a real HTTP server. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import ( |
| 11 | absolute_import, |
| 12 | print_function, |
| 13 | unicode_literals, |
| 14 | ) |
| 15 | |
| 16 | str = None |
| 17 | |
| 18 | __metaclass__ = type |
| 19 | __all__ = [ |
| 20 | 'MAASDjangoTestClient', |
| 21 | ] |
| 22 | |
| 23 | import httplib |
| 24 | import io |
| 25 | import urllib2 |
| 26 | |
| 27 | |
| 28 | def to_addinfourl(response): |
| 29 | """Convert a `django.http.HttpResponse` to a `urllib2.addinfourl`.""" |
| 30 | headers_raw = response.serialize_headers() |
| 31 | headers = httplib.HTTPMessage(io.BytesIO(headers_raw)) |
| 32 | return urllib2.addinfourl( |
| 33 | fp=io.BytesIO(response.content), headers=headers, |
| 34 | url=None, code=response.status_code) |
| 35 | |
| 36 | |
| 37 | class MAASDjangoTestClient: |
| 38 | """Wrap the Django testing Client to look like a MAASClient.""" |
| 39 | |
| 40 | def __init__(self, django_client): |
| 41 | self.django_client = django_client |
| 42 | |
| 43 | def get(self, path, op=None, **kwargs): |
| 44 | kwargs['op'] = op |
| 45 | return to_addinfourl(self.django_client.get(path, kwargs)) |
| 46 | |
| 47 | def post(self, path, op=None, **kwargs): |
| 48 | kwargs['op'] = op |
| 49 | return to_addinfourl(self.django_client.post(path, kwargs)) |
| 50 | |
| 51 | def put(self, path, **kwargs): |
| 52 | return to_addinfourl(self.django_client.put(path, kwargs)) |
| 53 | |
| 54 | def delete(self, path): |
| 55 | return to_addinfourl(self.django_client.delete(path)) |