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 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
|
# Copyright 2017 Red Hat, Inc.
# All Rights Reserved.
#
# 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.
from http import client as http_client
import json
import time
from unittest import mock
import requests
from sushy import auth as sushy_auth
from sushy import connector
from sushy import exceptions
from sushy.tests.unit import base
class ConnectorMethodsTestCase(base.TestCase):
@mock.patch.object(sushy_auth, 'SessionOrBasicAuth', autospec=True)
def setUp(self, mock_auth):
mock_auth.get_session_key.return_value = None
super().setUp()
self.conn = connector.Connector(
'http://foo.bar:1234', verify=True)
self.conn._auth = mock_auth
self.data = {'fake': 'data'}
self.headers = {'X-Fake': 'header'}
def test_init_with_credentials(self):
conn = connector.Connector('http://foo.bar:1234',
username='admin',
password='password')
self.assertEqual(conn._session.auth, ('admin', 'password'))
def test_init_with_callback(self):
def response_callback(response):
return
conn = connector.Connector('http://foo.bar:1234',
username='admin',
password='password',
response_callback=response_callback)
self.assertIs(conn._response_callback, response_callback)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_get(self, mock__op):
self.conn.get(path='fake/path', data=self.data.copy(),
headers=self.headers.copy())
mock__op.assert_called_once_with(mock.ANY, 'GET', 'fake/path',
data=self.data, headers=self.headers,
blocking=False, timeout=None)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_get_blocking(self, mock__op):
self.conn.get(path='fake/path', data=self.data.copy(),
headers=self.headers.copy(), blocking=True)
mock__op.assert_called_once_with(mock.ANY, 'GET', 'fake/path',
data=self.data, headers=self.headers,
blocking=True, timeout=None)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_post(self, mock__op):
self.conn.post(path='fake/path', data=self.data.copy(),
headers=self.headers.copy())
mock__op.assert_called_once_with(mock.ANY, 'POST', 'fake/path',
data=self.data, headers=self.headers,
blocking=False, timeout=None)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_post_blocking(self, mock__op):
self.conn.post(path='fake/path', data=self.data.copy(),
headers=self.headers.copy(), blocking=True, timeout=120)
mock__op.assert_called_once_with(mock.ANY, 'POST', 'fake/path',
data=self.data, headers=self.headers,
blocking=True, timeout=120)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_patch(self, mock__op):
self.conn.patch(path='fake/path', data=self.data.copy(),
headers=self.headers.copy())
mock__op.assert_called_once_with(mock.ANY, 'PATCH', 'fake/path',
data=self.data, headers=self.headers,
blocking=False, timeout=None)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_patch_blocking(self, mock__op):
self.conn.patch(path='fake/path', data=self.data.copy(), timeout=120,
headers=self.headers.copy(), blocking=True)
mock__op.assert_called_once_with(mock.ANY, 'PATCH', 'fake/path',
data=self.data, headers=self.headers,
blocking=True, timeout=120)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_put(self, mock__op):
self.conn.put(path='fake/path', data=self.data.copy(),
headers=self.headers.copy())
mock__op.assert_called_once_with(mock.ANY, 'PUT', 'fake/path',
data=self.data, headers=self.headers,
blocking=False, timeout=None)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_put_blocking(self, mock__op):
self.conn.put(path='fake/path', data=self.data.copy(), timeout=120,
headers=self.headers.copy(), blocking=True)
mock__op.assert_called_once_with(mock.ANY, 'PUT', 'fake/path',
data=self.data, headers=self.headers,
blocking=True, timeout=120)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_delete(self, mock__op):
self.conn.delete(path='fake/path', data=self.data.copy(),
headers=self.headers.copy())
mock__op.assert_called_once_with(mock.ANY, 'DELETE', 'fake/path',
data=self.data, headers=self.headers,
blocking=False, timeout=None)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_delete_blocking(self, mock__op):
self.conn.delete(path='fake/path', data=self.data.copy(), timeout=120,
headers=self.headers.copy(), blocking=True)
mock__op.assert_called_once_with(mock.ANY, 'DELETE', 'fake/path',
data=self.data, headers=self.headers,
blocking=True, timeout=120)
def test_set_auth(self):
mock_auth = mock.MagicMock()
self.conn.set_auth(mock_auth)
self.assertEqual(mock_auth, self.conn._auth)
def test_set_http_basic_auth(self):
self.conn.set_http_basic_auth('foo', 'secret')
self.assertEqual(('foo', 'secret'), self.conn._session.auth)
def test_set_http_session_auth(self):
self.conn.set_http_session_auth('hash-token')
self.assertIn('X-Auth-Token', self.conn._session.headers)
self.assertEqual(
'hash-token', self.conn._session.headers['X-Auth-Token'])
def test_close(self):
session = mock.Mock(spec=requests.Session)
self.conn._session = session
self.conn.close()
session.close.assert_called_once_with()
class ConnectorOpTestCase(base.TestCase):
@mock.patch.object(sushy_auth, 'SessionOrBasicAuth', autospec=True)
def setUp(self, mock_auth):
mock_auth.get_session_key.return_value = None
mock_auth._session_key = None
self.auth = mock_auth
super().setUp()
self.conn = connector.Connector(
'http://foo.bar:1234', verify=True,
server_side_retries=10, server_side_retries_delay=3)
self.conn._auth = mock_auth
self.data = {'fake': 'data'}
self.headers = {'Accept-Encoding': 'identity', 'OData-Version': '4.0'}
self.session = mock.Mock(spec=requests.Session)
self.conn._session = self.session
self.request = self.session.request
self.request.return_value.status_code = http_client.OK
def test_ok_get(self):
self.conn._op('GET', path='fake/path')
self.request.assert_called_once_with(
'GET', 'http://foo.bar:1234/fake/path',
headers=self.headers, json=None, verify=True, timeout=60)
def test_ok_get_with_headers(self):
self.conn._op('GET', path='fake/path', headers={'answer': '42'})
self.request.assert_called_once_with(
'GET', 'http://foo.bar:1234/fake/path',
headers=dict(self.headers, answer='42'),
json=None, verify=True, timeout=60)
def test_ok_get_default_timeout(self):
self.conn._default_request_timeout = 42
self.conn._op('GET', path='fake/path')
self.request.assert_called_once_with(
'GET', 'http://foo.bar:1234/fake/path',
headers=self.headers, json=None, verify=True, timeout=42)
def test_response_callback(self):
mock_response_callback = mock.MagicMock()
self.conn._response_callback = mock_response_callback
self.conn._op('GET', path='fake/path', headers=self.headers)
self.assertEqual(1, mock_response_callback.call_count)
def test_ok_get_url_redirect_false(self):
self.conn._op('GET', path='fake/path', allow_redirects=False)
self.request.assert_called_once_with(
'GET', 'http://foo.bar:1234/fake/path',
headers=self.headers, json=None, allow_redirects=False,
verify=True, timeout=60)
def test_ok_post(self):
self.conn._op('POST', path='fake/path', data=self.data.copy())
self.request.assert_called_once_with(
'POST', 'http://foo.bar:1234/fake/path',
json=self.data,
headers=dict(self.headers, **{'Content-Type': 'application/json'}),
verify=True, timeout=60)
def test_ok_post_with_headers(self):
self.conn._op('POST', path='fake/path', data=self.data.copy(),
headers={'answer': 42})
self.request.assert_called_once_with(
'POST', 'http://foo.bar:1234/fake/path',
json=self.data,
headers=dict(self.headers, **{'Content-Type': 'application/json',
'answer': 42}),
verify=True, timeout=60)
def test_ok_put(self):
self.conn._op('PUT', path='fake/path', data=self.data.copy())
self.request.assert_called_once_with(
'PUT', 'http://foo.bar:1234/fake/path',
headers=dict(self.headers, **{'Content-Type': 'application/json'}),
json=self.data, verify=True, timeout=60)
def test_ok_delete(self):
self.conn._op('DELETE', path='fake/path')
self.request.assert_called_once_with(
'DELETE', 'http://foo.bar:1234/fake/path',
headers=self.headers, json=None, verify=True, timeout=60)
def test_ok_post_with_session(self):
self.conn._session.headers = {}
self.conn._session.headers['X-Auth-Token'] = 'asdf1234'
expected_headers = self.headers.copy()
expected_headers['OData-Version'] = '4.0'
expected_headers['Content-Type'] = 'application/json'
self.conn._op('POST', path='fake/path', headers=self.headers,
data=self.data)
self.request.assert_called_once_with(
'POST', 'http://foo.bar:1234/fake/path',
json=self.data, headers=expected_headers, verify=True, timeout=60)
self.assertEqual(self.conn._session.headers,
{'X-Auth-Token': 'asdf1234'})
def test_odata_version_header_redfish(self):
path = '/redfish/v1/path'
headers = dict(self.headers)
expected_headers = dict(self.headers)
expected_headers['OData-Version'] = '4.0'
self.request.reset_mock()
self.conn._op('GET', path=path, headers=headers)
self.request.assert_called_once_with(
'GET', 'http://foo.bar:1234' + path,
headers=expected_headers, json=None, verify=True, timeout=60)
def test_odata_version_header_redfish_existing_header(self):
path = '/redfish/v1/foo'
headers = {'OData-Version': '3.0'}
expected_headers = dict(self.headers, **headers)
self.conn._op('GET', path=path, headers=headers)
self.request.assert_called_once_with(
'GET', 'http://foo.bar:1234' + path,
headers=expected_headers, json=None, verify=True, timeout=60)
def test_remove_header_accept_encoding(self):
path = '/redfish/v1/foo'
headers = {'Accept-Encoding': None}
self.headers.pop('Accept-Encoding')
self.conn._op('GET', path=path, headers=headers)
self.request.assert_called_once_with(
'GET', 'http://foo.bar:1234' + path,
headers=self.headers, json=None, verify=True, timeout=60)
def test_timed_out_session_unable_to_create_session(self):
self.conn._auth.can_refresh_session.return_value = False
self.session.auth = None
self.conn._session = self.session
self.request = self.session.request
self.request.return_value.status_code = http_client.FORBIDDEN
self.request.return_value.json.side_effect = ValueError('no json')
mock_response = mock.Mock()
mock_response.json.side_effect = ValueError('no json')
mock_response.status_code = http_client.FORBIDDEN
self.conn._auth.authenticate.side_effect = \
exceptions.AccessError('POST', 'fake/path', mock_response)
with self.assertRaisesRegex(exceptions.AccessError,
'unknown error') as ae:
self.conn._op('POST', path='fake/path', data=self.data,
headers=self.headers)
exc = ae.exception
self.assertEqual(http_client.FORBIDDEN, exc.status_code)
def test_timed_out_session_re_established(self):
self.auth._session_key = 'asdf1234'
self.auth.get_session_key.return_value = 'asdf1234'
self.conn._auth = self.auth
self.session = mock.Mock(spec=requests.Session)
self.session.auth = None
self.conn._session = self.session
self.request = self.session.request
first_response = mock.MagicMock()
first_response.status_code = http_client.FORBIDDEN
second_response = mock.MagicMock()
second_response.status_code = http_client.OK
second_response.json = {'Test': 'Testing'}
self.request.side_effect = [first_response, second_response]
response = self.conn._op('POST', path='fake/path', data=self.data,
headers=self.headers)
self.auth.refresh_session.assert_called_with()
self.auth.can_refresh_session.assert_called_with()
self.assertEqual(response.json, second_response.json)
def test_timed_out_session_timed_out_refresh(self):
self.auth._session_key = 'asdf1234'
self.auth.get_session_key.return_value = 'asdf1234'
self.conn._auth = self.auth
self.session = mock.Mock(spec=requests.Session)
self.session.auth = None
self.conn._session = self.session
self.request = self.session.request
first_response = mock.MagicMock()
first_response.status_code = http_client.FORBIDDEN
second_response = first_response
self.auth.refresh_session.side_effect = \
exceptions.ConnectionError('meow')
third_response = mock.MagicMock()
third_response.status_code = http_client.OK
third_response.json = {'Test': 'Testing'}
self.auth.can_refresh_session.return_value = True
self.request.side_effect = [first_response, second_response,
third_response]
self.assertRaises(exceptions.ConnectionError, self.conn._op, 'POST',
path='fake/path', data=self.data,
headers=self.headers)
self.auth.refresh_session.assert_called_with()
self.auth.refresh_session.reset_mock()
# Normally, this would be reset by refresh_session, but given
# the heavy mocking, we need to do it for this test.
self.auth._session_key = None
self.auth.get_session_key.return_value = None
self.auth.can_refresh_session.return_value = False
response = self.conn._op('POST', path='fake/path', data=self.data,
headers=self.headers)
self.auth.refresh_session.assert_not_called()
self.auth.authenticate.assert_called_once()
self.assertEqual(response.json, third_response.json)
def test_timed_out_session_fail_after_reestablish(self):
self.auth._session_key = 'asdf1234'
self.auth.get_session_key.return_value = 'asdf1234'
self.conn._auth = self.auth
self.session = mock.Mock(spec=requests.Session)
self.session.auth = None
self.conn._session = self.session
self.request = self.session.request
first_response = mock.MagicMock()
first_response.status_code = http_client.FORBIDDEN
second_response = mock.MagicMock()
second_response.status_code = http_client.BAD_REQUEST
self.request.side_effect = [first_response, second_response]
self.assertRaises(exceptions.BadRequestError,
self.conn._op,
'POST', path='fake/path', data=self.data,
headers=self.headers)
self.auth.refresh_session.assert_called_with()
self.auth.can_refresh_session.assert_called_with()
def test_timed_out_session_fail_after_reestablish_no_recursion(self):
self.auth._session_key = 'asdf1234'
self.auth.get_session_key.return_value = 'asdf1234'
self.conn._auth = self.auth
self.session = mock.Mock(spec=requests.Session)
self.session.auth = None
self.conn._session = self.session
self.request = self.session.request
first_response = mock.MagicMock()
first_response.status_code = http_client.FORBIDDEN
second_response = mock.MagicMock()
second_response.status_code = http_client.FORBIDDEN
self.request.side_effect = [first_response, second_response]
self.assertRaises(exceptions.AccessError,
self.conn._op,
'POST', path='fake/path', data=self.data,
headers=self.headers)
self.auth.refresh_session.assert_called_with()
self.auth.can_refresh_session.assert_called_with()
@mock.patch.object(time, 'sleep', autospec=True)
def test_connection_error(self, mock_sleep):
self.request.side_effect = requests.exceptions.ConnectionError
self.assertRaises(exceptions.ConnectionError, self.conn._op, 'GET')
def test_unknown_http_error(self):
self.request.return_value.status_code = http_client.CONFLICT
self.request.return_value.json.side_effect = ValueError('no json')
with self.assertRaisesRegex(exceptions.HTTPError,
'unknown error') as cm:
self.conn._op('GET', 'http://foo.bar')
exc = cm.exception
self.assertEqual(http_client.CONFLICT, exc.status_code)
self.assertIsNone(exc.body)
self.assertIsNone(exc.detail)
def test_known_http_error(self):
self.request.return_value.status_code = http_client.BAD_REQUEST
with open('sushy/tests/unit/json_samples/error.json') as f:
self.request.return_value.json.return_value = json.load(f)
with self.assertRaisesRegex(exceptions.BadRequestError,
'body submitted was malformed JSON') as cm:
self.conn._op('GET', 'http://foo.bar')
exc = cm.exception
self.assertEqual(http_client.BAD_REQUEST, exc.status_code)
self.assertIsNotNone(exc.body)
self.assertIn('body submitted was malformed JSON', exc.detail)
self.assertEqual(len(exc.extended_info), 3, exc.extended_info)
def test_known_http_error_nonlist_ext_info(self):
self.request.return_value.status_code =\
http_client.UNSUPPORTED_MEDIA_TYPE
with open('sushy/tests/unit/json_samples/'
'error_single_ext_info.json') as f:
self.request.return_value.json.return_value = json.load(f)
with self.assertRaisesRegex(exceptions.HTTPError,
'See Resolution for information') as cm:
self.conn._op('POST', 'http://foo.bar')
exc = cm.exception
self.assertEqual(http_client.UNSUPPORTED_MEDIA_TYPE, exc.status_code)
self.assertIsNotNone(exc.body)
self.assertIn('See Resolution for information', exc.detail)
self.assertIn('unsupported media type',
exc.extended_info['Resolution'])
@mock.patch('time.sleep', autospec=True)
def test_not_found_error(self, mock_sleep):
self.request.return_value.status_code = http_client.NOT_FOUND
self.request.return_value.json.side_effect = ValueError('no json')
with self.assertRaisesRegex(exceptions.ResourceNotFoundError,
'Resource http://foo.bar not found') as cm:
self.conn._op('GET', 'http://foo.bar')
exc = cm.exception
self.assertEqual(http_client.NOT_FOUND, exc.status_code)
self.assertFalse(mock_sleep.called)
self.assertEqual(1, self.request.call_count)
@mock.patch('time.sleep', autospec=True)
def test_server_error(self, mock_sleep):
self.request.return_value.status_code = (
http_client.INTERNAL_SERVER_ERROR)
self.request.return_value.json.side_effect = ValueError('no json')
with self.assertRaisesRegex(exceptions.ServerSideError,
'unknown error') as cm:
self.conn._op('GET', 'http://foo.bar')
exc = cm.exception
self.assertEqual(http_client.INTERNAL_SERVER_ERROR, exc.status_code)
self.assertEqual(10, mock_sleep.call_count)
self.assertEqual(11, self.request.call_count)
@mock.patch('time.sleep', autospec=True)
def test_op_retry_on_server_500_sys518(self, mock_sleep):
response_info = {"error": {"@Message.ExtendedInfo": [
{'MessageId': 'IDRAC.2.7.SYS518'}]}}
mock_error = mock.Mock()
mock_error.status_code = 500
mock_error.json.return_value = response_info
self.request.return_value.status_code = (
http_client.INTERNAL_SERVER_ERROR)
self.request.return_value.json.side_effect =\
exceptions.ServerSideError(
method='DELETE', url='http://foo.bar', response=mock_error)
self.assertRaises(exceptions.ServerSideError, self.conn._op, 'DELETE',
'http://foo.bar')
self.assertEqual(10, mock_sleep.call_count)
self.assertEqual(11, self.request.call_count)
@mock.patch('time.sleep', autospec=True)
def test_op_retry_on_server_500_other_than_sys518(self, mock_sleep):
response_info = {"error": {"@Message.ExtendedInfo": [
{'MessageId': 'IDRAC.2.7.SYS999'}]}}
mock_error = mock.Mock()
mock_error.status_code = 500
mock_error.json.return_value = response_info
self.request.return_value.status_code = (
http_client.INTERNAL_SERVER_ERROR)
self.request.return_value.json.side_effect =\
exceptions.ServerSideError(
method='DELETE', url='http://foo.bar', response=mock_error)
self.assertRaises(exceptions.ServerSideError, self.conn._op, 'DELETE',
'http://foo.bar')
self.assertEqual(0, mock_sleep.call_count)
self.assertEqual(1, self.request.call_count)
@mock.patch('time.sleep', autospec=True)
def test_op_retry_on_server_400_ilo_not_ready(self, mock_sleep):
response_info = {"error": {"@Message.ExtendedInfo": [
{'MessageId': 'iLO.2.15.InvalidOperationForSystemState'}]}}
mock_error = mock.Mock()
mock_error.status_code = 400
mock_error.json.return_value = response_info
self.request.return_value.status_code = (
http_client.INTERNAL_SERVER_ERROR)
self.request.return_value.json.side_effect =\
exceptions.ServerSideError(
method='DELETE', url='http://foo.bar', response=mock_error)
self.assertRaises(exceptions.ServerSideError, self.conn._op, 'DELETE',
'http://foo.bar')
self.assertEqual(10, mock_sleep.call_count)
self.assertEqual(11, self.request.call_count)
@mock.patch('time.sleep', autospec=True)
def test_op_retry_on_server_400_ilo_not_ready_other_error(self,
mock_sleep):
response_info = {"error": {"@Message.ExtendedInfo": [
{'MessageId': 'iLO.Invalid'}]}}
mock_error = mock.Mock()
mock_error.status_code = 400
mock_error.json.return_value = response_info
self.request.return_value.status_code = (
http_client.INTERNAL_SERVER_ERROR)
self.request.return_value.json.side_effect =\
exceptions.ServerSideError(
method='DELETE', url='http://foo.bar', response=mock_error)
self.assertRaises(exceptions.ServerSideError, self.conn._op, 'DELETE',
'http://foo.bar')
self.assertEqual(0, mock_sleep.call_count)
self.assertEqual(1, self.request.call_count)
def test_op_retry_without_identity(self):
self.request.side_effect = [
mock.Mock(status_code=http_client.NOT_ACCEPTABLE),
mock.Mock(status_code=http_client.OK),
]
self.conn._op('GET', 'http://foo.bar')
self.assertEqual(2, self.request.call_count)
headers_no_accept = self.headers.copy()
headers_no_accept.pop('Accept-Encoding')
self.request.assert_has_calls([
mock.call('GET', 'http://foo.bar', headers=self.headers,
json=None, verify=True, timeout=60),
mock.call('GET', 'http://foo.bar', headers=headers_no_accept,
json=None, verify=True, timeout=60),
])
def test_op_retry_without_identity_fails(self):
self.request.return_value.status_code = http_client.NOT_ACCEPTABLE
self.assertRaises(exceptions.NotAcceptableError, self.conn._op,
'GET', 'http://foo.bar')
self.assertEqual(2, self.request.call_count)
def test_access_error(self):
self.conn._auth = None
self.request.return_value.status_code = http_client.FORBIDDEN
self.request.return_value.json.side_effect = ValueError('no json')
with self.assertRaisesRegex(exceptions.AccessError,
'unknown error') as cm:
self.conn._op('GET', 'http://foo.bar')
exc = cm.exception
self.assertEqual(http_client.FORBIDDEN, exc.status_code)
def test_access_error_on_session_post_does_not_retry(self):
self.request.return_value.status_code = http_client.FORBIDDEN
self.request.return_value.json.side_effect = ValueError('no json')
self.conn._sessions_uri = '/redfish/v1/SessionService/Sessions'
with self.assertRaisesRegex(exceptions.AccessError,
'unknown error') as cm:
self.conn._op('POST', 'http://foo.bar/redfish/v1/Session'
'Service/Sessions',
data={'foo': 'bar'})
exc = cm.exception
self.assertEqual(http_client.FORBIDDEN, exc.status_code)
self.request.assert_called_once()
def test_access_error_triggers_auth_attempt(self):
self.conn._auth.can_refresh_session.return_value = False
value_error = ValueError('no json')
mock_response = mock.Mock()
mock_response.json.side_effect = value_error
mock_response.status_code = http_client.FORBIDDEN
self.session.auth = None
self.conn._session = self.session
# This doesn't test/wire all way back through auth -> main
# and ultimately we want to make sure we get an error all
# the way back.
self.conn._auth.authenticate.side_effect = \
exceptions.AccessError('GET', '/', mock_response)
self.request.return_value.status_code = http_client.FORBIDDEN
self.request.return_value.json.side_effect = value_error
with self.assertRaisesRegex(exceptions.AccessError,
'unknown error') as cm:
self.conn._op('GET', 'http://foo.bar')
exc = cm.exception
self.assertEqual(http_client.FORBIDDEN, exc.status_code)
self.conn._auth.authenticate.assert_called_once()
def test_access_error_without_auth(self):
self.conn._auth = None
self.request.return_value.status_code = http_client.FORBIDDEN
self.request.return_value.json.side_effect = ValueError('no json')
with self.assertRaisesRegex(exceptions.AccessError,
'unknown error') as cm:
self.conn._op('GET', 'http://foo.bar')
exc = cm.exception
self.assertEqual(http_client.FORBIDDEN, exc.status_code)
@mock.patch.object(connector.LOG, 'debug', autospec=True)
def test_access_error_service_session_reauth(self, mock_log):
self.conn._auth.can_refresh_session.return_value = False
self.request.return_value.status_code = http_client.FORBIDDEN
mock_response = mock.Mock()
mock_response.json.side_effect = ValueError('no json')
mock_response.status_code = http_client.FORBIDDEN
self.session.auth = None
self.conn._session = self.session
self.conn._auth.authenticate.side_effect = \
exceptions.AccessError('POST', 'fake/path', mock_response)
self.request.return_value.json.side_effect = ValueError('no json')
with self.assertRaisesRegex(exceptions.AccessError,
'unknown error') as cm:
self.conn._op('GET', 'http://redfish/v1/SessionService')
exc = cm.exception
self.assertEqual(http_client.FORBIDDEN, exc.status_code)
self.conn._auth.authenticate.assert_called_once()
@mock.patch.object(connector.LOG, 'debug', autospec=True)
def test_access_error_service_session_no_auth(self, mock_log):
self.conn._auth = None
self.request.return_value.status_code = http_client.FORBIDDEN
self.request.return_value.json.side_effect = ValueError('no json')
with self.assertRaisesRegex(exceptions.AccessError,
'unknown error') as cm:
self.conn._op('GET', 'http://redfish/v1/SessionService')
exc = cm.exception
mock_log.assert_called_with(
'HTTP GET of SessionService failed %s, '
'this is expected prior to authentication', 'HTTP GET '
'http://redfish/v1/SessionService returned code '
f'{http_client.FORBIDDEN!s}. unknown error Extended '
'information: None')
self.assertEqual(http_client.FORBIDDEN, exc.status_code)
def test_blocking_no_location_header(self):
self.request.return_value.status_code = http_client.ACCEPTED
self.request.return_value.headers = {'retry-after': 5}
with self.assertRaisesRegex(exceptions.ConnectionError,
'status 202, but no Location header'):
self.conn._op('POST', 'http://foo.bar', blocking=True)
@mock.patch('sushy.connector.time.sleep', autospec=True)
def test_blocking_task_fails(self, mock_sleep):
response1 = mock.MagicMock(spec=requests.Response)
response1.status_code = http_client.ACCEPTED
response1.headers = {
'Retry-After': 5,
'Location': '/redfish/v1/taskmon/1',
'Content-Length': 10
}
response1.json.return_value = {'Id': 3, 'Name': 'Test'}
response2 = mock.MagicMock(spec=requests.Response)
response2.status_code = http_client.BAD_REQUEST
message = 'Unable to create Volume with given parameters'
response2.json.return_value = {
'error': {
'message': message
}
}
self.request.side_effect = [response1, response1, response2]
with self.assertRaisesRegex(exceptions.BadRequestError, message):
self.conn._op('POST', 'http://foo.bar', blocking=True)
@mock.patch.object(connector.LOG, 'warning', autospec=True)
def test_access_error_basic_auth(self, mock_log):
self.conn._auth.can_refresh_session.return_value = False
self.conn._session.auth = ('foo', 'bar')
self.request.return_value.status_code = 403
mock_response = mock.Mock()
mock_response.json.side_effect = ValueError('no json')
mock_response.status_code = 403
self.request.return_value.json.side_effect = ValueError('no json')
with self.assertRaisesRegex(exceptions.AccessError,
'unknown error') as cm:
self.conn._op('GET', 'http://redfish/v1/SessionService')
exc = cm.exception
self.assertEqual(http_client.FORBIDDEN, exc.status_code)
self.conn._auth.authenticate.assert_not_called()
error_msg = (f'HTTP GET http://redfish/v1/SessionService '
f'returned code {exc.status_code}. unknown error '
f'Extended information: None')
mock_log.assert_called_once_with(
"We have encountered an AccessError when using 'basic' "
"authentication. %(err)s",
{'err': error_msg}
)
@mock.patch.object(time, 'sleep', autospec=True)
def test__op_raises_connection_error(self, mock_sleep):
exception_list = [
requests.exceptions.ChunkedEncodingError,
requests.exceptions.ContentDecodingError,
requests.exceptions.ReadTimeout,
requests.exceptions.ConnectTimeout,
requests.exceptions.SSLError,
requests.exceptions.ConnectionError,
requests.exceptions.RequestException,
]
for exc in exception_list:
self.request.side_effect = exc
self.assertRaises(exceptions.ConnectionError,
self.conn._op,
'POST',
'http://foo.bar',
blocking=True)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_etag_handler_strong_etag_ok(self, mock__op):
self.headers['If-Match'] = '"3d7b8a7360bf2941d"'
response = mock.MagicMock(spec=requests.Response)
response.status_code = http_client.OK
data = {'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}}
mock__op.return_value = response
self.conn._etag_handler(path='/redfish/v1/Systems/1',
headers=self.headers, data=data,
etag=self.headers['If-Match'],
blocking=False, timeout=60)
mock__op.assert_called_once_with(
self.conn,
"PATCH",
'/redfish/v1/Systems/1',
data={'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}},
headers=dict(self.headers, **{'If-Match': '"3d7b8a7360bf2941d"'}),
blocking=False,
timeout=60)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_etag_handler_weak_etag_ok(self, mock__op):
self.headers['If-Match'] = 'W/"3d7b8a7360bf2941d"'
response = mock.MagicMock(spec=requests.Response)
response.status_code = http_client.OK
data = {'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}}
mock__op.return_value = response
self.conn._etag_handler(path='/redfish/v1/Systems/1',
headers=self.headers, data=data,
etag=self.headers['If-Match'],
blocking=False, timeout=60)
mock__op.assert_called_once_with(
self.conn,
"PATCH",
'/redfish/v1/Systems/1',
data={'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}},
headers=dict(self.headers,
**{'If-Match': 'W/"3d7b8a7360bf2941d"'}),
blocking=False,
timeout=60)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_etag_handler_no_etag_ok(self, mock__op):
response = mock.MagicMock(spec=requests.Response)
response.status_code = http_client.OK
data = {'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}}
mock__op.return_value = response
self.conn._etag_handler(path='/redfish/v1/Systems/1',
headers=self.headers, data=data,
blocking=False, timeout=60)
mock__op.assert_called_once_with(
self.conn,
"PATCH",
'/redfish/v1/Systems/1',
data={'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}},
headers=self.headers,
blocking=False,
timeout=60)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_etag_handler_weak_etag_fallback_to_strong(self, mock__op):
self.headers['If-Match'] = 'W/"3d7b8a7360bf2941d"'
target_uri = '/redfish/v1/Systems/1'
response_412 = mock.MagicMock(spec=requests.Response)
response_412.status_code = http_client.PRECONDITION_FAILED
response_200 = mock.MagicMock(spec=requests.Response)
response_200.status_code = http_client.OK
mock__op.side_effect = [
exceptions.HTTPError(method='PATCH', url=target_uri,
response=response_412),
response_200]
data = {'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}}
self.conn._etag_handler(path=target_uri, headers=self.headers,
data=data, etag=self.headers['If-Match'],
blocking=False, timeout=60)
mock__op.assert_called_with(
self.conn,
"PATCH",
'/redfish/v1/Systems/1',
data={'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}},
headers=dict(self.headers, **{'If-Match': '"3d7b8a7360bf2941d"'}),
blocking=False,
timeout=60)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_etag_handler_weak_etag_fallback_to_no_etag(self, mock__op):
self.headers['If-Match'] = 'W/"3d7b8a7360bf2941d"'
target_uri = '/redfish/v1/Systems/1'
response_412 = mock.MagicMock(spec=requests.Response)
response_412.status_code = http_client.PRECONDITION_FAILED
response_200 = mock.MagicMock(spec=requests.Response)
response_200.status_code = http_client.OK
mock__op.side_effect = [
exceptions.HTTPError(method='PATCH', url=target_uri,
response=response_412),
exceptions.HTTPError(method='PATCH', url=target_uri,
response=response_412),
response_200]
data = {'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}}
self.conn._etag_handler(path=target_uri, headers=self.headers,
data=data, etag=self.headers['If-Match'],
blocking=False, timeout=60)
mock__op.assert_called_with(
self.conn,
"PATCH",
'/redfish/v1/Systems/1',
data={'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}},
headers=self.headers,
blocking=False,
timeout=60)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_etag_handler_strong_etag_fallback_to_no_etag(self, mock__op):
self.headers['If-Match'] = '"3d7b8a7360bf2941d"'
target_uri = '/redfish/v1/Systems/1'
response_412 = mock.MagicMock(spec=requests.Response)
response_412.status_code = http_client.PRECONDITION_FAILED
response_200 = mock.MagicMock(spec=requests.Response)
response_200.status_code = http_client.OK
mock__op.side_effect = [
exceptions.HTTPError(method='PATCH', url=target_uri,
response=response_412),
response_200]
data = {'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}}
self.conn._etag_handler(path=target_uri, headers=self.headers,
data=data, etag=self.headers['If-Match'],
blocking=False, timeout=60)
mock__op.assert_called_with(
self.conn,
"PATCH",
'/redfish/v1/Systems/1',
data={'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}},
headers=self.headers,
blocking=False,
timeout=60)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_etag_handler_emptystring_etag(self, mock__op):
self.headers_no_etag = self.headers.copy()
target_uri = '/redfish/v1/Systems/1'
response_200 = mock.MagicMock(spec=requests.Response)
response_200.status_code = http_client.OK
data = {'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}}
self.conn._etag_handler(path=target_uri, headers=self.headers,
data=data, etag='',
blocking=False, timeout=60)
mock__op.assert_called_with(
self.conn,
"PATCH",
'/redfish/v1/Systems/1',
data={'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}},
headers=self.headers_no_etag,
blocking=False,
timeout=60)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_etag_handler_emptystring_etag_from_headers(self, mock__op):
self.headers_no_etag = self.headers.copy()
self.headers['If-Match'] = ''
target_uri = '/redfish/v1/Systems/1'
response_200 = mock.MagicMock(spec=requests.Response)
response_200.status_code = http_client.OK
data = {'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}}
self.conn._etag_handler(path=target_uri, headers=self.headers,
data=data, etag=self.headers['If-Match'],
blocking=False, timeout=60)
mock__op.assert_called_with(
self.conn,
"PATCH",
'/redfish/v1/Systems/1',
data={'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}},
headers=self.headers_no_etag,
blocking=False,
timeout=60)
@mock.patch.object(connector.Connector, '_op', autospec=True)
def test_etag_handler_fail_other_exception(self, mock__op):
self.headers['If-Match'] = 'W/"3d7b8a7360bf2941d"'
target_uri = '/redfish/v1/Systems/1'
data = {'Boot': {'BootSourceOverrideTarget': 'Cd',
'BootSourceOverrideEnabled': 'Once'}}
response = mock.MagicMock(spec=requests.Response)
response.status_code = http_client.FORBIDDEN
response.message = "boom"
mock__op.return_value = response
mock__op.side_effect = \
exceptions.HTTPError(method='PATCH',
url=target_uri,
response=response)
self.assertRaises(exceptions.HTTPError, self.conn._etag_handler,
'PATCH', target_uri, data,
self.headers,
blocking=False, timeout=60)
@mock.patch.object(time, 'sleep', autospec=True)
def test_retry_on_connection_error(self, mock_sleep):
self.request.side_effect = [
requests.exceptions.ConnectionError("temporary issue"),
mock.Mock(status_code=200, headers={}, json=lambda: {})
]
target_uri = '/redfish/v1/Systems/1'
result = self.conn.get(target_uri)
self.assertEqual(result.status_code, 200)
self.assertEqual(self.request.call_count, 2)
@mock.patch.object(time, 'sleep', autospec=True)
def test_raises_after_max_retries(self, mock_sleep):
target_uri = '/redfish/v1/Systems/1'
self.request.side_effect = requests.exceptions.ConnectTimeout(
"timeout")
self.assertRaises(exceptions.ConnectionError, self.conn.get,
target_uri)
self.assertEqual(self.request.call_count,
self.conn._server_side_retries)
|