Debian Codegraph @

glanceclient/tests/utils.py

raw symbols SCIP
1 # Copyright 2012 OpenStack Foundation
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import copy
17 from email.message import EmailMessage
18 import io
19 import json
20 import testtools
21 from urllib import parse
22
23 from glanceclient.v2 import schemas
24
25
26 class FakeAPI(object):
27 def __init__(self, fixtures):
28 self.fixtures = fixtures
29 self.calls = []
30
31 def _request(self, method, url, headers=None, data=None,
32 content_length=None):
33 call = build_call_record(method, sort_url_by_query_keys(url),
34 headers or {}, data)
35 if content_length is not None:
36 call = tuple(list(call) + [content_length])
37 self.calls.append(call)
38
39 fixture = self.fixtures[sort_url_by_query_keys(url)][method]
40
41 data = fixture[1]
42 if isinstance(fixture[1], str):
43 try:
44 data = json.loads(fixture[1])
45 except ValueError:
46 data = io.StringIO(fixture[1])
47
48 return FakeResponse(fixture[0], fixture[1]), data
49
50 def get(self, *args, **kwargs):
51 return self._request('GET', *args, **kwargs)
52
53 def post(self, *args, **kwargs):
54 return self._request('POST', *args, **kwargs)
55
56 def put(self, *args, **kwargs):
57 return self._request('PUT', *args, **kwargs)
58
59 def patch(self, *args, **kwargs):
60 return self._request('PATCH', *args, **kwargs)
61
62 def delete(self, *args, **kwargs):
63 return self._request('DELETE', *args, **kwargs)
64
65 def head(self, *args, **kwargs):
66 return self._request('HEAD', *args, **kwargs)
67
68
69 class FakeSchemaAPI(FakeAPI):
70 def get(self, *args, **kwargs):
71 _, raw_schema = self._request('GET', *args, **kwargs)
72 return schemas.Schema(raw_schema)
73
74
75 class RawRequest(object):
76 def __init__(self, headers, body=None,
77 version=1.0, status=200, reason="Ok"):
78 """A crafted request object used for testing.
79
80 :param headers: dict representing HTTP response headers
81 :param body: file-like object
82 :param version: HTTP Version
83 :param status: Response status code
84 :param reason: Status code related message.
85 """
86 self.body = body
87 self.status = status
88 self.reason = reason
89 self.version = version
90 self.headers = headers
91
92 def getheaders(self):
93 return copy.deepcopy(self.headers).items()
94
95 def getheader(self, key, default):
96 return self.headers.get(key, default)
97
98 def read(self, amt):
99 return self.body.read(amt)
100
101
102 class FakeResponse(object):
103 def __init__(self, headers=None, body=None,
104 version=1.0, status_code=200, reason="Ok"):
105 """A crafted response object used for testing.
106
107 :param headers: dict representing HTTP response headers
108 :param body: file-like object
109 :param version: HTTP Version
110 :param status: Response status code
111 :param reason: Status code related message.
112 """
113 self.body = body
114 self.reason = reason
115 self.version = version
116 # NOTE(tkajinam): Make the FakeResponse class compatible with
117 # http.client.HTTPResponse
118 # https://docs.python.org/3/library/http.client.html
119 self.headers = EmailMessage()
120 for header_key in headers:
121 self.headers[header_key] = headers[header_key]
122 self.headers['x-openstack-request-id'] = 'req-1234'
123 self.status_code = status_code
124 self.raw = RawRequest(headers, body=body, reason=reason,
125 version=version, status=status_code)
126
127 @property
128 def status(self):
129 return self.status_code
130
131 @property
132 def ok(self):
133 return (self.status_code < 400 or
134 self.status_code >= 600)
135
136 def read(self, amt):
137 return self.body.read(amt)
138
139 def close(self):
140 pass
141
142 @property
143 def content(self):
144 if hasattr(self.body, "read"):
145 return self.body.read()
146 return self.body
147
148 @property
149 def text(self):
150 if isinstance(self.content, bytes):
151 return self.content.decode('utf-8')
152
153 return self.content
154
155 def json(self, **kwargs):
156 return self.body and json.loads(self.text) or ""
157
158 def iter_content(self, chunk_size=1, decode_unicode=False):
159 while True:
160 chunk = self.raw.read(chunk_size)
161 if not chunk:
162 break
163 yield chunk
164
165 def release_conn(self, **kwargs):
166 pass
167
168
169 class TestCase(testtools.TestCase):
170 TEST_REQUEST_BASE = {
171 'config': {'danger_mode': False},
172 'verify': True}
173
174
175 class FakeTTYStdout(io.StringIO):
176 """A Fake stdout that try to emulate a TTY device as much as possible."""
177
178 def isatty(self):
179 return True
180
181 def write(self, data):
182 # When a CR (carriage return) is found reset file.
183 if data.startswith('\r'):
184 self.seek(0)
185 data = data[1:]
186 return io.StringIO.write(self, data)
187
188
189 class FakeNoTTYStdout(FakeTTYStdout):
190 """A Fake stdout that is not a TTY device."""
191
192 def isatty(self):
193 return False
194
195
196 def sort_url_by_query_keys(url):
197 """A helper function which sorts the keys of the query string of a url.
198
199 For example, an input of '/v2/tasks?sort_key=id&sort_dir=asc&limit=10'
200 returns '/v2/tasks?limit=10&sort_dir=asc&sort_key=id'. This is to
201 prevent non-deterministic ordering of the query string causing
202 problems with unit tests.
203 :param url: url which will be ordered by query keys
204 :returns url: url with ordered query keys
205 """
206 parsed = parse.urlparse(url)
207 queries = parse.parse_qsl(parsed.query, True)
208 sorted_query = sorted(queries, key=lambda x: x[0])
209
210 encoded_sorted_query = parse.urlencode(sorted_query, True)
211
212 url_parts = (parsed.scheme, parsed.netloc, parsed.path,
213 parsed.params, encoded_sorted_query,
214 parsed.fragment)
215
216 return parse.urlunparse(url_parts)
217
218
219 def build_call_record(method, url, headers, data):
220 """Key the request body be ordered if it's a dict type."""
221 if isinstance(data, dict):
222 data = sorted(data.items())
223 if isinstance(data, str):
224 # NOTE(flwang): For image update, the data will be a 'list' which
225 # contains operation dict, such as: [{"op": "remove", "path": "/a"}]
226 try:
227 data = json.loads(data)
228 except ValueError:
229 return (method, url, headers or {}, data)
230 data = [sorted(d.items()) for d in data]
231 return (method, url, headers or {}, data)