Debian Codegraph @

heatclient/tests/unit/test_common_http.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain 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,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10 # implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 import socket
15 from unittest import mock
16
17 import io
18 from keystoneauth1 import adapter
19 from oslo_serialization import jsonutils
20 import testtools
21
22 from heatclient.common import http
23 from heatclient.common import utils
24 from heatclient import exc
25 from heatclient.tests.unit import fakes
26
27
28 @mock.patch('heatclient.common.http.requests.request')
29 class HttpClientTest(testtools.TestCase):
30
31 def test_http_raw_request(self, mock_request):
32 headers = {'Content-Type': 'application/octet-stream',
33 'User-Agent': 'python-heatclient'}
34
35 # Record a 200
36 mock_request.return_value = fakes.FakeHTTPResponse(
37 200, 'OK',
38 {'content-type': 'application/octet-stream'},
39 '')
40 # Replay, create client, assert
41 client = http.HTTPClient('http://example.com:8004')
42 resp = client.raw_request('GET', '')
43 self.assertEqual(200, resp.status_code)
44 self.assertEqual('', ''.join([x for x in resp.content]))
45 mock_request.assert_called_with('GET', 'http://example.com:8004',
46 allow_redirects=False,
47 headers=headers)
48
49 def test_token_or_credentials(self, mock_request):
50 # Record a 200
51 fake200 = fakes.FakeHTTPResponse(
52 200, 'OK',
53 {'content-type': 'application/octet-stream'},
54 '')
55
56 mock_request.return_value = fake200
57 # no token or credentials
58 client = http.HTTPClient('http://example.com:8004')
59 resp = client.raw_request('GET', '')
60 self.assertEqual(200, resp.status_code)
61 # credentials
62 client.username = 'user'
63 client.password = 'pass'
64 resp = client.raw_request('GET', '')
65 self.assertEqual(200, resp.status_code)
66 # token suppresses credentials
67 client.auth_token = 'abcd1234'
68 resp = client.raw_request('GET', '')
69 self.assertEqual(200, resp.status_code)
70 mock_request.assert_has_calls([
71 mock.call('GET', 'http://example.com:8004',
72 allow_redirects=False,
73 headers={'Content-Type': 'application/octet-stream',
74 'User-Agent': 'python-heatclient'}),
75 mock.call('GET', 'http://example.com:8004',
76 allow_redirects=False,
77 headers={'Content-Type': 'application/octet-stream',
78 'User-Agent': 'python-heatclient',
79 'X-Auth-Key': 'pass',
80 'X-Auth-User': 'user'}),
81 mock.call('GET', 'http://example.com:8004',
82 allow_redirects=False,
83 headers={'Content-Type': 'application/octet-stream',
84 'User-Agent': 'python-heatclient',
85 'X-Auth-Token': 'abcd1234'})
86 ])
87
88 def test_include_pass(self, mock_request):
89 # Record a 200
90 fake200 = fakes.FakeHTTPResponse(
91 200, 'OK',
92 {'content-type': 'application/octet-stream'},
93 '')
94 mock_request.return_value = fake200
95 # no token or credentials
96 client = http.HTTPClient('http://example.com:8004')
97 resp = client.raw_request('GET', '')
98 self.assertEqual(200, resp.status_code)
99 # credentials
100 client.username = 'user'
101 client.password = 'pass'
102 client.include_pass = True
103 resp = client.raw_request('GET', '')
104 self.assertEqual(200, resp.status_code)
105 # token suppresses credentials
106 client.auth_token = 'abcd1234'
107 resp = client.raw_request('GET', '')
108 self.assertEqual(200, resp.status_code)
109 mock_request.assert_has_calls([
110 mock.call('GET', 'http://example.com:8004',
111 allow_redirects=False,
112 headers={'Content-Type': 'application/octet-stream',
113 'User-Agent': 'python-heatclient'}),
114 mock.call('GET', 'http://example.com:8004',
115 allow_redirects=False,
116 headers={'Content-Type': 'application/octet-stream',
117 'User-Agent': 'python-heatclient',
118 'X-Auth-Key': 'pass',
119 'X-Auth-User': 'user'}),
120 mock.call('GET', 'http://example.com:8004',
121 allow_redirects=False,
122 headers={'Content-Type': 'application/octet-stream',
123 'User-Agent': 'python-heatclient',
124 'X-Auth-Token': 'abcd1234',
125 'X-Auth-Key': 'pass',
126 'X-Auth-User': 'user'})
127 ])
128
129 def test_not_include_pass(self, mock_request):
130 # Record a 200
131 fake500 = fakes.FakeHTTPResponse(
132 500, 'ERROR',
133 {'content-type': 'application/octet-stream'},
134 b'(HTTP 401)')
135
136 # no token or credentials
137 mock_request.return_value = fake500
138
139 # Replay, create client, assert
140 client = http.HTTPClient('http://example.com:8004')
141 e = self.assertRaises(exc.HTTPUnauthorized,
142 client.raw_request, 'GET', '')
143 self.assertIn('Authentication failed', str(e))
144 mock_request.assert_called_with(
145 'GET', 'http://example.com:8004',
146 allow_redirects=False,
147 headers={'Content-Type': 'application/octet-stream',
148 'User-Agent': 'python-heatclient'})
149
150 def test_region_name(self, mock_request):
151 # Record a 200
152 fake200 = fakes.FakeHTTPResponse(
153 200, 'OK',
154 {'content-type': 'application/octet-stream'},
155 '')
156
157 # Specify region name
158 mock_request.return_value = fake200
159
160 # Replay, create client, assert
161 client = http.HTTPClient('http://example.com:8004')
162 client.region_name = 'RegionOne'
163 resp = client.raw_request('GET', '')
164 self.assertEqual(200, resp.status_code)
165 mock_request.assert_called_with(
166 'GET', 'http://example.com:8004',
167 allow_redirects=False,
168 headers={'Content-Type': 'application/octet-stream',
169 'X-Region-Name': 'RegionOne',
170 'User-Agent': 'python-heatclient'})
171
172 def test_http_json_request(self, mock_request):
173 # Record a 200
174 mock_request.return_value = fakes.FakeHTTPResponse(
175 200, 'OK',
176 {'content-type': 'application/json'},
177 '{}')
178 # Replay, create client, assert
179 client = http.HTTPClient('http://example.com:8004')
180 resp, body = client.json_request('GET', '')
181 self.assertEqual(200, resp.status_code)
182 self.assertEqual({}, body)
183 mock_request.assert_called_with(
184 'GET', 'http://example.com:8004',
185 allow_redirects=False,
186 headers={'Content-Type': 'application/json',
187 'Accept': 'application/json',
188 'User-Agent': 'python-heatclient'})
189
190 def test_http_json_request_argument_passed_to_requests(self, mock_request):
191 """Check that we have sent the proper arguments to requests."""
192 # Record a 200
193 mock_request.return_value = fakes.FakeHTTPResponse(
194 200, 'OK',
195 {'content-type': 'application/json'},
196 '{}')
197
198 client = http.HTTPClient('http://example.com:8004')
199 client.verify_cert = True
200 client.cert_file = 'RANDOM_CERT_FILE'
201 client.key_file = 'RANDOM_KEY_FILE'
202 client.auth_url = 'http://AUTH_URL'
203 resp, body = client.json_request('GET', '', data='text')
204 self.assertEqual(200, resp.status_code)
205 self.assertEqual({}, body)
206 mock_request.assert_called_with(
207 'GET', 'http://example.com:8004',
208 allow_redirects=False,
209 cert=('RANDOM_CERT_FILE', 'RANDOM_KEY_FILE'),
210 verify=True,
211 data='"text"',
212 headers={'Content-Type': 'application/json',
213 'Accept': 'application/json',
214 'X-Auth-Url': 'http://AUTH_URL',
215 'User-Agent': 'python-heatclient'})
216
217 def test_http_json_request_w_req_body(self, mock_request):
218 # Record a 200
219 mock_request.return_value = fakes.FakeHTTPResponse(
220 200, 'OK',
221 {'content-type': 'application/json'},
222 '{}')
223 # Replay, create client, assert
224 client = http.HTTPClient('http://example.com:8004')
225 resp, body = client.json_request('GET', '', body='test-body')
226 self.assertEqual(200, resp.status_code)
227 mock_request.assert_called_with(
228 'GET', 'http://example.com:8004',
229 body='test-body',
230 allow_redirects=False,
231 headers={'Content-Type': 'application/json',
232 'Accept': 'application/json',
233 'User-Agent': 'python-heatclient'})
234
235 def test_http_json_request_non_json_resp_cont_type(self, mock_request):
236 # Record a 200i
237 mock_request.return_value = fakes.FakeHTTPResponse(
238 200, 'OK',
239 {'content-type': 'not/json'},
240 '{}')
241 # Replay, create client, assert
242 client = http.HTTPClient('http://example.com:8004')
243 resp, body = client.json_request('GET', '', body='test-body')
244 self.assertEqual(200, resp.status_code)
245 self.assertIsNone(body)
246 mock_request.assert_called_with(
247 'GET', 'http://example.com:8004',
248 body='test-body',
249 allow_redirects=False,
250 headers={'Content-Type': 'application/json',
251 'Accept': 'application/json',
252 'User-Agent': 'python-heatclient'})
253
254 def test_http_json_request_invalid_json(self, mock_request):
255 # Record a 200
256 mock_request.return_value = fakes.FakeHTTPResponse(
257 200, 'OK',
258 {'content-type': 'application/json'},
259 'invalid-json')
260
261 # Replay, create client, assert
262 client = http.HTTPClient('http://example.com:8004')
263 resp, body = client.json_request('GET', '')
264 self.assertEqual(200, resp.status_code)
265 self.assertEqual('invalid-json', body)
266 mock_request.assert_called_with(
267 'GET', 'http://example.com:8004',
268 allow_redirects=False,
269 headers={'Content-Type': 'application/json',
270 'Accept': 'application/json',
271 'User-Agent': 'python-heatclient'})
272
273 def test_http_manual_redirect_delete(self, mock_request):
274 mock_request.side_effect = [
275 fakes.FakeHTTPResponse(
276 302, 'Found',
277 {'location': 'http://example.com:8004/foo/bar'},
278 ''),
279 fakes.FakeHTTPResponse(
280 200, 'OK',
281 {'content-type': 'application/json'},
282 'invalid-json')
283 ]
284
285 client = http.HTTPClient('http://example.com:8004/foo')
286 resp, body = client.json_request('DELETE', '')
287
288 mock_request.assert_has_calls([
289 mock.call('DELETE', 'http://example.com:8004/foo',
290 allow_redirects=False,
291 headers={'Content-Type': 'application/json',
292 'Accept': 'application/json',
293 'User-Agent': 'python-heatclient'}),
294 mock.call('DELETE', 'http://example.com:8004/foo/bar',
295 allow_redirects=False,
296 headers={'Content-Type': 'application/json',
297 'Accept': 'application/json',
298 'User-Agent': 'python-heatclient'})
299 ])
300
301 def test_http_manual_redirect_post(self, mock_request):
302 mock_request.side_effect = [
303 fakes.FakeHTTPResponse(
304 302, 'Found',
305 {'location': 'http://example.com:8004/foo/bar'},
306 ''),
307 fakes.FakeHTTPResponse(
308 200, 'OK',
309 {'content-type': 'application/json'},
310 'invalid-json')
311 ]
312
313 client = http.HTTPClient('http://example.com:8004/foo')
314 resp, body = client.json_request('POST', '')
315
316 mock_request.assert_has_calls([
317 mock.call('POST', 'http://example.com:8004/foo',
318 allow_redirects=False,
319 headers={'Content-Type': 'application/json',
320 'Accept': 'application/json',
321 'User-Agent': 'python-heatclient'}),
322 mock.call('POST', 'http://example.com:8004/foo/bar',
323 allow_redirects=False,
324 headers={'Content-Type': 'application/json',
325 'Accept': 'application/json',
326 'User-Agent': 'python-heatclient'})
327 ])
328
329 def test_http_manual_redirect_put(self, mock_request):
330 mock_request.side_effect = [
331 fakes.FakeHTTPResponse(
332 302, 'Found',
333 {'location': 'http://example.com:8004/foo/bar'},
334 ''),
335 fakes.FakeHTTPResponse(
336 200, 'OK',
337 {'content-type': 'application/json'},
338 'invalid-json')
339 ]
340
341 client = http.HTTPClient('http://example.com:8004/foo')
342 resp, body = client.json_request('PUT', '')
343
344 mock_request.assert_has_calls([
345 mock.call('PUT', 'http://example.com:8004/foo',
346 allow_redirects=False,
347 headers={'Content-Type': 'application/json',
348 'Accept': 'application/json',
349 'User-Agent': 'python-heatclient'}),
350 mock.call('PUT', 'http://example.com:8004/foo/bar',
351 allow_redirects=False,
352 headers={'Content-Type': 'application/json',
353 'Accept': 'application/json',
354 'User-Agent': 'python-heatclient'})
355 ])
356
357 def test_http_manual_redirect_put_uppercase(self, mock_request):
358 mock_request.side_effect = [
359 fakes.FakeHTTPResponse(
360 302, 'Found',
361 {'location': 'http://example.com:8004/foo/bar'},
362 ''),
363 fakes.FakeHTTPResponse(
364 200, 'OK',
365 {'content-type': 'application/json'},
366 'invalid-json')
367 ]
368 client = http.HTTPClient('http://EXAMPLE.com:8004/foo')
369 resp, body = client.json_request('PUT', '')
370 self.assertEqual(200, resp.status_code)
371
372 mock_request.assert_has_calls([
373 mock.call('PUT', 'http://EXAMPLE.com:8004/foo',
374 allow_redirects=False,
375 headers={'Content-Type': 'application/json',
376 'Accept': 'application/json',
377 'User-Agent': 'python-heatclient'}),
378 mock.call('PUT', 'http://example.com:8004/foo/bar',
379 allow_redirects=False,
380 headers={'Content-Type': 'application/json',
381 'Accept': 'application/json',
382 'User-Agent': 'python-heatclient'})
383 ])
384
385 def test_http_manual_redirect_error_without_location(self, mock_request):
386 mock_request.return_value = fakes.FakeHTTPResponse(
387 302, 'Found',
388 {},
389 '')
390 client = http.HTTPClient('http://example.com:8004/foo')
391 self.assertRaises(exc.InvalidEndpoint,
392 client.json_request, 'DELETE', '')
393 mock_request.assert_called_once_with(
394 'DELETE', 'http://example.com:8004/foo',
395 allow_redirects=False,
396 headers={'Content-Type': 'application/json',
397 'Accept': 'application/json',
398 'User-Agent': 'python-heatclient'})
399
400 def test_http_json_request_redirect(self, mock_request):
401 # Record the 302
402 mock_request.side_effect = [
403 fakes.FakeHTTPResponse(
404 302, 'Found',
405 {'location': 'http://example.com:8004'},
406 ''),
407 fakes.FakeHTTPResponse(
408 200, 'OK',
409 {'content-type': 'application/json'},
410 '{}')
411 ]
412 client = http.HTTPClient('http://example.com:8004')
413 resp, body = client.json_request('GET', '')
414 self.assertEqual(200, resp.status_code)
415 self.assertEqual({}, body)
416 mock_request.assert_has_calls([
417 mock.call('GET', 'http://example.com:8004',
418 allow_redirects=False,
419 headers={'Content-Type': 'application/json',
420 'Accept': 'application/json',
421 'User-Agent': 'python-heatclient'}),
422 mock.call('GET', 'http://example.com:8004',
423 allow_redirects=False,
424 headers={'Content-Type': 'application/json',
425 'Accept': 'application/json',
426 'User-Agent': 'python-heatclient'})
427 ])
428
429 def test_http_404_json_request(self, mock_request):
430 # Record a 404
431 mock_request.return_value = fakes.FakeHTTPResponse(
432 404, 'OK', {'content-type': 'application/json'},
433 '{}')
434 client = http.HTTPClient('http://example.com:8004')
435 e = self.assertRaises(exc.HTTPNotFound, client.json_request, 'GET', '')
436 # Assert that the raised exception can be converted to string
437 self.assertIsNotNone(str(e))
438 mock_request.assert_called_with(
439 'GET', 'http://example.com:8004',
440 allow_redirects=False,
441 headers={'Content-Type': 'application/json',
442 'Accept': 'application/json',
443 'User-Agent': 'python-heatclient'})
444
445 def test_http_300_json_request(self, mock_request):
446 # Record a 300
447 mock_request.return_value = fakes.FakeHTTPResponse(
448 300, 'OK', {'content-type': 'application/json'},
449 '{}')
450 # Assert that the raised exception can be converted to string
451 client = http.HTTPClient('http://example.com:8004')
452 e = self.assertRaises(
453 exc.HTTPMultipleChoices, client.json_request, 'GET', '')
454 self.assertIsNotNone(str(e))
455 mock_request.assert_called_with(
456 'GET', 'http://example.com:8004',
457 allow_redirects=False,
458 headers={'Content-Type': 'application/json',
459 'Accept': 'application/json',
460 'User-Agent': 'python-heatclient'})
461
462 def test_fake_json_request(self, mock_request):
463 headers = {'User-Agent': 'python-heatclient'}
464 mock_request.side_effect = [socket.gaierror]
465 client = http.HTTPClient('fake://example.com:8004')
466 self.assertRaises(exc.InvalidEndpoint,
467 client._http_request, "/", "GET")
468
469 mock_request.assert_called_with('GET', 'fake://example.com:8004/',
470 allow_redirects=False,
471 headers=headers)
472
473 def test_debug_curl_command(self, mock_request):
474 with mock.patch('logging.Logger.debug') as mock_logging_debug:
475
476 ssl_connection_params = {'ca_file': 'TEST_CA',
477 'cert_file': 'TEST_CERT',
478 'key_file': 'TEST_KEY',
479 'insecure': 'TEST_NSA'}
480
481 headers = {'key': 'value'}
482 mock_logging_debug.return_value = None
483 client = http.HTTPClient('http://foo')
484 client.ssl_connection_params = ssl_connection_params
485 client.log_curl_request('GET', '/bar', {'headers': headers,
486 'data': 'text'})
487 mock_logging_debug.assert_called_with(
488 "curl -g -i -X GET -H 'key: value' --key TEST_KEY "
489 "--cert TEST_CERT --cacert TEST_CA "
490 "-k -d 'text' http://foo/bar"
491 )
492
493 def test_http_request_socket_error(self, mock_request):
494 headers = {'User-Agent': 'python-heatclient'}
495 mock_request.side_effect = [socket.error]
496
497 client = http.HTTPClient('http://example.com:8004')
498 self.assertRaises(exc.CommunicationError,
499 client._http_request, "/", "GET")
500 mock_request.assert_called_with('GET', 'http://example.com:8004/',
501 allow_redirects=False,
502 headers=headers)
503
504 def test_http_request_socket_timeout(self, mock_request):
505 headers = {'User-Agent': 'python-heatclient'}
506 mock_request.side_effect = [socket.timeout]
507
508 client = http.HTTPClient('http://example.com:8004')
509 self.assertRaises(exc.CommunicationError,
510 client._http_request, "/", "GET")
511 mock_request.assert_called_with('GET', 'http://example.com:8004/',
512 allow_redirects=False,
513 headers=headers)
514
515 def test_http_request_specify_timeout(self, mock_request):
516 mock_request.return_value = fakes.FakeHTTPResponse(
517 200, 'OK',
518 {'content-type': 'application/json'},
519 '{}')
520 client = http.HTTPClient('http://example.com:8004', timeout='123')
521 resp, body = client.json_request('GET', '')
522 self.assertEqual(200, resp.status_code)
523 mock_request.assert_called_with(
524 'GET', 'http://example.com:8004',
525 allow_redirects=False,
526 headers={'Content-Type': 'application/json',
527 'Accept': 'application/json',
528 'User-Agent': 'python-heatclient'},
529 timeout=float(123))
530
531 def test_get_system_ca_file(self, mock_request):
532 chosen = '/etc/ssl/certs/ca-certificates.crt'
533 with mock.patch('os.path.exists') as mock_os:
534 mock_os.return_value = chosen
535 ca = http.get_system_ca_file()
536 self.assertEqual(chosen, ca)
537 mock_os.assert_called_once_with(chosen)
538
539 def test_insecure_verify_cert_None(self, mock_request):
540 client = http.HTTPClient('https://foo', insecure=True)
541 self.assertFalse(client.verify_cert)
542
543 def test_passed_cert_to_verify_cert(self, mock_request):
544 client = http.HTTPClient('https://foo', ca_file="NOWHERE")
545 self.assertEqual("NOWHERE", client.verify_cert)
546
547 with mock.patch('heatclient.common.http.get_system_ca_file') as gsf:
548 gsf.return_value = "SOMEWHERE"
549 client = http.HTTPClient('https://foo')
550 self.assertEqual("SOMEWHERE", client.verify_cert)
551
552 @mock.patch('logging.Logger.debug', return_value=None)
553 def test_curl_log_i18n_headers(self, mock_log, mock_request):
554 kwargs = {'headers': {'Key': b'foo\xe3\x8a\x8e'}}
555
556 client = http.HTTPClient('http://somewhere')
557 client.log_curl_request("GET", '', kwargs=kwargs)
558 mock_log.assert_called_once_with(
559 "curl -g -i -X GET -H 'Key: foo㊎' http://somewhere")
560
561
562 class SessionClientTest(testtools.TestCase):
563 def setUp(self):
564 super().setUp()
565 self.request = mock.patch.object(adapter.LegacyJsonAdapter,
566 'request').start()
567
568 def test_session_simple_request(self):
569 resp = fakes.FakeHTTPResponse(
570 200,
571 'OK',
572 {'content-type': 'application/octet-stream'},
573 '')
574 self.request.return_value = (resp, '')
575
576 client = http.SessionClient(session=mock.ANY,
577 auth=mock.ANY)
578 response = client.request(method='GET', url='')
579 self.assertEqual(200, response.status_code)
580 self.assertEqual('', ''.join([x for x in response.content]))
581
582 def test_session_json_request(self):
583 fake = fakes.FakeHTTPResponse(
584 200,
585 'OK',
586 {'content-type': 'application/json'},
587 jsonutils.dumps({'some': 'body'}))
588 self.request.return_value = (fake, {})
589
590 client = http.SessionClient(session=mock.ANY,
591 auth=mock.ANY)
592
593 resp = client.request('', 'GET')
594 self.assertEqual(200, resp.status_code)
595 self.assertEqual({'some': 'body'}, resp.json())
596
597 def test_404_error_response(self):
598 fake = fakes.FakeHTTPResponse(
599 404,
600 'FAIL',
601 {'content-type': 'application/octet-stream'},
602 '')
603 self.request.return_value = (fake, '')
604
605 client = http.SessionClient(session=mock.ANY,
606 auth=mock.ANY)
607 e = self.assertRaises(exc.HTTPNotFound,
608 client.request, '', 'GET')
609 # Assert that the raised exception can be converted to string
610 self.assertIsNotNone(str(e))
611
612 def test_redirect_302_location(self):
613 fake1 = fakes.FakeHTTPResponse(
614 302,
615 'OK',
616 {'location': 'http://no.where/ishere'},
617 ''
618 )
619 fake2 = fakes.FakeHTTPResponse(
620 200,
621 'OK',
622 {'content-type': 'application/json'},
623 jsonutils.dumps({'Mount': 'Fuji'})
624 )
625 self.request.side_effect = [
626 (fake1, ''), (fake2, jsonutils.dumps({'Mount': 'Fuji'}))]
627
628 client = http.SessionClient(session=mock.ANY,
629 auth=mock.ANY,
630 endpoint_override='http://no.where/')
631 resp = client.request('', 'GET', redirect=True)
632
633 self.assertEqual(200, resp.status_code)
634 self.assertEqual({'Mount': 'Fuji'}, utils.get_response_body(resp))
635
636 self.assertEqual(('', 'GET'), self.request.call_args_list[0][0])
637 self.assertEqual(('ishere', 'GET'), self.request.call_args_list[1][0])
638 for call in self.request.call_args_list:
639 self.assertEqual({'headers': {'Content-Type': 'application/json'},
640 'user_agent': 'python-heatclient',
641 'raise_exc': False,
642 'redirect': True}, call[1])
643
644 def test_302_location_no_endpoint(self):
645 fake1 = fakes.FakeHTTPResponse(
646 302,
647 'OK',
648 {'location': 'http://no.where/ishere'},
649 ''
650 )
651 fake2 = fakes.FakeHTTPResponse(
652 200,
653 'OK',
654 {'content-type': 'application/json'},
655 jsonutils.dumps({'Mount': 'Fuji'})
656 )
657 self.request.side_effect = [
658 (fake1, ''), (fake2, jsonutils.dumps({'Mount': 'Fuji'}))]
659
660 client = http.SessionClient(session=mock.ANY,
661 auth=mock.ANY)
662 resp = client.request('', 'GET', redirect=True)
663
664 self.assertEqual(200, resp.status_code)
665 self.assertEqual({'Mount': 'Fuji'}, utils.get_response_body(resp))
666
667 self.assertEqual(('', 'GET'), self.request.call_args_list[0][0])
668 self.assertEqual(('http://no.where/ishere',
669 'GET'), self.request.call_args_list[1][0])
670 for call in self.request.call_args_list:
671 self.assertEqual({'headers': {'Content-Type': 'application/json'},
672 'user_agent': 'python-heatclient',
673 'raise_exc': False,
674 'redirect': True}, call[1])
675
676 def test_redirect_302_no_location(self):
677 fake = fakes.FakeHTTPResponse(
678 302,
679 'OK',
680 {},
681 ''
682 )
683 self.request.side_effect = [(fake, '')]
684
685 client = http.SessionClient(session=mock.ANY,
686 auth=mock.ANY)
687 e = self.assertRaises(exc.InvalidEndpoint,
688 client.request, '', 'GET', redirect=True)
689 self.assertEqual("Location not returned with 302", str(e))
690
691 def test_no_redirect_302_no_location(self):
692 fake = fakes.FakeHTTPResponse(
693 302,
694 'OK',
695 {'location': 'http://no.where/ishere'},
696 ''
697 )
698 self.request.side_effect = [(fake, '')]
699
700 client = http.SessionClient(session=mock.ANY,
701 auth=mock.ANY)
702
703 self.assertEqual(fake, client.request('', 'GET'))
704
705 def test_300_error_response(self):
706 fake = fakes.FakeHTTPResponse(
707 300,
708 'FAIL',
709 {'content-type': 'application/octet-stream'},
710 '')
711 self.request.return_value = (fake, '')
712
713 client = http.SessionClient(session=mock.ANY,
714 auth=mock.ANY)
715 e = self.assertRaises(exc.HTTPMultipleChoices,
716 client.request, '', 'GET')
717 # Assert that the raised exception can be converted to string
718 self.assertIsNotNone(str(e))
719
720 def test_504_error_response(self):
721 # for 504 we don't have specific exception type
722 fake = fakes.FakeHTTPResponse(
723 504,
724 'FAIL',
725 {'content-type': 'application/octet-stream'},
726 '')
727 self.request.return_value = (fake, '')
728
729 client = http.SessionClient(session=mock.ANY,
730 auth=mock.ANY)
731 e = self.assertRaises(exc.HTTPException,
732 client.request, '', 'GET')
733
734 self.assertEqual(504, e.code)
735
736 def test_kwargs(self):
737 fake = fakes.FakeHTTPResponse(
738 200,
739 'OK',
740 {'content-type': 'application/json'},
741 {}
742 )
743 kwargs = dict(endpoint_override='http://no.where/',
744 data='some_data')
745
746 client = http.SessionClient(mock.ANY)
747
748 self.request.return_value = (fake, {})
749
750 resp = client.request('', 'GET', **kwargs)
751
752 self.assertEqual({'endpoint_override': 'http://no.where/',
753 'data': '"some_data"',
754 'headers': {'Content-Type': 'application/json'},
755 'user_agent': 'python-heatclient',
756 'raise_exc': False}, self.request.call_args[1])
757 self.assertEqual(200, resp.status_code)
758
759 @mock.patch.object(jsonutils, 'dumps')
760 def test_kwargs_with_files(self, mock_dumps):
761 fake = fakes.FakeHTTPResponse(
762 200,
763 'OK',
764 {'content-type': 'application/json'},
765 {}
766 )
767 mock_dumps.return_value = "{'files': test}}"
768 data = io.BytesIO(b'test')
769 kwargs = {'endpoint_override': 'http://no.where/',
770 'data': {'files': data}}
771 client = http.SessionClient(mock.ANY)
772
773 self.request.return_value = (fake, {})
774
775 resp = client.request('', 'GET', **kwargs)
776
777 self.assertEqual({'endpoint_override': 'http://no.where/',
778 'data': "{'files': test}}",
779 'headers': {'Content-Type': 'application/json'},
780 'user_agent': 'python-heatclient',
781 'raise_exc': False}, self.request.call_args[1])
782 self.assertEqual(200, resp.status_code)
783
784 def test_methods(self):
785 fake = fakes.FakeHTTPResponse(
786 200,
787 'OK',
788 {'content-type': 'application/json'},
789 {}
790 )
791 self.request.return_value = (fake, {})
792
793 client = http.SessionClient(mock.ANY)
794 methods = [client.get, client.put, client.post, client.patch,
795 client.delete, client.head]
796 for method in methods:
797 resp = method('')
798 self.assertEqual(200, resp.status_code)
799
800 def test_credentials_headers(self):
801 client = http.SessionClient(mock.ANY)
802 self.assertEqual({}, client.credentials_headers())