File: test_exceptions.py

package info (click to toggle)
python-azure 20201208%2Bgit-6
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,437,920 kB
  • sloc: python: 4,287,452; javascript: 269; makefile: 198; sh: 187; xml: 106
file content (252 lines) | stat: -rw-r--r-- 9,787 bytes parent folder | download
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
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# --------------------------------------------------------------------------
import json
import logging
import os

import requests
import pytest
try:
    from unittest.mock import Mock
except ImportError:
    # python < 3.3
    from mock import Mock

# module under test
from azure.core.exceptions import HttpResponseError, ODataV4Error, ODataV4Format
from azure.core.pipeline.transport import RequestsTransportResponse
from azure.core.pipeline.transport._base import _HttpResponseBase


def _build_response(json_body):
    class MockResponse(_HttpResponseBase):
        def __init__(self):
            super(MockResponse, self).__init__(
                request=None,
                internal_response = None,
            )
            self.status_code = 400
            self.reason = "Bad Request"
            self.content_type = "application/json"
            self._body = json_body

        def body(self):
            return self._body

    return MockResponse()


class FakeErrorOne(object):

    def __init__(self):
        self.error = Mock(message="A fake error", code="FakeErrorOne")


class FakeErrorTwo(object):

    def __init__(self):
        self.code = "FakeErrorTwo"
        self.message = "A different fake error"


class FakeHttpResponse(HttpResponseError):

    def __init__(self, response, error, *args, **kwargs):
        self.error = error
        super(FakeHttpResponse, self).__init__(self, response=response, *args, **kwargs)


class TestExceptions(object):

    def test_empty_httpresponse_error(self):
        error = HttpResponseError()
        assert str(error) == "Operation returned an invalid status 'None'"
        assert error.message == "Operation returned an invalid status 'None'"
        assert error.response is None
        assert error.reason is None
        assert error.error is None
        assert error.status_code is None

    def test_message_httpresponse_error(self):
        error = HttpResponseError(message="Specific error message")
        assert str(error) == "Specific error message"
        assert error.message == "Specific error message"
        assert error.response is None
        assert error.reason is None
        assert error.error is None
        assert error.status_code is None

    def test_error_continuation_token(self):
        error = HttpResponseError(message="Specific error message", continuation_token='foo')
        assert str(error) == "Specific error message"
        assert error.message == "Specific error message"
        assert error.response is None
        assert error.reason is None
        assert error.error is None
        assert error.status_code is None
        assert error.continuation_token == 'foo'

    def test_deserialized_httpresponse_error_code(self):
        """This is backward compat support of autorest azure-core (KV 4.0.0, Storage 12.0.0).

        Do NOT adapt this test unless you know what you're doing.
        """
        message = {
            "error": {
                "code": "FakeErrorOne",
                "message": "A fake error",
            }
        }
        response = _build_response(json.dumps(message).encode("utf-8"))
        error = FakeHttpResponse(response, FakeErrorOne())
        assert error.message == "(FakeErrorOne) A fake error"
        assert str(error.error) == "(FakeErrorOne) A fake error"
        assert error.error.code == "FakeErrorOne"
        assert error.error.message == "A fake error"
        assert error.response is response
        assert error.reason == "Bad Request"
        assert error.status_code == 400
        assert isinstance(error.model, FakeErrorOne)
        assert isinstance(error.error, ODataV4Format)

        # Could test if we see a deprecation warning
        assert error.error.error.code == "FakeErrorOne"
        assert error.error.error.message == "A fake error"


    def test_deserialized_httpresponse_error_message(self):
        """This is backward compat support for weird responses, adn even if it's likely
        just the autorest testserver, should be fine parsing.

        Do NOT adapt this test unless you know what you're doing.
        """
        message = {
            "code": "FakeErrorTwo",
            "message": "A different fake error",
        }
        response = _build_response(json.dumps(message).encode("utf-8"))
        error = FakeHttpResponse(response, FakeErrorTwo())
        assert error.message == "(FakeErrorTwo) A different fake error"
        assert str(error.error) == "(FakeErrorTwo) A different fake error"
        assert error.error.code == "FakeErrorTwo"
        assert error.error.message == "A different fake error"
        assert error.response is response
        assert error.reason == "Bad Request"
        assert error.status_code == 400
        assert isinstance(error.model, FakeErrorTwo)
        assert isinstance(error.error, ODataV4Format)

    def test_httpresponse_error_with_response(self):
        response = requests.get("https://bing.com")
        http_response = RequestsTransportResponse(None, response)

        error = HttpResponseError(response=http_response)
        assert error.message == "Operation returned an invalid status 'OK'"
        assert error.response is not None
        assert error.reason == 'OK'
        assert isinstance(error.status_code, int)
        assert error.error is None

    def test_odata_v4_exception(self):
        message = {
            "error": {
                "code": "501",
                "message": "Unsupported functionality",
                "target": "query",
                "details": [{
                    "code": "301",
                    "target": "$search",
                    "message": "$search query option not supported",
                }],
                "innererror": {
                    "trace": [],
                    "context": {}
                }
            }
        }
        exp = ODataV4Error(_build_response(json.dumps(message).encode("utf-8")))

        assert exp.code == "501"
        assert exp.message == "Unsupported functionality"
        assert exp.target == "query"
        assert exp.details[0].code == "301"
        assert exp.details[0].target == "$search"
        assert "trace" in exp.innererror
        assert "context" in exp.innererror

        message = {}
        exp = ODataV4Error(_build_response(json.dumps(message).encode("utf-8")))
        assert exp.message == "Operation returned an invalid status 'Bad Request'"

        exp = ODataV4Error(_build_response(b""))
        assert exp.message == "Operation returned an invalid status 'Bad Request'"
        assert str(exp) == "Operation returned an invalid status 'Bad Request'"

    def test_odata_v4_minimal(self):
        """Minimal valid OData v4 is code/message and nothing else.
        """
        message = {
            "error": {
                "code": "501",
                "message": "Unsupported functionality",
            }
        }
        exp = ODataV4Error(_build_response(json.dumps(message).encode("utf-8")))
        assert exp.code == "501"
        assert exp.message == "Unsupported functionality"
        assert exp.target is None
        assert exp.details == []
        assert exp.innererror == {}

    def test_broken_odata_details(self):
        """Do not block creating a nice exception if "details" only is broken
        """
        message = {
            "error": {
                "code": "Conflict",
                "message": "The maximum number of Free ServerFarms allowed in a Subscription is 10.",
                "target": None,
                "details": [
                    {
                        "message": "The maximum number of Free ServerFarms allowed in a Subscription is 10."
                    },
                    {"code": "Conflict"},
                    {
                        "errorentity": {
                            "code": "Conflict",
                            "message": "The maximum number of Free ServerFarms allowed in a Subscription is 10.",
                            "extendedCode": "59301",
                            "messageTemplate": "The maximum number of {0} ServerFarms allowed in a Subscription is {1}.",
                            "parameters": ["Free", "10"],
                            "innerErrors": None,
                        }
                    },
                ],
                "innererror": None,
            }
        }
        exp = HttpResponseError(response=_build_response(json.dumps(message).encode("utf-8")))
        assert exp.error.code == "Conflict"