Debian Codegraph @

glanceclient/tests/unit/test_http.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
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 import functools
16 import json
17 import logging
18 from unittest import mock
19 import uuid
20
21 import fixtures
22 import io
23 from keystoneauth1 import session
24 from keystoneauth1 import token_endpoint
25 from oslo_utils import encodeutils
26 import requests
27 from requests_mock.contrib import fixture
28 from urllib import parse
29 from testscenarios import load_tests_apply_scenarios as load_tests # noqa
30 import testtools
31 from testtools import matchers
32 import types
33
34 import glanceclient
35 from glanceclient.common import http
36 from glanceclient.tests import utils
37
38
39 def original_only(f):
40 @functools.wraps(f)
41 def wrapper(self, *args, **kwargs):
42 if not hasattr(self.client, 'log_curl_request'):
43 self.skipTest('Skip logging tests for session client')
44
45 return f(self, *args, **kwargs)
46 return wrapper
47
48
49 class TestClient(testtools.TestCase):
50
51 scenarios = [
52 ('httpclient', {'create_client': '_create_http_client'}),
53 ('session', {'create_client': '_create_session_client'})
54 ]
55
56 def _create_http_client(self):
57 return http.HTTPClient(self.endpoint, token=self.token)
58
59 def _create_session_client(self):
60 auth = token_endpoint.Token(self.endpoint, self.token)
61 sess = session.Session(auth=auth)
62 return http.SessionClient(sess)
63
64 def setUp(self):
65 super(TestClient, self).setUp()
66 self.mock = self.useFixture(fixture.Fixture())
67
68 self.endpoint = 'http://example.com:9292'
69 self.ssl_endpoint = 'https://example.com:9292'
70 self.token = 'abc123'
71
72 self.client = getattr(self, self.create_client)()
73
74 def test_identity_headers_and_token(self):
75 identity_headers = {
76 'X-Auth-Token': 'auth_token',
77 'X-User-Id': 'user',
78 'X-Tenant-Id': 'tenant',
79 'X-Roles': 'roles',
80 'X-Identity-Status': 'Confirmed',
81 'X-Service-Catalog': 'service_catalog',
82 }
83 # with token
84 kwargs = {'token': 'fake-token',
85 'identity_headers': identity_headers}
86 http_client_object = http.HTTPClient(self.endpoint, **kwargs)
87 self.assertEqual('auth_token', http_client_object.auth_token)
88 self.assertTrue(http_client_object.identity_headers.
89 get('X-Auth-Token') is None)
90
91 def test_identity_headers_and_no_token_in_header(self):
92 identity_headers = {
93 'X-User-Id': 'user',
94 'X-Tenant-Id': 'tenant',
95 'X-Roles': 'roles',
96 'X-Identity-Status': 'Confirmed',
97 'X-Service-Catalog': 'service_catalog',
98 }
99 # without X-Auth-Token in identity headers
100 kwargs = {'token': 'fake-token',
101 'identity_headers': identity_headers}
102 http_client_object = http.HTTPClient(self.endpoint, **kwargs)
103 self.assertEqual('fake-token', http_client_object.auth_token)
104 self.assertTrue(http_client_object.identity_headers.
105 get('X-Auth-Token') is None)
106
107 def test_identity_headers_and_no_token_in_session_header(self):
108 # Tests that if token or X-Auth-Token are not provided in the kwargs
109 # when creating the http client, the session headers don't contain
110 # the X-Auth-Token key.
111 identity_headers = {
112 'X-User-Id': 'user',
113 'X-Tenant-Id': 'tenant',
114 'X-Roles': 'roles',
115 'X-Identity-Status': 'Confirmed',
116 'X-Service-Catalog': 'service_catalog',
117 }
118 kwargs = {'identity_headers': identity_headers}
119 http_client_object = http.HTTPClient(self.endpoint, **kwargs)
120 self.assertIsNone(http_client_object.auth_token)
121 self.assertNotIn('X-Auth-Token', http_client_object.session.headers)
122
123 def test_identity_headers_are_passed(self):
124 # Tests that if token or X-Auth-Token are not provided in the kwargs
125 # when creating the http client, the session headers don't contain
126 # the X-Auth-Token key.
127 identity_headers = {
128 'X-User-Id': b'user',
129 'X-Tenant-Id': b'tenant',
130 'X-Roles': b'roles',
131 'X-Identity-Status': b'Confirmed',
132 'X-Service-Catalog': b'service_catalog',
133 }
134 kwargs = {'identity_headers': identity_headers}
135 http_client = http.HTTPClient(self.endpoint, **kwargs)
136
137 path = '/v1/images/my-image'
138 self.mock.get(self.endpoint + path)
139 http_client.get(path)
140
141 headers = self.mock.last_request.headers
142 for k, v in identity_headers.items():
143 self.assertEqual(v, headers[k])
144
145 def test_language_header_passed(self):
146 kwargs = {'language_header': 'nb_NO'}
147 http_client = http.HTTPClient(self.endpoint, **kwargs)
148
149 path = '/v2/images/my-image'
150 self.mock.get(self.endpoint + path)
151 http_client.get(path)
152
153 headers = self.mock.last_request.headers
154 self.assertEqual(kwargs['language_header'], headers['Accept-Language'])
155
156 def test_request_id_header_passed(self):
157 global_id = encodeutils.safe_encode("req-%s" % uuid.uuid4())
158 kwargs = {'global_request_id': global_id}
159 http_client = http.HTTPClient(self.endpoint, **kwargs)
160
161 path = '/v2/images/my-image'
162 self.mock.get(self.endpoint + path)
163 http_client.get(path)
164
165 headers = self.mock.last_request.headers
166 self.assertEqual(global_id, headers['X-OpenStack-Request-ID'])
167
168 def test_language_header_not_passed_no_language(self):
169 kwargs = {}
170 http_client = http.HTTPClient(self.endpoint, **kwargs)
171
172 path = '/v2/images/my-image'
173 self.mock.get(self.endpoint + path)
174 http_client.get(path)
175
176 headers = self.mock.last_request.headers
177 self.assertNotIn('Accept-Language', headers)
178
179 def test_connection_timeout(self):
180 """Verify a InvalidEndpoint is received if connection times out."""
181 def cb(request, context):
182 raise requests.exceptions.Timeout
183
184 path = '/v1/images'
185 self.mock.get(self.endpoint + path, text=cb)
186 comm_err = self.assertRaises(glanceclient.exc.InvalidEndpoint,
187 self.client.get,
188 '/v1/images')
189 self.assertIn(self.endpoint, comm_err.message)
190
191 def test_connection_refused(self):
192 """Verify a CommunicationError is received if connection is refused.
193
194 The error should list the host and port that refused the connection.
195 """
196 def cb(request, context):
197 raise requests.exceptions.ConnectionError()
198
199 path = '/v1/images/detail?limit=20'
200 self.mock.get(self.endpoint + path, text=cb)
201
202 comm_err = self.assertRaises(glanceclient.exc.CommunicationError,
203 self.client.get,
204 '/v1/images/detail?limit=20')
205
206 self.assertIn(self.endpoint, comm_err.message)
207
208 def test_http_encoding(self):
209 path = '/v1/images/detail'
210 text = 'Ok'
211 self.mock.get(self.endpoint + path, text=text,
212 headers={"Content-Type": "text/plain"})
213
214 headers = {"test": 'ni\xf1o'}
215 resp, body = self.client.get(path, headers=headers)
216 self.assertEqual(text, resp.text)
217
218 def test_headers_encoding(self):
219 value = 'ni\xf1o'
220 fake_location = b'http://web_server:80/images/fake.img'
221 headers = {"test": value,
222 "none-val": None,
223 "Name": "value",
224 "x-image-meta-location": fake_location}
225 encoded = http.encode_headers(headers)
226 # Bug #1766235: According to RFC 8187, headers must be
227 # encoded as 7-bit ASCII, so expect to see only displayable
228 # chars in percent-encoding
229 self.assertEqual(b"ni%C3%B1o", encoded[b"test"])
230 self.assertNotIn("none-val", encoded)
231 self.assertNotIn(b"none-val", encoded)
232 self.assertEqual(b"value", encoded[b"Name"])
233 # Bug #1788942: Colons in URL should not get percent-encoded
234 self.assertEqual(fake_location, encoded[b"x-image-meta-location"])
235
236 @mock.patch('keystoneauth1.adapter.Adapter.request')
237 def test_http_duplicate_content_type_headers(self, mock_ksarq):
238 """Test proper handling of Content-Type headers.
239
240 encode_headers() must be called as late as possible before a
241 request is sent. If this principle is violated, and if any
242 changes are made to the headers between encode_headers() and the
243 actual request (for instance a call to
244 _set_common_request_kwargs()), and if you're trying to set a
245 Content-Type that is not equal to application/octet-stream (the
246 default), it is entirely possible that you'll end up with two
247 Content-Type headers defined (yours plus
248 application/octet-stream). The request will go out the door with
249 only one of them chosen seemingly at random.
250
251 This situation only occurs in python3. This test will never fail
252 in python2.
253 """
254 path = "/v2/images/my-image"
255 headers = {
256 "Content-Type": "application/openstack-images-v2.1-json-patch"
257 }
258 data = '[{"value": "qcow2", "path": "/disk_format", "op": "replace"}]'
259 self.mock.patch(self.endpoint + path)
260 sess_http_client = self._create_session_client()
261 sess_http_client.patch(path, headers=headers, data=data)
262 # Pull out the headers with which Adapter.request was invoked
263 ksarqh = mock_ksarq.call_args[1]['headers']
264 # Only one Content-Type header (of any text-type)
265 self.assertEqual(1, [encodeutils.safe_decode(key)
266 for key in ksarqh.keys()].count('Content-Type'))
267 # And it's the one we set
268 self.assertEqual(b"application/openstack-images-v2.1-json-patch",
269 ksarqh[b"Content-Type"])
270
271 def test_request_id_header_session_client(self):
272 global_id = "req-%s" % uuid.uuid4()
273 kwargs = {'global_request_id': global_id}
274 auth = token_endpoint.Token(self.endpoint, self.token)
275 sess = session.Session(auth=auth)
276 http_client = http.SessionClient(sess, **kwargs)
277
278 path = '/v2/images/my-image'
279 self.mock.get(self.endpoint + path)
280 http_client.get(path)
281
282 headers = self.mock.last_request.headers
283 self.assertEqual(global_id, headers['X-OpenStack-Request-ID'])
284
285 def test_raw_request(self):
286 """Verify the path being used for HTTP requests reflects accurately."""
287 headers = {"Content-Type": "text/plain"}
288 text = 'Ok'
289 path = '/v1/images/detail'
290
291 self.mock.get(self.endpoint + path, text=text, headers=headers)
292
293 resp, body = self.client.get('/v1/images/detail', headers=headers)
294 self.assertEqual(headers, resp.headers)
295 self.assertEqual(text, resp.text)
296
297 def test_parse_endpoint(self):
298 endpoint = 'http://example.com:9292'
299 test_client = http.HTTPClient(endpoint, token='adc123')
300 actual = test_client.parse_endpoint(endpoint)
301 expected = parse.SplitResult(scheme='http',
302 netloc='example.com:9292', path='',
303 query='', fragment='')
304 self.assertEqual(expected, actual)
305
306 def test_get_connections_kwargs_http(self):
307 endpoint = 'http://example.com:9292'
308 test_client = http.HTTPClient(endpoint, token='adc123')
309 self.assertEqual(600.0, test_client.timeout)
310
311 def test__chunk_body_exact_size_chunk(self):
312 test_client = http._BaseHTTPClient()
313 bytestring = b'x' * http.CHUNKSIZE
314 data = io.BytesIO(bytestring)
315 chunk = list(test_client._chunk_body(data))
316 self.assertEqual(1, len(chunk))
317 self.assertEqual([bytestring], chunk)
318
319 def test_http_chunked_request(self):
320 text = "Ok"
321 data = io.StringIO(text)
322 path = '/v1/images/'
323 self.mock.post(self.endpoint + path, text=text)
324
325 headers = {"test": 'chunked_request'}
326 resp, body = self.client.post(path, headers=headers, data=data)
327 self.assertIsInstance(self.mock.last_request.body, types.GeneratorType)
328 self.assertEqual(text, resp.text)
329
330 def test_http_json(self):
331 data = {"test": "json_request"}
332 path = '/v1/images'
333 text = 'OK'
334 self.mock.post(self.endpoint + path, text=text)
335
336 headers = {"test": 'chunked_request'}
337 resp, body = self.client.post(path, headers=headers, data=data)
338
339 self.assertEqual(text, resp.text)
340 self.assertIsInstance(self.mock.last_request.body, str)
341 self.assertEqual(data, json.loads(self.mock.last_request.body))
342
343 def test_http_chunked_response(self):
•344 data = b"TEST"
345 path = '/v1/images/'
•346 self.mock.get(self.endpoint + path, body=io.BytesIO(data),
347 headers={"Content-Type": "application/octet-stream"})
348
349 resp, body = self.client.get(path)
350 self.assertIsInstance(body, types.GeneratorType)
351 self.assertEqual([data], list(body))
352
353 @original_only
354 def test_log_http_response_with_non_ascii_char(self):
355 try:
356 response = 'Ok'
357 headers = {"Content-Type": "text/plain",
358 "test": "value1\xa5\xa6"}
359 fake = utils.FakeResponse(headers, io.StringIO(response))
360 self.client.log_http_response(fake)
361 except UnicodeDecodeError as e:
362 self.fail("Unexpected UnicodeDecodeError exception '%s'" % e)
363
364 @original_only
365 def test_log_curl_request_with_non_ascii_char(self):
366 try:
367 headers = {'header1': 'value1\xa5\xa6'}
368 body = 'examplebody\xa5\xa6'
369 self.client.log_curl_request('GET', '/api/v1/\xa5', headers, body,
370 None)
371 except UnicodeDecodeError as e:
372 self.fail("Unexpected UnicodeDecodeError exception '%s'" % e)
373
374 @original_only
375 @mock.patch('glanceclient.common.http.LOG.debug')
376 def test_log_curl_request_with_body_and_header(self, mock_log):
377 hd_name = 'header1'
378 hd_val = 'value1'
379 headers = {hd_name: hd_val}
380 body = 'examplebody'
381 self.client.log_curl_request('GET', '/api/v1/', headers, body, None)
382 self.assertTrue(mock_log.called, 'LOG.debug never called')
383 self.assertTrue(mock_log.call_args[0],
384 'LOG.debug called with no arguments')
385 hd_regex = r".*\s-H\s+'\s*%s\s*:\s*%s\s*'.*" % (hd_name, hd_val)
386 self.assertThat(mock_log.call_args[0][0],
387 matchers.MatchesRegex(hd_regex),
388 'header not found in curl command')
389 body_regex = r".*\s-d\s+'%s'\s.*" % body
390 self.assertThat(mock_log.call_args[0][0],
391 matchers.MatchesRegex(body_regex),
392 'body not found in curl command')
393
394 def _test_log_curl_request_with_certs(self, mock_log, key, cert, cacert):
395 headers = {'header1': 'value1'}
396 http_client_object = http.HTTPClient(self.ssl_endpoint, key_file=key,
397 cert_file=cert, cacert=cacert,
398 token='fake-token')
399 http_client_object.log_curl_request('GET', '/api/v1/', headers, None,
400 None)
401 self.assertTrue(mock_log.called, 'LOG.debug never called')
402 self.assertTrue(mock_log.call_args[0],
403 'LOG.debug called with no arguments')
404
405 needles = {'key': key, 'cert': cert, 'cacert': cacert}
406 for option, value in needles.items():
407 if value:
408 regex = r".*\s--%s\s+('%s'|%s).*" % (option, value, value)
409 self.assertThat(mock_log.call_args[0][0],
410 matchers.MatchesRegex(regex),
411 'no --%s option in curl command' % option)
412 else:
413 regex = r".*\s--%s\s+.*" % option
414 self.assertThat(mock_log.call_args[0][0],
415 matchers.Not(matchers.MatchesRegex(regex)),
416 'unexpected --%s option in curl command' %
417 option)
418
419 @mock.patch('glanceclient.common.http.LOG.debug')
420 def test_log_curl_request_with_all_certs(self, mock_log):
421 self._test_log_curl_request_with_certs(mock_log, 'key1', 'cert1',
422 'cacert2')
423
424 @mock.patch('glanceclient.common.http.LOG.debug')
425 def test_log_curl_request_with_some_certs(self, mock_log):
426 self._test_log_curl_request_with_certs(mock_log, 'key1', 'cert1', None)
427
428 @mock.patch('glanceclient.common.http.LOG.debug')
429 def test_log_curl_request_with_insecure_param(self, mock_log):
430 headers = {'header1': 'value1'}
431 http_client_object = http.HTTPClient(self.ssl_endpoint, insecure=True,
432 token='fake-token')
433 http_client_object.log_curl_request('GET', '/api/v1/', headers, None,
434 None)
435 self.assertTrue(mock_log.called, 'LOG.debug never called')
436 self.assertTrue(mock_log.call_args[0],
437 'LOG.debug called with no arguments')
438 self.assertThat(mock_log.call_args[0][0],
439 matchers.MatchesRegex(r'.*\s-k\s.*'),
440 'no -k option in curl command')
441
442 @mock.patch('glanceclient.common.http.LOG.debug')
443 def test_log_curl_request_with_token_header(self, mock_log):
444 fake_token = 'fake-token'
445 headers = {'X-Auth-Token': fake_token}
446 http_client_object = http.HTTPClient(self.endpoint,
447 identity_headers=headers)
448 http_client_object.log_curl_request('GET', '/api/v1/', headers, None,
449 None)
450 self.assertTrue(mock_log.called, 'LOG.debug never called')
451 self.assertTrue(mock_log.call_args[0],
452 'LOG.debug called with no arguments')
453 token_regex = '.*%s.*' % fake_token
454 self.assertThat(mock_log.call_args[0][0],
455 matchers.Not(matchers.MatchesRegex(token_regex)),
456 'token found in LOG.debug parameter')
457
458 def test_log_request_id_once(self):
459 logger = self.useFixture(fixtures.FakeLogger(level=logging.DEBUG))
•460 data = b"TEST"
461 path = '/v1/images/'
•462 self.mock.get(self.endpoint + path, body=io.BytesIO(data),
463 headers={"Content-Type": "application/octet-stream",
464 'x-openstack-request-id': "1234"})
465
466 resp, body = self.client.get(path)
467 self.assertIsInstance(body, types.GeneratorType)
468 self.assertEqual([data], list(body))
469 expected_log = ("GET call to image "
470 "for http://example.com:9292/v1/images/ "
471 "used request id 1234")
472 self.assertEqual(1, logger.output.count(expected_log))
473
474 def test_expired_token_has_changed(self):
475 # instantiate client with some token
476 fake_token = b'fake-token'
477 http_client = http.HTTPClient(self.endpoint,
478 token=fake_token)
479 path = '/v1/images/my-image'
480 self.mock.get(self.endpoint + path)
481 http_client.get(path)
482 headers = self.mock.last_request.headers
483 self.assertEqual(fake_token, headers['X-Auth-Token'])
484 # refresh the token
485 refreshed_token = b'refreshed-token'
486 http_client.auth_token = refreshed_token
487 http_client.get(path)
488 headers = self.mock.last_request.headers
489 self.assertEqual(refreshed_token, headers['X-Auth-Token'])
490 # regression check for bug 1448080
491 unicode_token = 'ni\xf1o+=='
492 http_client.auth_token = unicode_token
493 http_client.get(path)
494 headers = self.mock.last_request.headers
495 # Bug #1766235: According to RFC 8187, headers must be
496 # encoded as 7-bit ASCII, so expect to see only displayable
497 # chars in percent-encoding. The '+' and '= 'chars will not
498 # be changed.
499 self.assertEqual(b'ni%C3%B1o+==', headers['X-Auth-Token'])