summaryrefslogtreecommitdiff
path: root/heatclient/tests/unit/test_common_http.py
blob: eb124ca8a705fb4f8d4ad8c2885b52ed8a4be1bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
# -*- coding:utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import socket
from unittest import mock

import io
from keystoneauth1 import adapter
from oslo_serialization import jsonutils
import testtools

from heatclient.common import http
from heatclient.common import utils
from heatclient import exc
from heatclient.tests.unit import fakes


@mock.patch('heatclient.common.http.requests.request')
class HttpClientTest(testtools.TestCase):

    def test_http_raw_request(self, mock_request):
        headers = {'Content-Type': 'application/octet-stream',
                   'User-Agent': 'python-heatclient'}

        # Record a 200
        mock_request.return_value = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'application/octet-stream'},
            '')
        # Replay, create client, assert
        client = http.HTTPClient('http://example.com:8004')
        resp = client.raw_request('GET', '')
        self.assertEqual(200, resp.status_code)
        self.assertEqual('', ''.join([x for x in resp.content]))
        mock_request.assert_called_with('GET', 'http://example.com:8004',
                                        allow_redirects=False,
                                        headers=headers)

    def test_token_or_credentials(self, mock_request):
        # Record a 200
        fake200 = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'application/octet-stream'},
            '')

        mock_request.return_value = fake200
        # no token or credentials
        client = http.HTTPClient('http://example.com:8004')
        resp = client.raw_request('GET', '')
        self.assertEqual(200, resp.status_code)
        # credentials
        client.username = 'user'
        client.password = 'pass'
        resp = client.raw_request('GET', '')
        self.assertEqual(200, resp.status_code)
        # token suppresses credentials
        client.auth_token = 'abcd1234'
        resp = client.raw_request('GET', '')
        self.assertEqual(200, resp.status_code)
        mock_request.assert_has_calls([
            mock.call('GET', 'http://example.com:8004',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/octet-stream',
                               'User-Agent': 'python-heatclient'}),
            mock.call('GET', 'http://example.com:8004',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/octet-stream',
                               'User-Agent': 'python-heatclient',
                               'X-Auth-Key': 'pass',
                               'X-Auth-User': 'user'}),
            mock.call('GET', 'http://example.com:8004',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/octet-stream',
                               'User-Agent': 'python-heatclient',
                               'X-Auth-Token': 'abcd1234'})
        ])

    def test_include_pass(self, mock_request):
        # Record a 200
        fake200 = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'application/octet-stream'},
            '')
        mock_request.return_value = fake200
        # no token or credentials
        client = http.HTTPClient('http://example.com:8004')
        resp = client.raw_request('GET', '')
        self.assertEqual(200, resp.status_code)
        # credentials
        client.username = 'user'
        client.password = 'pass'
        client.include_pass = True
        resp = client.raw_request('GET', '')
        self.assertEqual(200, resp.status_code)
        # token suppresses credentials
        client.auth_token = 'abcd1234'
        resp = client.raw_request('GET', '')
        self.assertEqual(200, resp.status_code)
        mock_request.assert_has_calls([
            mock.call('GET', 'http://example.com:8004',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/octet-stream',
                               'User-Agent': 'python-heatclient'}),
            mock.call('GET', 'http://example.com:8004',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/octet-stream',
                               'User-Agent': 'python-heatclient',
                               'X-Auth-Key': 'pass',
                               'X-Auth-User': 'user'}),
            mock.call('GET', 'http://example.com:8004',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/octet-stream',
                               'User-Agent': 'python-heatclient',
                               'X-Auth-Token': 'abcd1234',
                               'X-Auth-Key': 'pass',
                               'X-Auth-User': 'user'})
        ])

    def test_not_include_pass(self, mock_request):
        # Record a 200
        fake500 = fakes.FakeHTTPResponse(
            500, 'ERROR',
            {'content-type': 'application/octet-stream'},
            b'(HTTP 401)')

        # no token or credentials
        mock_request.return_value = fake500

        # Replay, create client, assert
        client = http.HTTPClient('http://example.com:8004')
        e = self.assertRaises(exc.HTTPUnauthorized,
                              client.raw_request, 'GET', '')
        self.assertIn('Authentication failed', str(e))
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            allow_redirects=False,
            headers={'Content-Type': 'application/octet-stream',
                     'User-Agent': 'python-heatclient'})

    def test_region_name(self, mock_request):
        # Record a 200
        fake200 = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'application/octet-stream'},
            '')

        # Specify region name
        mock_request.return_value = fake200

        # Replay, create client, assert
        client = http.HTTPClient('http://example.com:8004')
        client.region_name = 'RegionOne'
        resp = client.raw_request('GET', '')
        self.assertEqual(200, resp.status_code)
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            allow_redirects=False,
            headers={'Content-Type': 'application/octet-stream',
                     'X-Region-Name': 'RegionOne',
                     'User-Agent': 'python-heatclient'})

    def test_http_json_request(self, mock_request):
        # Record a 200
        mock_request.return_value = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'application/json'},
            '{}')
        # Replay, create client, assert
        client = http.HTTPClient('http://example.com:8004')
        resp, body = client.json_request('GET', '')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({}, body)
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            allow_redirects=False,
            headers={'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'User-Agent': 'python-heatclient'})

    def test_http_json_request_argument_passed_to_requests(self, mock_request):
        """Check that we have sent the proper arguments to requests."""
        # Record a 200
        mock_request.return_value = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'application/json'},
            '{}')

        client = http.HTTPClient('http://example.com:8004')
        client.verify_cert = True
        client.cert_file = 'RANDOM_CERT_FILE'
        client.key_file = 'RANDOM_KEY_FILE'
        client.auth_url = 'http://AUTH_URL'
        resp, body = client.json_request('GET', '', data='text')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({}, body)
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            allow_redirects=False,
            cert=('RANDOM_CERT_FILE', 'RANDOM_KEY_FILE'),
            verify=True,
            data='"text"',
            headers={'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'X-Auth-Url': 'http://AUTH_URL',
                     'User-Agent': 'python-heatclient'})

    def test_http_json_request_w_req_body(self, mock_request):
        # Record a 200
        mock_request.return_value = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'application/json'},
            '{}')
        # Replay, create client, assert
        client = http.HTTPClient('http://example.com:8004')
        resp, body = client.json_request('GET', '', body='test-body')
        self.assertEqual(200, resp.status_code)
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            body='test-body',
            allow_redirects=False,
            headers={'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'User-Agent': 'python-heatclient'})

    def test_http_json_request_non_json_resp_cont_type(self, mock_request):
        # Record a 200i
        mock_request.return_value = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'not/json'},
            '{}')
        # Replay, create client, assert
        client = http.HTTPClient('http://example.com:8004')
        resp, body = client.json_request('GET', '', body='test-body')
        self.assertEqual(200, resp.status_code)
        self.assertIsNone(body)
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            body='test-body',
            allow_redirects=False,
            headers={'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'User-Agent': 'python-heatclient'})

    def test_http_json_request_invalid_json(self, mock_request):
        # Record a 200
        mock_request.return_value = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'application/json'},
            'invalid-json')

        # Replay, create client, assert
        client = http.HTTPClient('http://example.com:8004')
        resp, body = client.json_request('GET', '')
        self.assertEqual(200, resp.status_code)
        self.assertEqual('invalid-json', body)
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            allow_redirects=False,
            headers={'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'User-Agent': 'python-heatclient'})

    def test_http_manual_redirect_delete(self, mock_request):
        mock_request.side_effect = [
            fakes.FakeHTTPResponse(
                302, 'Found',
                {'location': 'http://example.com:8004/foo/bar'},
                ''),
            fakes.FakeHTTPResponse(
                200, 'OK',
                {'content-type': 'application/json'},
                'invalid-json')
        ]

        client = http.HTTPClient('http://example.com:8004/foo')
        resp, body = client.json_request('DELETE', '')

        mock_request.assert_has_calls([
            mock.call('DELETE', 'http://example.com:8004/foo',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'}),
            mock.call('DELETE', 'http://example.com:8004/foo/bar',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'})
        ])

    def test_http_manual_redirect_post(self, mock_request):
        mock_request.side_effect = [
            fakes.FakeHTTPResponse(
                302, 'Found',
                {'location': 'http://example.com:8004/foo/bar'},
                ''),
            fakes.FakeHTTPResponse(
                200, 'OK',
                {'content-type': 'application/json'},
                'invalid-json')
        ]

        client = http.HTTPClient('http://example.com:8004/foo')
        resp, body = client.json_request('POST', '')

        mock_request.assert_has_calls([
            mock.call('POST', 'http://example.com:8004/foo',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'}),
            mock.call('POST', 'http://example.com:8004/foo/bar',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'})
        ])

    def test_http_manual_redirect_put(self, mock_request):
        mock_request.side_effect = [
            fakes.FakeHTTPResponse(
                302, 'Found',
                {'location': 'http://example.com:8004/foo/bar'},
                ''),
            fakes.FakeHTTPResponse(
                200, 'OK',
                {'content-type': 'application/json'},
                'invalid-json')
        ]

        client = http.HTTPClient('http://example.com:8004/foo')
        resp, body = client.json_request('PUT', '')

        mock_request.assert_has_calls([
            mock.call('PUT', 'http://example.com:8004/foo',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'}),
            mock.call('PUT', 'http://example.com:8004/foo/bar',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'})
        ])

    def test_http_manual_redirect_put_uppercase(self, mock_request):
        mock_request.side_effect = [
            fakes.FakeHTTPResponse(
                302, 'Found',
                {'location': 'http://example.com:8004/foo/bar'},
                ''),
            fakes.FakeHTTPResponse(
                200, 'OK',
                {'content-type': 'application/json'},
                'invalid-json')
        ]
        client = http.HTTPClient('http://EXAMPLE.com:8004/foo')
        resp, body = client.json_request('PUT', '')
        self.assertEqual(200, resp.status_code)

        mock_request.assert_has_calls([
            mock.call('PUT', 'http://EXAMPLE.com:8004/foo',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'}),
            mock.call('PUT', 'http://example.com:8004/foo/bar',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'})
        ])

    def test_http_manual_redirect_error_without_location(self, mock_request):
        mock_request.return_value = fakes.FakeHTTPResponse(
            302, 'Found',
            {},
            '')
        client = http.HTTPClient('http://example.com:8004/foo')
        self.assertRaises(exc.InvalidEndpoint,
                          client.json_request, 'DELETE', '')
        mock_request.assert_called_once_with(
            'DELETE', 'http://example.com:8004/foo',
            allow_redirects=False,
            headers={'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'User-Agent': 'python-heatclient'})

    def test_http_json_request_redirect(self, mock_request):
        # Record the 302
        mock_request.side_effect = [
            fakes.FakeHTTPResponse(
                302, 'Found',
                {'location': 'http://example.com:8004'},
                ''),
            fakes.FakeHTTPResponse(
                200, 'OK',
                {'content-type': 'application/json'},
                '{}')
        ]
        client = http.HTTPClient('http://example.com:8004')
        resp, body = client.json_request('GET', '')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({}, body)
        mock_request.assert_has_calls([
            mock.call('GET', 'http://example.com:8004',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'}),
            mock.call('GET', 'http://example.com:8004',
                      allow_redirects=False,
                      headers={'Content-Type': 'application/json',
                               'Accept': 'application/json',
                               'User-Agent': 'python-heatclient'})
        ])

    def test_http_404_json_request(self, mock_request):
        # Record a 404
        mock_request.return_value = fakes.FakeHTTPResponse(
            404, 'OK', {'content-type': 'application/json'},
            '{}')
        client = http.HTTPClient('http://example.com:8004')
        e = self.assertRaises(exc.HTTPNotFound, client.json_request, 'GET', '')
        # Assert that the raised exception can be converted to string
        self.assertIsNotNone(str(e))
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            allow_redirects=False,
            headers={'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'User-Agent': 'python-heatclient'})

    def test_http_300_json_request(self, mock_request):
        # Record a 300
        mock_request.return_value = fakes.FakeHTTPResponse(
            300, 'OK', {'content-type': 'application/json'},
            '{}')
        # Assert that the raised exception can be converted to string
        client = http.HTTPClient('http://example.com:8004')
        e = self.assertRaises(
            exc.HTTPMultipleChoices, client.json_request, 'GET', '')
        self.assertIsNotNone(str(e))
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            allow_redirects=False,
            headers={'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'User-Agent': 'python-heatclient'})

    def test_fake_json_request(self, mock_request):
        headers = {'User-Agent': 'python-heatclient'}
        mock_request.side_effect = [socket.gaierror]
        client = http.HTTPClient('fake://example.com:8004')
        self.assertRaises(exc.InvalidEndpoint,
                          client._http_request, "/", "GET")

        mock_request.assert_called_with('GET', 'fake://example.com:8004/',
                                        allow_redirects=False,
                                        headers=headers)

    def test_debug_curl_command(self, mock_request):
        with mock.patch('logging.Logger.debug') as mock_logging_debug:

            ssl_connection_params = {'ca_file': 'TEST_CA',
                                     'cert_file': 'TEST_CERT',
                                     'key_file': 'TEST_KEY',
                                     'insecure': 'TEST_NSA'}

            headers = {'key': 'value'}
            mock_logging_debug.return_value = None
            client = http.HTTPClient('http://foo')
            client.ssl_connection_params = ssl_connection_params
            client.log_curl_request('GET', '/bar', {'headers': headers,
                                                    'data': 'text'})
            mock_logging_debug.assert_called_with(
                "curl -g -i -X GET -H 'key: value' --key TEST_KEY "
                "--cert TEST_CERT --cacert TEST_CA "
                "-k -d 'text' http://foo/bar"
            )

    def test_http_request_socket_error(self, mock_request):
        headers = {'User-Agent': 'python-heatclient'}
        mock_request.side_effect = [socket.error]

        client = http.HTTPClient('http://example.com:8004')
        self.assertRaises(exc.CommunicationError,
                          client._http_request, "/", "GET")
        mock_request.assert_called_with('GET', 'http://example.com:8004/',
                                        allow_redirects=False,
                                        headers=headers)

    def test_http_request_socket_timeout(self, mock_request):
        headers = {'User-Agent': 'python-heatclient'}
        mock_request.side_effect = [socket.timeout]

        client = http.HTTPClient('http://example.com:8004')
        self.assertRaises(exc.CommunicationError,
                          client._http_request, "/", "GET")
        mock_request.assert_called_with('GET', 'http://example.com:8004/',
                                        allow_redirects=False,
                                        headers=headers)

    def test_http_request_specify_timeout(self, mock_request):
        mock_request.return_value = fakes.FakeHTTPResponse(
            200, 'OK',
            {'content-type': 'application/json'},
            '{}')
        client = http.HTTPClient('http://example.com:8004', timeout='123')
        resp, body = client.json_request('GET', '')
        self.assertEqual(200, resp.status_code)
        mock_request.assert_called_with(
            'GET', 'http://example.com:8004',
            allow_redirects=False,
            headers={'Content-Type': 'application/json',
                     'Accept': 'application/json',
                     'User-Agent': 'python-heatclient'},
            timeout=float(123))

    def test_get_system_ca_file(self, mock_request):
        chosen = '/etc/ssl/certs/ca-certificates.crt'
        with mock.patch('os.path.exists') as mock_os:
            mock_os.return_value = chosen
            ca = http.get_system_ca_file()
            self.assertEqual(chosen, ca)
            mock_os.assert_called_once_with(chosen)

    def test_insecure_verify_cert_None(self, mock_request):
        client = http.HTTPClient('https://foo', insecure=True)
        self.assertFalse(client.verify_cert)

    def test_passed_cert_to_verify_cert(self, mock_request):
        client = http.HTTPClient('https://foo', ca_file="NOWHERE")
        self.assertEqual("NOWHERE", client.verify_cert)

        with mock.patch('heatclient.common.http.get_system_ca_file') as gsf:
            gsf.return_value = "SOMEWHERE"
            client = http.HTTPClient('https://foo')
            self.assertEqual("SOMEWHERE", client.verify_cert)

    @mock.patch('logging.Logger.debug', return_value=None)
    def test_curl_log_i18n_headers(self, mock_log, mock_request):
        kwargs = {'headers': {'Key': b'foo\xe3\x8a\x8e'}}

        client = http.HTTPClient('http://somewhere')
        client.log_curl_request("GET", '', kwargs=kwargs)
        mock_log.assert_called_once_with(
            u"curl -g -i -X GET -H 'Key: foo㊎' http://somewhere")


class SessionClientTest(testtools.TestCase):
    def setUp(self):
        super(SessionClientTest, self).setUp()
        self.request = mock.patch.object(adapter.LegacyJsonAdapter,
                                         'request').start()

    def test_session_simple_request(self):
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/octet-stream'},
            '')
        self.request.return_value = (resp, '')

        client = http.SessionClient(session=mock.ANY,
                                    auth=mock.ANY)
        response = client.request(method='GET', url='')
        self.assertEqual(200, response.status_code)
        self.assertEqual('', ''.join([x for x in response.content]))

    def test_session_json_request(self):
        fake = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps({'some': 'body'}))
        self.request.return_value = (fake, {})

        client = http.SessionClient(session=mock.ANY,
                                    auth=mock.ANY)

        resp = client.request('', 'GET')
        self.assertEqual(200, resp.status_code)
        self.assertEqual({'some': 'body'}, resp.json())

    def test_404_error_response(self):
        fake = fakes.FakeHTTPResponse(
            404,
            'FAIL',
            {'content-type': 'application/octet-stream'},
            '')
        self.request.return_value = (fake, '')

        client = http.SessionClient(session=mock.ANY,
                                    auth=mock.ANY)
        e = self.assertRaises(exc.HTTPNotFound,
                              client.request, '', 'GET')
        # Assert that the raised exception can be converted to string
        self.assertIsNotNone(str(e))

    def test_redirect_302_location(self):
        fake1 = fakes.FakeHTTPResponse(
            302,
            'OK',
            {'location': 'http://no.where/ishere'},
            ''
        )
        fake2 = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps({'Mount': 'Fuji'})
        )
        self.request.side_effect = [
            (fake1, ''), (fake2, jsonutils.dumps({'Mount': 'Fuji'}))]

        client = http.SessionClient(session=mock.ANY,
                                    auth=mock.ANY,
                                    endpoint_override='http://no.where/')
        resp = client.request('', 'GET', redirect=True)

        self.assertEqual(200, resp.status_code)
        self.assertEqual({'Mount': 'Fuji'}, utils.get_response_body(resp))

        self.assertEqual(('', 'GET'), self.request.call_args_list[0][0])
        self.assertEqual(('ishere', 'GET'), self.request.call_args_list[1][0])
        for call in self.request.call_args_list:
            self.assertEqual({'headers': {'Content-Type': 'application/json'},
                              'user_agent': 'python-heatclient',
                              'raise_exc': False,
                              'redirect': True}, call[1])

    def test_302_location_no_endpoint(self):
        fake1 = fakes.FakeHTTPResponse(
            302,
            'OK',
            {'location': 'http://no.where/ishere'},
            ''
        )
        fake2 = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps({'Mount': 'Fuji'})
        )
        self.request.side_effect = [
            (fake1, ''), (fake2, jsonutils.dumps({'Mount': 'Fuji'}))]

        client = http.SessionClient(session=mock.ANY,
                                    auth=mock.ANY)
        resp = client.request('', 'GET', redirect=True)

        self.assertEqual(200, resp.status_code)
        self.assertEqual({'Mount': 'Fuji'}, utils.get_response_body(resp))

        self.assertEqual(('', 'GET'), self.request.call_args_list[0][0])
        self.assertEqual(('http://no.where/ishere',
                          'GET'), self.request.call_args_list[1][0])
        for call in self.request.call_args_list:
            self.assertEqual({'headers': {'Content-Type': 'application/json'},
                              'user_agent': 'python-heatclient',
                              'raise_exc': False,
                              'redirect': True}, call[1])

    def test_redirect_302_no_location(self):
        fake = fakes.FakeHTTPResponse(
            302,
            'OK',
            {},
            ''
        )
        self.request.side_effect = [(fake, '')]

        client = http.SessionClient(session=mock.ANY,
                                    auth=mock.ANY)
        e = self.assertRaises(exc.InvalidEndpoint,
                              client.request, '', 'GET', redirect=True)
        self.assertEqual("Location not returned with 302", str(e))

    def test_no_redirect_302_no_location(self):
        fake = fakes.FakeHTTPResponse(
            302,
            'OK',
            {'location': 'http://no.where/ishere'},
            ''
        )
        self.request.side_effect = [(fake, '')]

        client = http.SessionClient(session=mock.ANY,
                                    auth=mock.ANY)

        self.assertEqual(fake, client.request('', 'GET'))

    def test_300_error_response(self):
        fake = fakes.FakeHTTPResponse(
            300,
            'FAIL',
            {'content-type': 'application/octet-stream'},
            '')
        self.request.return_value = (fake, '')

        client = http.SessionClient(session=mock.ANY,
                                    auth=mock.ANY)
        e = self.assertRaises(exc.HTTPMultipleChoices,
                              client.request, '', 'GET')
        # Assert that the raised exception can be converted to string
        self.assertIsNotNone(str(e))

    def test_504_error_response(self):
        # for 504 we don't have specific exception type
        fake = fakes.FakeHTTPResponse(
            504,
            'FAIL',
            {'content-type': 'application/octet-stream'},
            '')
        self.request.return_value = (fake, '')

        client = http.SessionClient(session=mock.ANY,
                                    auth=mock.ANY)
        e = self.assertRaises(exc.HTTPException,
                              client.request, '', 'GET')

        self.assertEqual(504, e.code)

    def test_kwargs(self):
        fake = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            {}
        )
        kwargs = dict(endpoint_override='http://no.where/',
                      data='some_data')

        client = http.SessionClient(mock.ANY)

        self.request.return_value = (fake, {})

        resp = client.request('', 'GET', **kwargs)

        self.assertEqual({'endpoint_override': 'http://no.where/',
                          'data': '"some_data"',
                          'headers': {'Content-Type': 'application/json'},
                          'user_agent': 'python-heatclient',
                          'raise_exc': False}, self.request.call_args[1])
        self.assertEqual(200, resp.status_code)

    @mock.patch.object(jsonutils, 'dumps')
    def test_kwargs_with_files(self, mock_dumps):
        fake = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            {}
        )
        mock_dumps.return_value = "{'files': test}}"
        data = io.BytesIO(b'test')
        kwargs = {'endpoint_override': 'http://no.where/',
                  'data': {'files': data}}
        client = http.SessionClient(mock.ANY)

        self.request.return_value = (fake, {})

        resp = client.request('', 'GET', **kwargs)

        self.assertEqual({'endpoint_override': 'http://no.where/',
                          'data': "{'files': test}}",
                          'headers': {'Content-Type': 'application/json'},
                          'user_agent': 'python-heatclient',
                          'raise_exc': False}, self.request.call_args[1])
        self.assertEqual(200, resp.status_code)

    def test_methods(self):
        fake = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            {}
        )
        self.request.return_value = (fake, {})

        client = http.SessionClient(mock.ANY)
        methods = [client.get, client.put, client.post, client.patch,
                   client.delete, client.head]
        for method in methods:
            resp = method('')
            self.assertEqual(200, resp.status_code)

    def test_credentials_headers(self):
        client = http.SessionClient(mock.ANY)
        self.assertEqual({}, client.credentials_headers())