blob: 3d67284b19f4e351d4d0e5e28f986789058c94a1 [file] [log] [blame]
Krzysztof Szukiełojć15b62b72017-02-15 08:58:18 +01001# 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
6This actually passes the requests on to a django.test.client.Client, to avoid
7having to go via a real HTTP server.
8"""
9
10from __future__ import (
11 absolute_import,
12 print_function,
13 unicode_literals,
14 )
15
16str = None
17
18__metaclass__ = type
19__all__ = [
20 'MAASDjangoTestClient',
21 ]
22
23import httplib
24import io
25import urllib2
26
27
28def 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
37class 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))