Beispiel #1
0
    def _mock_http_get(self, *_, **kwargs):
        if "foo.bar" == kwargs[
                'endpoint'] and not self._mock_imds_expect_fallback:
            raise Exception("Unexpected endpoint called")
        if self._mock_imds_primary_ioerror and "169.254.169.254" == kwargs[
                'endpoint']:
            raise HttpError(
                "[HTTP Failed] GET http://{0}/metadata/{1} -- IOError timed out -- 6 attempts made"
                .format(kwargs['endpoint'], kwargs['resource_path']))
        if self._mock_imds_secondary_ioerror and "foo.bar" == kwargs[
                'endpoint']:
            raise HttpError(
                "[HTTP Failed] GET http://{0}/metadata/{1} -- IOError timed out -- 6 attempts made"
                .format(kwargs['endpoint'], kwargs['resource_path']))
        if self._mock_imds_gone_error:
            raise ResourceGoneError("Resource is gone")
        if self._mock_imds_throttled:
            raise HttpError(
                "[HTTP Retry] GET http://{0}/metadata/{1} -- Status Code 429 -- 25 attempts made"
                .format(kwargs['endpoint'], kwargs['resource_path']))

        resp = MagicMock()
        resp.reason = 'reason'
        if self._mock_imds_bad_request:
            resp.status = httpclient.NOT_FOUND
            resp.read.return_value = 'Mock not found'
        else:
            resp.status = httpclient.OK
            resp.read.return_value = 'Mock success response'
        return resp
Beispiel #2
0
    def mock_http_put(self, url, *args, **kwargs):  # pylint: disable=unused-argument
        content = None

        resp = MagicMock()
        resp.status = httpclient.OK

        if url.endswith('/vmAgentLog'):
            self.call_counts['/vmAgentLog'] += 1
            content = ''
        else:
            raise Exception("Bad url {0}".format(url))

        resp.read = Mock(return_value=content.encode("utf-8"))
        return resp
Beispiel #3
0
    def mock_http_post(self, url, *args, **kwargs):
        content = None

        resp = MagicMock()
        resp.status = httpclient.OK

        if url.endswith('/HealthService'):
            self.call_counts['/HealthService'] += 1
            content = ''
        else:
            raise Exception("Bad url {0}".format(url))

        resp.read = Mock(return_value=content.encode("utf-8"))
        return resp
Beispiel #4
0
    def mock_http_put(self, url, data, **_):
        content = ''

        resp = MagicMock()
        resp.status = httpclient.OK

        if url.endswith('/vmAgentLog'):
            self.call_counts['/vmAgentLog'] += 1
        elif url.endswith('/StatusBlob'):
            self.call_counts['/StatusBlob'] += 1
            self.status_blobs.append(data)
        else:
            raise Exception("Bad url {0}".format(url))

        resp.read = Mock(return_value=content.encode("utf-8"))
        return resp
 def test_read_response_error(self):
     """
     Validate the read_response_error method handles encoding correctly
     """
     responses = ['message', b'message', '\x80message\x80']
     response = MagicMock()
     response.status = 'status'
     response.reason = 'reason'
     with patch.object(response, 'read') as patch_response:
         for s in responses:
             patch_response.return_value = s
             result = restutil.read_response_error(response)
             print("RESPONSE: {0}".format(s))
             print("RESULT: {0}".format(result))
             print("PRESENT: {0}".format('[status: reason]' in result))
             self.assertTrue('[status: reason]' in result)
             self.assertTrue('message' in result)
Beispiel #6
0
 def mock_http_get(self, url, *args, **kwargs):
     content = None
     if url.count(u"identity?") > 0:
         content = self.identity
     elif url.count(u"certificates") > 0:
         content = self.certificates
     elif url.count(u"certificates_data") > 0:
         content = self.certificates_data
     elif url.count(u"extensionHandlers") > 0:
         content = self.ext_handlers
     elif url.count(u"versionUri") > 0:
         content = self.ext_handler_pkgs
     else:
         raise Exception("Bad url {0}".format(url))
     resp = MagicMock()
     resp.status = httpclient.OK
     if content is None:
         resp.read = Mock(return_value=None)
     else:
         resp.read = Mock(return_value=content.encode("utf-8"))
     return resp
    def test_read_response_bytes(self):
        response_bytes = '7b:0a:20:20:20:20:22:65:72:72:6f:72:43:6f:64:65:22:' \
                         '3a:20:22:54:68:65:20:62:6c:6f:62:20:74:79:70:65:20:' \
                         '69:73:20:69:6e:76:61:6c:69:64:20:66:6f:72:20:74:68:' \
                         '69:73:20:6f:70:65:72:61:74:69:6f:6e:2e:22:2c:0a:20:' \
                         '20:20:20:22:6d:65:73:73:61:67:65:22:3a:20:22:c3:af:' \
                         'c2:bb:c2:bf:3c:3f:78:6d:6c:20:76:65:72:73:69:6f:6e:' \
                         '3d:22:31:2e:30:22:20:65:6e:63:6f:64:69:6e:67:3d:22:' \
                         '75:74:66:2d:38:22:3f:3e:3c:45:72:72:6f:72:3e:3c:43:' \
                         '6f:64:65:3e:49:6e:76:61:6c:69:64:42:6c:6f:62:54:79:' \
                         '70:65:3c:2f:43:6f:64:65:3e:3c:4d:65:73:73:61:67:65:' \
                         '3e:54:68:65:20:62:6c:6f:62:20:74:79:70:65:20:69:73:' \
                         '20:69:6e:76:61:6c:69:64:20:66:6f:72:20:74:68:69:73:' \
                         '20:6f:70:65:72:61:74:69:6f:6e:2e:0a:52:65:71:75:65:' \
                         '73:74:49:64:3a:63:37:34:32:39:30:63:62:2d:30:30:30:' \
                         '31:2d:30:30:62:35:2d:30:36:64:61:2d:64:64:36:36:36:' \
                         '61:30:30:30:22:2c:0a:20:20:20:20:22:64:65:74:61:69:' \
                         '6c:73:22:3a:20:22:22:0a:7d'.split(':')
        expected_response = '[HTTP Failed] [status: reason] {\n    "errorCode": "The blob ' \
                            'type is invalid for this operation.",\n    ' \
                            '"message": "<?xml version="1.0" ' \
                            'encoding="utf-8"?>' \
                            '<Error><Code>InvalidBlobType</Code><Message>The ' \
                            'blob type is invalid for this operation.\n' \
                            'RequestId:c74290cb-0001-00b5-06da-dd666a000",' \
                            '\n    "details": ""\n}'

        response_string = ''.join(chr(int(b, 16)) for b in response_bytes)
        response = MagicMock()
        response.status = 'status'
        response.reason = 'reason'
        with patch.object(response, 'read') as patch_response:
            patch_response.return_value = response_string
            result = restutil.read_response_error(response)
            self.assertEqual(result, expected_response)
            try:
                raise HttpError("{0}".format(result))
            except HttpError as e:
                self.assertTrue(result in ustr(e))
Beispiel #8
0
    def mock_http_get(self, url, *args, **kwargs):
        content = None

        resp = MagicMock()
        resp.status = httpclient.OK

        if "comp=versions" in url:  # wire server versions
            content = self.version_info
            self.call_counts["comp=versions"] += 1
        elif "/versions" in url:  # HostPlugin versions
            content = '["2015-09-01"]'
            self.call_counts["/versions"] += 1
        elif url.endswith("/health"):  # HostPlugin health
            content = ''
            self.call_counts["/health"] += 1
        elif "goalstate" in url:
            content = self.goal_state
            self.call_counts["goalstate"] += 1
        elif "hostingenvuri" in url:
            content = self.hosting_env
            self.call_counts["hostingenvuri"] += 1
        elif "sharedconfiguri" in url:
            content = self.shared_config
            self.call_counts["sharedconfiguri"] += 1
        elif "certificatesuri" in url:
            content = self.certs
            self.call_counts["certificatesuri"] += 1
        elif "extensionsconfiguri" in url:
            content = self.ext_conf
            self.call_counts["extensionsconfiguri"] += 1
        elif "remoteaccessinfouri" in url:
            content = self.remote_access
            self.call_counts["remoteaccessinfouri"] += 1
        elif ".vmSettings" in url or ".settings" in url:
            content = self.in_vm_artifacts_profile
            self.call_counts["in_vm_artifacts_profile"] += 1

        else:
            # A stale GoalState results in a 400 from the HostPlugin
            # for which the HTTP handler in restutil raises ResourceGoneError
            if self.emulate_stale_goal_state:
                if "extensionArtifact" in url:
                    self.emulate_stale_goal_state = False
                    self.call_counts["extensionArtifact"] += 1
                    raise ResourceGoneError()
                else:
                    raise HttpError()

            # For HostPlugin requests, replace the URL with that passed
            # via the x-ms-artifact-location header
            if "extensionArtifact" in url:
                self.call_counts["extensionArtifact"] += 1
                if "headers" not in kwargs:
                    raise ValueError("HostPlugin request is missing the HTTP headers: {0}", kwargs)
                if "x-ms-artifact-location" not in kwargs["headers"]:
                    raise ValueError("HostPlugin request is missing the x-ms-artifact-location header: {0}", kwargs)
                url = kwargs["headers"]["x-ms-artifact-location"]

            if "manifest.xml" in url:
                content = self.manifest
                self.call_counts["manifest.xml"] += 1
            elif "manifest_of_ga.xml" in url:
                content = self.ga_manifest
                self.call_counts["manifest_of_ga.xml"] += 1
            elif "ExampleHandlerLinux" in url:
                content = self.ext
                self.call_counts["ExampleHandlerLinux"] += 1
                resp.read = Mock(return_value=content)
                return resp
            elif ".vmSettings" in url or ".settings" in url:
                content = self.in_vm_artifacts_profile
                self.call_counts["in_vm_artifacts_profile"] += 1
            else:
                raise Exception("Bad url {0}".format(url))

        resp.read = Mock(return_value=content.encode("utf-8"))
        return resp