Debian Codegraph @

keystoneclient/tests/unit/v3/utils.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import requests
14 import uuid
15
16 from urllib import parse as urlparse
17
18 from keystoneauth1.identity import v3
19 from keystoneauth1 import session
20 from keystoneclient.tests.unit import client_fixtures
21 from keystoneclient.tests.unit import utils
22 from keystoneclient.v3 import client
23
24
25 def parameterize(ref):
26 """Rewrite attributes to match the kwarg naming convention in client.
27
28 >>> parameterize({'project_id': 0})
29 {'project': 0}
30
31 """
32 params = ref.copy()
33 for key in ref:
34 if key[-3:] == '_id':
35 params.setdefault(key[:-3], params.pop(key))
36 return params
37
38
39 class UnauthenticatedTestCase(utils.TestCase):
40 """Class used as base for unauthenticated calls."""
41
42 TEST_ROOT_URL = 'http://127.0.0.1:5000/'
43 TEST_URL = '%s%s' % (TEST_ROOT_URL, 'v3')
44 TEST_ROOT_ADMIN_URL = 'http://127.0.0.1:35357/'
45 TEST_ADMIN_URL = '%s%s' % (TEST_ROOT_ADMIN_URL, 'v3')
46
47
48 class TestCase(UnauthenticatedTestCase):
49
50 TEST_ADMIN_IDENTITY_ENDPOINT = "http://127.0.0.1:35357/v3"
51 TEST_PUBLIC_IDENTITY_ENDPOINT = "http://127.0.0.1:5000/v3"
52
53 TEST_SERVICE_CATALOG = [{
54 "endpoints": [{
55 "url": "http://cdn.admin-nets.local:8774/v1.0/",
56 "region": "RegionOne",
57 "interface": "public"
58 }, {
59 "url": "http://127.0.0.1:8774/v1.0",
60 "region": "RegionOne",
61 "interface": "internal"
62 }, {
63 "url": "http://cdn.admin-nets.local:8774/v1.0",
64 "region": "RegionOne",
65 "interface": "admin"
66 }],
67 "type": "nova_compat"
68 }, {
69 "endpoints": [{
70 "url": "http://nova/novapi/public",
71 "region": "RegionOne",
72 "interface": "public"
73 }, {
74 "url": "http://nova/novapi/internal",
75 "region": "RegionOne",
76 "interface": "internal"
77 }, {
78 "url": "http://nova/novapi/admin",
79 "region": "RegionOne",
80 "interface": "admin"
81 }],
82 "type": "compute"
83 }, {
84 "endpoints": [{
85 "url": "http://glance/glanceapi/public",
86 "region": "RegionOne",
87 "interface": "public"
88 }, {
89 "url": "http://glance/glanceapi/internal",
90 "region": "RegionOne",
91 "interface": "internal"
92 }, {
93 "url": "http://glance/glanceapi/admin",
94 "region": "RegionOne",
95 "interface": "admin"
96 }],
97 "type": "image",
98 "name": "glance"
99 }, {
100 "endpoints": [{
101 "url": "http://127.0.0.1:5000/v3",
102 "region": "RegionOne",
103 "interface": "public"
104 }, {
105 "url": "http://127.0.0.1:5000/v3",
106 "region": "RegionOne",
107 "interface": "internal"
108 }, {
109 "url": TEST_ADMIN_IDENTITY_ENDPOINT,
110 "region": "RegionOne",
111 "interface": "admin"
112 }],
113 "type": "identity"
114 }, {
115 "endpoints": [{
116 "url": "http://swift/swiftapi/public",
117 "region": "RegionOne",
118 "interface": "public"
119 }, {
120 "url": "http://swift/swiftapi/internal",
121 "region": "RegionOne",
122 "interface": "internal"
123 }, {
124 "url": "http://swift/swiftapi/admin",
125 "region": "RegionOne",
126 "interface": "admin"
127 }],
128 "type": "object-store"
129 }]
130
131 def stub_auth(self, subject_token=None, **kwargs):
132
133 if not subject_token:
134 subject_token = self.TEST_TOKEN
135
136 try:
137 response_list = kwargs['response_list']
138 except KeyError:
139 headers = kwargs.setdefault('headers', {})
140 headers['X-Subject-Token'] = subject_token
141 else:
142 for resp in response_list:
143 headers = resp.setdefault('headers', {})
144 headers['X-Subject-Token'] = subject_token
145
146 self.stub_url('POST', ['auth', 'tokens'], **kwargs)
147
148
149 class ClientTestCase(utils.ClientTestCaseMixin, TestCase):
150
151 ORIGINAL_CLIENT_TYPE = 'original'
152 KSC_SESSION_CLIENT_TYPE = 'ksc-session'
153 KSA_SESSION_CLIENT_TYPE = 'ksa-session'
154
155 scenarios = [
156 (
157 ORIGINAL_CLIENT_TYPE, {
158 'client_fixture_class': client_fixtures.OriginalV3,
159 'client_type': ORIGINAL_CLIENT_TYPE
160 }
161 ),
162 (
163 KSC_SESSION_CLIENT_TYPE, {
164 'client_fixture_class': client_fixtures.KscSessionV3,
165 'client_type': KSC_SESSION_CLIENT_TYPE
166 }
167 ),
168 (
169 KSA_SESSION_CLIENT_TYPE, {
170 'client_fixture_class': client_fixtures.KsaSessionV3,
171 'client_type': KSA_SESSION_CLIENT_TYPE
172 }
173 )
174
175 ]
176
177 @property
178 def is_original_client(self):
179 return self.client_type == self.ORIGINAL_CLIENT_TYPE
180
181 @property
182 def is_session_client(self):
183 return self.client_type in (self.KSC_SESSION_CLIENT_TYPE,
184 self.KSA_SESSION_CLIENT_TYPE)
185
186
187 class CrudTests(object):
188 key = None
189 collection_key = None
190 model = None
191 manager = None
192 path_prefix = None
193
194 def new_ref(self, **kwargs):
195 kwargs.setdefault('id', uuid.uuid4().hex)
196 kwargs.setdefault(uuid.uuid4().hex, uuid.uuid4().hex)
197 return kwargs
198
199 def encode(self, entity):
200 if isinstance(entity, dict):
201 return {self.key: entity}
202 if isinstance(entity, list):
203 return {self.collection_key: entity}
204 raise NotImplementedError('Are you sure you want to encode that?')
205
206 def stub_entity(self, method, parts=None, entity=None, id=None, **kwargs):
207 if entity:
208 entity = self.encode(entity)
209 kwargs['json'] = entity
210
211 if not parts:
212 parts = [self.collection_key]
213
214 if self.path_prefix:
215 parts.insert(0, self.path_prefix)
216
217 if id:
218 if not parts:
219 parts = []
220
221 parts.append(id)
222
223 self.stub_url(method, parts=parts, **kwargs)
224
225 def assertEntityRequestBodyIs(self, entity):
226 self.assertRequestBodyIs(json=self.encode(entity))
227
228 def test_create(self, ref=None, req_ref=None):
229 deprecations = self.useFixture(client_fixtures.Deprecations())
230 deprecations.expect_deprecations()
231 ref = ref or self.new_ref()
232 manager_ref = ref.copy()
233 manager_ref.pop('id')
234
235 # req_ref argument allows you to specify a different
236 # signature for the request when the manager does some
237 # conversion before doing the request (e.g. converting
238 # from datetime object to timestamp string)
239 if req_ref:
240 req_ref = req_ref.copy()
241 else:
242 req_ref = ref.copy()
243 req_ref.pop('id')
244
245 self.stub_entity('POST', entity=req_ref, status_code=201)
246
247 returned = self.manager.create(**parameterize(manager_ref))
248 self.assertIsInstance(returned, self.model)
249 for attr in req_ref:
250 self.assertEqual(
251 getattr(returned, attr),
252 req_ref[attr],
253 'Expected different %s' % attr)
254 self.assertEntityRequestBodyIs(req_ref)
255
256 # The entity created here may be used in other test cases
257 return returned
258
259 def test_get(self, ref=None):
260 ref = ref or self.new_ref()
261
262 self.stub_entity('GET', id=ref['id'], entity=ref)
263
264 returned = self.manager.get(ref['id'])
265 self.assertIsInstance(returned, self.model)
266 for attr in ref:
267 self.assertEqual(
268 getattr(returned, attr),
269 ref[attr],
270 'Expected different %s' % attr)
271
272 def _get_expected_path(self, expected_path=None):
273 if not expected_path:
274 if self.path_prefix:
275 expected_path = 'v3/%s/%s' % (self.path_prefix,
276 self.collection_key)
277 else:
278 expected_path = 'v3/%s' % self.collection_key
279
280 return expected_path
281
282 def test_list_by_id(self, ref=None, **filter_kwargs):
283 """Test ``entities.list(id=x)`` being rewritten as ``GET /v3/entities/x``. # noqa
284
285 This tests an edge case of each manager's list() implementation, to
286 ensure that it "does the right thing" when users call ``.list()``
287 when they should have used ``.get()``.
288
289 """
290 if 'id' not in filter_kwargs:
291 ref = ref or self.new_ref()
292 filter_kwargs['id'] = ref['id']
293
294 self.assertRaises(TypeError, self.manager.list, **filter_kwargs)
295
296 def test_list(self, ref_list=None, expected_path=None,
297 expected_query=None, **filter_kwargs):
298 ref_list = ref_list or [self.new_ref(), self.new_ref()]
299 expected_path = self._get_expected_path(expected_path)
300
301 self.requests_mock.get(urlparse.urljoin(self.TEST_URL, expected_path),
302 json=self.encode(ref_list))
303
304 returned_list = self.manager.list(**filter_kwargs)
305 self.assertEqual(len(ref_list), len(returned_list))
306 [self.assertIsInstance(r, self.model) for r in returned_list]
307
308 qs_args = self.requests_mock.last_request.qs
309 qs_args_expected = expected_query or filter_kwargs
310 for key, value in qs_args_expected.items():
311 self.assertIn(key, qs_args)
312 # The querystring value is a list. Note we convert the value to a
313 # string and lower, as the query string is always a string and the
314 # filter_kwargs may contain non-string values, for example a
315 # boolean, causing the comaprison to fail.
316 self.assertIn(str(value).lower(), qs_args[key])
317
318 # Also check that no query string args exist which are not expected
319 for key in qs_args:
320 self.assertIn(key, qs_args_expected)
321
322 def test_list_params(self):
323 ref_list = [self.new_ref()]
324 filter_kwargs = {uuid.uuid4().hex: uuid.uuid4().hex}
325 expected_path = self._get_expected_path()
326
327 self.requests_mock.get(urlparse.urljoin(self.TEST_URL, expected_path),
328 json=self.encode(ref_list))
329
330 self.manager.list(**filter_kwargs)
331 self.assertQueryStringContains(**filter_kwargs)
332
333 def test_find(self, ref=None):
334 ref = ref or self.new_ref()
335 ref_list = [ref]
336
337 self.stub_entity('GET', entity=ref_list)
338
339 returned = self.manager.find(name=getattr(ref, 'name', None))
340 self.assertIsInstance(returned, self.model)
341 for attr in ref:
342 self.assertEqual(
343 getattr(returned, attr),
344 ref[attr],
345 'Expected different %s' % attr)
346
347 if hasattr(ref, 'name'):
348 self.assertQueryStringIs('name=%s' % ref['name'])
349 else:
350 self.assertQueryStringIs('')
351
352 def test_update(self, ref=None, req_ref=None):
353 deprecations = self.useFixture(client_fixtures.Deprecations())
354 deprecations.expect_deprecations()
355 ref = ref or self.new_ref()
356
357 self.stub_entity('PATCH', id=ref['id'], entity=ref)
358
359 # req_ref argument allows you to specify a different
360 # signature for the request when the manager does some
361 # conversion before doing the request (e.g. converting
362 # from datetime object to timestamp string)
363 if req_ref:
364 req_ref = req_ref.copy()
365 else:
366 req_ref = ref.copy()
367 req_ref.pop('id')
368
369 returned = self.manager.update(ref['id'], **parameterize(req_ref))
370 self.assertIsInstance(returned, self.model)
371 for attr in ref:
372 self.assertEqual(
373 getattr(returned, attr),
374 ref[attr],
375 'Expected different %s' % attr)
376 self.assertEntityRequestBodyIs(req_ref)
377
378 def test_delete(self, ref=None):
379 ref = ref or self.new_ref()
380
381 self.stub_entity('DELETE', id=ref['id'], status_code=204)
382 self.manager.delete(ref['id'])
383
384
385 class TestRequestId(TestCase):
386 resp = requests.Response()
387 TEST_REQUEST_ID = uuid.uuid4().hex
388 resp.headers['x-openstack-request-id'] = TEST_REQUEST_ID
389
390 def setUp(self):
391 super(TestRequestId, self).setUp()
392 auth = v3.Token(auth_url='http://127.0.0.1:5000',
393 token=self.TEST_TOKEN)
394 session_ = session.Session(auth=auth)
395 self.client = client.Client(session=session_,
396 include_metadata='True')._adapter