Пример #1
0
def test_new_download_oneshot(base_command, url, content_disposition):
    base_command.requests = mock.MagicMock()
    response = mock.MagicMock()
    response.url = url
    response.status_code = 200
    response.headers = mock.Mock(
        wraps=HTTPHeaderDict({
            "content-disposition": content_disposition,
        } if content_disposition is not None else {}))
    response.content = b"all content"
    base_command.requests.get.return_value = response

    # Download the file
    filename = base_command.download_url(
        url="https://example.com/support?useful=Yes",
        download_path=base_command.base_path / "downloads",
    )

    # requests.get has been invoked, but content isn't iterated
    base_command.requests.get.assert_called_with(
        "https://example.com/support?useful=Yes",
        stream=True,
    )
    response.headers.get.assert_called_with("content-length")
    response.iter_content.assert_not_called()

    # The filename is derived from the URL or header
    assert filename == base_command.base_path / "downloads" / "something.zip"

    # File content is as expected
    with (base_command.base_path / "downloads" / "something.zip").open() as f:
        assert f.read() == "all content"
Пример #2
0
    def call_api_side_effect(self, url, attr='GET', header_params=None, _preload_content=None, body=None):
        """
        Side effect function for get usage of a pod,
        return string tmpHttpObj, same api_client.call_api() method
        """
        test_nodes_list = self.nodes_list
        test_pods_list = self.pods_list

        if url.split('/')[2] == 'metrics.k8s.io':
            class tmpHttpObj():
                def __init__(self):
                    if url.split('/')[-2] == 'nodes':
                        node_name = url.split('/')[-1]
                        self.tmp = ''
                        self.data = b''
                        for node in test_nodes_list.items:
                            if node.metadata.name == node_name:
                                cpu = node.usage['cpu']
                                memory = node.usage['memory']
                                self.tmp = '''{"usage":{"cpu":"''' + str(cpu) + '''","memory":"''' + str(
                                    memory) + '''"}}\n'''
                                self.data = bytes(self.tmp, 'utf-8')

                    if url.split('/')[-2] == 'pods':
                        pod_name = url.split('/')[-1]
                        pod_namespace = url.split('/')[-3]
                        self.tmp = ''
                        self.data = b''
                        for pod in test_pods_list.items:
                            if pod.metadata.name == pod_name:
                                self.tmp = {'containers': []}
                                for cont in pod.spec.containers:
                                    cpu = cont.usage['cpu']
                                    memory = cont.usage['memory']
                                    self.tmp['containers'].append({"usage": {"cpu": str(cpu), "memory": str(memory)}})
                                string_tmp = json.dumps(self.tmp)
                                self.data = bytes(string_tmp, 'utf-8')

            retobj = tmpHttpObj()
            return [retobj]

        if url.split('/')[2] == 'extensions':
            # TODO do not have any info about deployment right now
            deployment_name = url.split('/')[7]
            namespace = url.split('/')[5]

            if namespace == self.mocked_deployments['namespace']:
                for name in self.mocked_deployments['deployment_name']:
                    if name == deployment_name:
                        tmp = list()
                        tmp.append(None)
                        tmp.append(200)
                        tmp.append(HTTPHeaderDict(
                            {'Content-Type': 'application/json', 'Date': 'Sat, 12 Oct 2019 14:15:57 GMT',
                             'Transfer-Encoding': 'chunked'}))
                        return tmp
            raise ApiException(404)
Пример #3
0
async def convert_to_response_dict(http_response, operation_model):
    """Convert an HTTP response object to a request dict.

    This converts the requests library's HTTP response object to
    a dictionary.

    :type http_response: botocore.vendored.requests.model.Response
    :param http_response: The HTTP response from an AWS service request.

    :rtype: dict
    :return: A response dictionary which will contain the following keys:
        * headers (dict)
        * status_code (int)
        * body (string or file-like object)

    """
    response_dict = {
        # botocore converts keys to str, so make sure that they are in
        # the expected case. See detailed discussion here:
        # https://github.com/aio-libs/aiobotocore/pull/116
        # aiohttp's CIMultiDict camel cases the headers :(
        'headers':
        HTTPHeaderDict({
            k.decode('utf-8').lower(): v.decode('utf-8')
            for k, v in http_response.raw_headers
        }),
        'status_code':
        http_response.status_code,
        'context': {
            'operation_name': operation_model.name,
        }
    }
    if response_dict['status_code'] >= 300:
        response_dict['body'] = await http_response.read()
    elif operation_model.has_event_stream_output:
        response_dict['body'] = http_response.raw
    elif operation_model.has_streaming_output:
        length = response_dict['headers'].get('content-length')
        response_dict['body'] = StreamingBody(http_response.raw, length)
    else:
        response_dict['body'] = await http_response.read()
    return response_dict
Пример #4
0
def test_activate_doesnt_change_signature_for_method():
    class TestCase(object):
        def test_function(self, a, b=None):
            return (self, a, b)

        decorated_test_function = responses.activate(test_function)

    test_case = TestCase()
    assert test_case.decorated_test_function(1, 2) == test_case.test_function(
        1, 2)
    assert test_case.decorated_test_function(3) == test_case.test_function(3)


@pytest.mark.parametrize("http_headers", [
    HTTPHeaderDict([(
        'Set-Cookie',
        'One=1; HttpOnly; Path=it/doesnt/matter; Expires=Sun, 06 Nov 2024 08:49:37 GMT; Secure; Max-Age=13'
    ), ('Set-Cookie', 'Two=2; Path=it/really/doesnt/matter')])
])
def test_response_cookies_for_real(http_headers):
    body = b"test callback"
    status = 200
    url = "http://example.com/"
    headers = dict(http_headers.itermerged())

    def request_callback(request):

        return (status, headers, body)

    @responses.activate
    def run():
        responses.add_callback(responses.GET, url, request_callback)
Пример #5
0
    def send(self, request, stream=False, timeout=None, verify=True,
             cert=None, proxies=None):

        # Prepare the request to send to the app.

        # webob will include the port into the HTTP_HOST header by default.
        #
        # It's not desirable, so let's insert it into the environment
        # manually. But only do this if the user hasn't set an explicit host
        # name.
        environ = {}
        if 'HTTP_HOST' not in self.app.extra_environ:
            parsed = urlparse(request.url)
            environ['HTTP_HOST'] = parsed.netloc

        non_body_methods = set('GET HEAD DELETE OPTIONS'.split())
        with_body_methods = set('POST PUT PATCH'.split())

        wtparams = dict(headers=request.headers, extra_environ=environ,
                        url=request.url, expect_errors=True)
        if request.method in with_body_methods:
            wtparams['params'] = request.body

        if stream and not issubclass(self.app.RequestClass, PyriformTestRequest):
            warnings.warn('Passing a TestApp instance to WSGIAdapter prevents '
                          'streamed requests from streaming content in real time.',
                          RuntimeWarning)

        # Delegate to the appropriate handler if we have one.
        if request.method in non_body_methods or \
                request.method in with_body_methods:
            handler = getattr(self.app, request.method.lower())
        else:
            # This is an internal method, but most handlers delegate to it, so
            # we'll just make use of it for unknown methods.
            wtparams['method'] = request.method
            handler = self.app._gen_request

        # We only care about the read timeout.
        if isinstance(timeout, tuple):
            _, timeout = timeout

        wtresp = self._invoke_handler(handler, wtparams, timeout)

        # Convert the response.
        resp = Response()
        resp.status_code = wtresp.status_code
        resp.reason = wtresp.status.split(' ', 1)[1]
        resp.url = request.url

        # Although HTTPHeaderDict is better positioned to handle multiple headers with the same
        # name, requests doesn't use this type for responses. Instead, it uses its own dictionary
        # type for headers (which doesn't have multiple header value support).
        #
        # But because it uses the HTTPHeaderDict object, all multiple value headers will be
        # compiled together, so that's what we store here (to be consistent with requests).
        #
        # It would be nice to use HTTPHeaderDict for the response, but we don't want to provide a
        # different object with a different API.
        resp.headers.update(HTTPHeaderDict(wtresp.headerlist))

        resp.request = request
        resp.raw = IterStringIO(wtresp._app_iter)
        return resp