requests.models.Response

Here are the examples of the python api requests.models.Response taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

90 Examples 7

Example 1

Project: dropbox-sdk-python
Source File: dropbox.py
View license
    def __init__(self, obj_result, http_resp=None):
        """
        :param str obj_result: The result of a route not including the binary
            payload portion, if one exists. Must be serialized JSON.
        :param requests.models.Response http_resp: A raw HTTP response. It will
            be used to stream the binary-body payload of the response.
        """
        assert isinstance(obj_result, six.string_types), \
            'obj_result: expected string, got %r' % type(obj_result)
        if http_resp is not None:
            assert isinstance(http_resp, requests.models.Response), \
                'http_resp: expected requests.models.Response, got %r' % \
                type(http_resp)
        self.obj_result = obj_result
        self.http_resp = http_resp

Example 2

Project: screencloud-plugins
Source File: dropbox.py
View license
    def __init__(self, obj_result, http_resp=None):
        """
        :param str obj_result: The result of a route not including the binary
            payload portion, if one exists. Must be serialized JSON.
        :param requests.models.Response http_resp: A raw HTTP response. It will
            be used to stream the binary-body payload of the response.
        """
        assert isinstance(obj_result, six.string_types), \
            'obj_result: expected string, got %r' % type(obj_result)
        if http_resp is not None:
            assert isinstance(http_resp, requests.models.Response), \
                'http_resp: expected requests.models.Response, got %r' % \
                type(http_resp)
        self.obj_result = obj_result
        self.http_resp = http_resp

Example 3

View license
    def _build_response(self, text):
        logger.debug("CurlSession: building response from %s" % text)
        raw_response = self._parse_http(text)
        response = requests.models.Response()
        response.encoding = 'utf-8'
        response.status_code = raw_response.status
        response.headers = dict(raw_response.getheaders())
        response._content = raw_response.read()
        return response

Example 4

Project: shuup
Source File: test_telemetry.py
View license
@pytest.mark.django_db
def test_telemetry_is_sent_on_login(rf, admin_user):
    shop = get_default_shop()
    with patch.object(requests, "post", return_value=Response()) as requestor:
        with override_settings(SHUUP_TELEMETRY_ENABLED=True):
            _backdate_installation_key(days=0)  # instance was created today
            request = apply_request_middleware(rf.get("/"), user=admin_user)
            view_func = DashboardView.as_view()
            response = view_func(request)
            sent = get_last_submission_time()

            response = view_func(request)
            assert get_last_submission_time() == sent

            response = view_func(request)
            assert get_last_submission_time() == sent

            assert len(requestor.mock_calls) == 1

Example 5

Project: shuup
Source File: test_telemetry.py
View license
@pytest.mark.django_db
def test_telemetry_multiple_days(rf):
    with override_settings(SHUUP_TELEMETRY_ENABLED=True, DEBUG=True):
        with patch.object(requests, "post", return_value=Response()) as requestor:
            try_send_telemetry()
            day = now()
            _backdate_telemetry_submission(days=0)
            assert not get_daily_data(day)
            _backdate_telemetry_submission(days=20)
            assert len(get_daily_data(now())) == 19  # Since current day is not added to telemetry

Example 6

Project: github3.py
Source File: decorators.py
View license
def generate_fake_error_response(msg, status_code=401, encoding='utf-8'):
    r = Response()
    r.status_code = status_code
    r.encoding = encoding
    r.raw = RequestsStringIO(msg.encode())
    r._content_consumed = True
    r._content = r.raw.read()
    return r

Example 7

Project: pelican-gist
Source File: test_plugin.py
View license
def test_fetch_gist():
    """Ensure fetch_gist returns the response content as a string."""
    CODE_BODY = "code"
    with patch('requests.get') as get:
        return_response = requests.models.Response()
        return_response.status_code = 200
        return_response._content= CODE_BODY.encode()
        get.return_value = return_response
        assert gistplugin.fetch_gist(1) == CODE_BODY

Example 8

Project: sublime-github
Source File: sublime_requests.py
View license
    def _build_response(self, text):
        logger.debug("CurlSession: building response from %s" % text)
        raw_response = self._parse_http(text)
        response = requests.models.Response()
        response.encoding = 'utf-8'
        response.status_code = raw_response.status
        response.headers = dict(raw_response.getheaders())
        response._content = raw_response.read()
        return response

Example 9

Project: bravado
Source File: exception_test.py
View license
@pytest.fixture
def response_500():
    requests_response = Response()
    requests_response.status_code = 500
    requests_response.reason = "Server Error"
    return requests_response

Example 10

Project: bravado
Source File: exception_test.py
View license
def test_make_http_exception_unknown():
    requests_response = Response()
    requests_response.status_code = 600
    requests_response.reason = "Womp Error"
    exc = make_http_exception(
        RequestsResponseAdapter(requests_response),
    )
    assert type(exc) == HTTPError

Example 11

Project: threat_intel
Source File: http_test.py
View license
    def mock_ok_responses(self, number_of_responses):
        """Mocks `number_of_responses` response mocks. All of them are with the "200 OK" HTTP status code."""
        responses = [Response() for _ in range(number_of_responses)]
        for response in responses:
            response.status_code = 200
            response._content = '{"Director": "Alejandro González Iñárritu"}'
        return responses

Example 12

Project: ClusterRunner
Source File: test_build_runner.py
View license
    def _create_build_runner_instance(self, response):
        mock_get_logger = self.patch('app.client.build_runner.get_logger')
        logger = mock_get_logger.return_value

        build_id = '1'

        runner = BuildRunner('url', {}, 'mellon')
        start_response = Response()
        start_response.json = MagicMock(return_value={'build_id': build_id})
        runner._network.post = MagicMock(return_value=start_response)
        status_response = Response()
        status_response.json = MagicMock(return_value=response)
        runner._network.get = MagicMock(return_value=status_response)
        runner._download_and_extract_results = MagicMock()
        return runner, logger, build_id

Example 13

Project: resources
Source File: test_resources.py
View license
    def test_resources_get(self):
        url = "http://localhost/api"
        client = Mock()
        fake_api = Resource(url, client=client)
        client.request.return_value = Response(200, "Hello")
        status, result = fake_api.get()
        self.assertEqual(200, status)
        self.assertEqual("Hello", result)

Example 14

Project: commcare-hq
Source File: tasks.py
View license
def _log_response(target, data, response):
    status_code = response.status_code if isinstance(response, requests.models.Response) else response.status
    try:
        response_text = json.dumps(response.json(), indent=2, sort_keys=True)
    except Exception:
        response_text = status_code

    message = 'Sent this data to {target}: {data} \nreceived: {response}'.format(
        target=target,
        data=json.dumps(data, indent=2, sort_keys=True),
        response=response_text
    )

    if status_code != 200:
        logger.error(message)
    else:
        logger.debug(message)

Example 15

Project: gitsome
Source File: decorators.py
View license
def generate_fake_error_response(msg, status_code=401, encoding='utf-8'):
    r = Response()
    r.status_code = status_code
    r.encoding = encoding
    r.raw = RequestsStringIO(msg.encode())
    r._content_consumed = True
    r._content = r.raw.read()
    return r

Example 16

Project: http-prompt
Source File: test_cli.py
View license
    def setUp(self):
        self.listener = ExecutionListener({})

        self.response = Response()
        self.response.cookies.update({
            'username': 'john',
            'sessionid': 'abcd'
        })

        self.context = Context('http://localhost')
        self.context.headers['Cookie'] = 'name="John Doe"; sessionid=xyz'

Example 17

Project: python-salesforce-client
Source File: base.py
View license
    def send(self, request, **kwargs):
        response = Response()
        response.headers = {}
        response.encoding = 'utf-8'  # FIXME: this is a complete guess
        response.url = request.url
        response.request = request
        response.connection = self

        try:
            response.raw = open(request.url.replace('file://', ''), 'r')
        except IOError as e:
            response.status_code = 404
            return response

        response.status_code = 200
        return response

Example 18

View license
    def _build_response(self, text):
        logger.debug("CurlSession: building response from %s" % text)
        raw_response = self._parse_http(text)
        response = requests.models.Response()
        response.encoding = 'utf-8'
        response.status_code = raw_response.status
        response.headers = dict(raw_response.getheaders())
        response._content = raw_response.read()
        return response

Example 19

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_account_list():
    resp = Response()
    resp._content = helpers.account_list
    with patch('sdk.resources.request') as mock_req:
        mock_req.return_value = resp
        accounts = Account().all()
        assert len(accounts) > 0
        assert all([isinstance(x, Account) for x in accounts])

Example 20

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_account_retrieve():
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.account
        mock_req.return_value = resp
        account_data = json.loads(helpers.account)
        account = Account().retrieve(account_data['id'])
        assert isinstance(account, Account)
        for attr in ['id', 'service', 'active', 'account']:
            assert account_data[attr] == getattr(account, attr)
        mock_req.assert_called_with(account._api_session.get,
                                    'accounts/%s' % account_data['id'],
                                    configuration=None,
                                    params={})

Example 21

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_folder_contents():
    account = Account.create_from_data(json.loads(helpers.account))
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.root_folder_contents
        mock_req.return_value = resp
        folder = account.folders()
        contents = folder.contents()
        assert len(contents) > 0
        assert all([(isinstance(x, Folder) or isinstance(x, File)) for x in contents])
        mock_req.assert_called_with(folder._api_session.get,
                                    ('accounts/%s/folders/root/contents'
                                        % account.id),
                                    configuration=account._configuration)

Example 22

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_folder_metadata():
    account = Account.create_from_data(json.loads(helpers.account))
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.folder_data
        mock_req.return_value = resp
        folder_data = json.loads(helpers.folder_data)
        folder = Folder.retrieve(id=folder_data['id'],
                                 parent_resource=account)
        assert isinstance(folder, Folder)
        for attr in ['id', 'name', 'type', 'size', 'account']:
            assert folder_data[attr] == getattr(folder, attr)
        mock_req.assert_called_with(Folder._api_session.get,
                                    ('accounts/%s/folders/%s'
                                        % (account.id, folder_data['id'])),
                                    configuration=None,
                                    params={})

Example 23

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_folder_delete():
    account = Account.create_from_data(json.loads(helpers.account))
    folder_data = json.loads(helpers.folder_data)
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp.status_code = 204
        mock_req.resturn_value = resp
        folder = Folder.create_from_data(json.loads(helpers.folder_data),
                                         parent_resource=account)
        folder.delete()
        mock_req.assert_called_with(Folder._api_session.delete,
                                    ('accounts/%s/folders/%s'
                                     % (account.id, folder_data['id'])),
                                    configuration=account._configuration,
                                    params={})

Example 24

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_file_metadata():
    account = Account.create_from_data(json.loads(helpers.account))
    file_data = json.loads(helpers.file_data)
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.file_data
        mock_req.return_value = resp
        file_obj = File.retrieve(id=file_data['id'],
                                 parent_resource=account)
        assert isinstance(file_obj, File)
        for attr in ['id', 'name', 'type', 'size', 'account']:
            assert file_data[attr] == getattr(file_obj, attr)
        mock_req.assert_called_with(File._api_session.get,
                                    ('accounts/%s/files/%s'
                                        % (account.id, file_data['id'])),
                                    configuration=None,
                                    params={})

Example 25

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_file_contents():
    account = Account.create_from_data(json.loads(helpers.account))
    file_data = json.loads(helpers.file_data)
    file_obj = File.create_from_data(file_data, parent_resource=account)
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.file_contents
        mock_req.return_value = resp
        file_contents = file_obj.contents()
        assert isinstance(file_contents, Response)
        mock_req.assert_called_with(file_obj._api_session.get,
                                    ('accounts/%s/files/%s/contents'
                                        % (account.id, file_data['id'])),
                                    configuration=file_obj._configuration,
                                    stream=True)

Example 26

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_account_list():
    resp = Response()
    resp._content = helpers.account_list
    with patch('sdk.resources.request') as mock_req:
        mock_req.return_value = resp
        accounts = Account().all()
        assert len(accounts) > 0
        assert all([isinstance(x, Account) for x in accounts])

Example 27

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_file_delete():
    account = Account.create_from_data(json.loads(helpers.account))
    file_data = json.loads(helpers.file_data)
    file_obj = File.create_from_data(file_data, parent_resource=account)
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp.status_code = 204
        mock_req.return_value = resp
        file_obj.delete()
        mock_req.assert_called_with(file_obj._api_session.delete,
                                    ('accounts/%s/files/%s'
                                        % (account.id, file_data['id'])),
                                    configuration=file_obj._configuration,
                                    params={})

Example 28

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_account_retrieve():
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.account
        mock_req.return_value = resp
        account_data = json.loads(helpers.account)
        account = Account().retrieve(account_data['id'])
        assert isinstance(account, Account)
        for attr in ['id', 'service', 'active', 'account']:
            assert account_data[attr] == getattr(account, attr)
        mock_req.assert_called_with(account._api_session.get,
                                    'accounts/%s' % account_data['id'],
                                    configuration=None,
                                    params={})

Example 29

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_folder_contents():
    account = Account.create_from_data(json.loads(helpers.account))
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.root_folder_contents
        mock_req.return_value = resp
        folder = account.folders()
        contents = folder.contents()
        assert len(contents) > 0
        assert all([(isinstance(x, Folder) or isinstance(x, File)) for x in contents])
        mock_req.assert_called_with(folder._api_session.get,
                                    ('accounts/%s/folders/root/contents'
                                        % account.id),
                                    configuration=account._configuration)

Example 30

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_folder_metadata():
    account = Account.create_from_data(json.loads(helpers.account))
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.folder_data
        mock_req.return_value = resp
        folder_data = json.loads(helpers.folder_data)
        folder = Folder.retrieve(id=folder_data['id'],
                                 parent_resource=account)
        assert isinstance(folder, Folder)
        for attr in ['id', 'name', 'type', 'size', 'account']:
            assert folder_data[attr] == getattr(folder, attr)
        mock_req.assert_called_with(Folder._api_session.get,
                                    ('accounts/%s/folders/%s'
                                        % (account.id, folder_data['id'])),
                                    configuration=None,
                                    params={})

Example 31

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_folder_delete():
    account = Account.create_from_data(json.loads(helpers.account))
    folder_data = json.loads(helpers.folder_data)
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp.status_code = 204
        mock_req.resturn_value = resp
        folder = Folder.create_from_data(json.loads(helpers.folder_data),
                                         parent_resource=account)
        folder.delete()
        mock_req.assert_called_with(Folder._api_session.delete,
                                    ('accounts/%s/folders/%s'
                                     % (account.id, folder_data['id'])),
                                    configuration=account._configuration,
                                    params={})

Example 32

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_file_metadata():
    account = Account.create_from_data(json.loads(helpers.account))
    file_data = json.loads(helpers.file_data)
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.file_data
        mock_req.return_value = resp
        file_obj = File.retrieve(id=file_data['id'],
                                 parent_resource=account)
        assert isinstance(file_obj, File)
        for attr in ['id', 'name', 'type', 'size', 'account']:
            assert file_data[attr] == getattr(file_obj, attr)
        mock_req.assert_called_with(File._api_session.get,
                                    ('accounts/%s/files/%s'
                                        % (account.id, file_data['id'])),
                                    configuration=None,
                                    params={})

Example 33

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_file_contents():
    account = Account.create_from_data(json.loads(helpers.account))
    file_data = json.loads(helpers.file_data)
    file_obj = File.create_from_data(file_data, parent_resource=account)
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp._content = helpers.file_contents
        mock_req.return_value = resp
        file_contents = file_obj.contents()
        assert isinstance(file_contents, Response)
        mock_req.assert_called_with(file_obj._api_session.get,
                                    ('accounts/%s/files/%s/contents'
                                        % (account.id, file_data['id'])),
                                    configuration=file_obj._configuration,
                                    stream=True)

Example 34

Project: kloudless-python
Source File: test_resources.py
View license
@helpers.configured_test
def test_file_delete():
    account = Account.create_from_data(json.loads(helpers.account))
    file_data = json.loads(helpers.file_data)
    file_obj = File.create_from_data(file_data, parent_resource=account)
    with patch('sdk.resources.request') as mock_req:
        resp = Response()
        resp.status_code = 204
        mock_req.return_value = resp
        file_obj.delete()
        mock_req.assert_called_with(file_obj._api_session.delete,
                                    ('accounts/%s/files/%s'
                                        % (account.id, file_data['id'])),
                                    configuration=file_obj._configuration,
                                    params={})

Example 35

View license
    @mock.patch(
        'leap.bitmask.config.providerconfig.ProviderConfig.get_api_uri',
        lambda x: 'api.uri')
    @mock.patch(
        'leap.bitmask.config.providerconfig.ProviderConfig.get_ca_cert_path',
        lambda x: '/cert/path')
    def test_check_api_certificate_skips(self):
        self.pb._provider_config = ProviderConfig()
        self.pb._session.get = mock.MagicMock(return_value=Response())

        self.pb._should_proceed_cert = mock.MagicMock(return_value=False)
        self.pb._check_api_certificate()
        self.assertFalse(self.pb._session.get.called)

Example 36

View license
    @mock.patch(
        'leap.bitmask.config.providerconfig.ProviderConfig.get_api_uri',
        lambda x: 'api.uri')
    @mock.patch(
        'leap.bitmask.config.providerconfig.ProviderConfig.get_ca_cert_path',
        lambda x: '/cert/path')
    def test_check_api_certificate_skips(self):
        self.pb._provider_config = ProviderConfig()
        self.pb._session.get = mock.MagicMock(return_value=Response())

        self.pb._should_proceed_cert = mock.MagicMock(return_value=False)
        self.pb._check_api_certificate()
        self.assertFalse(self.pb._session.get.called)

Example 37

View license
    def _build_response(self, text):
        logger.debug("CurlSession: building response from %s" % text)
        raw_response = self._parse_http(text)
        response = requests.models.Response()
        response.encoding = 'utf-8'
        response.status_code = raw_response.status
        response.headers = dict(raw_response.getheaders())
        response._content = raw_response.read()
        return response

Example 38

View license
    def _build_response(self, text):
        logger.debug("CurlSession: building response from %s" % text)
        raw_response = self._parse_http(text)
        response = requests.models.Response()
        response.encoding = 'utf-8'
        response.status_code = raw_response.status
        response.headers = dict(raw_response.getheaders())
        response._content = raw_response.read()
        return response

Example 39

Project: openprocurement.api
Source File: base.py
View license
    def setUpDS(self):
        self.app.app.registry.docservice_url = 'http://localhost'
        test = self
        def request(method, url, **kwargs):
            response = Response()
            if method == 'POST' and '/upload' in url:
                url = test.generate_docservice_url()
                response.status_code = 200
                response.encoding = 'application/json'
                response._content = '{{"data":{{"url":"{url}","hash":"md5:{md5}","format":"application/msword","title":"name.doc"}},"get_url":"{url}"}}'.format(url=url, md5='0'*32)
                response.reason = '200 OK'
            return response

        self._srequest = SESSION.request
        SESSION.request = request

Example 40

Project: openprocurement.api
Source File: base.py
View license
    def setUpBadDS(self):
        self.app.app.registry.docservice_url = 'http://localhost'
        def request(method, url, **kwargs):
            response = Response()
            response.status_code = 403
            response.encoding = 'application/json'
            response._content = '"Unauthorized: upload_view failed permission check"'
            response.reason = '403 Forbidden'
            return response

        self._srequest = SESSION.request
        SESSION.request = request

Example 41

Project: glance_store
Source File: utils.py
View license
def fake_response(status_code=200, headers=None, content=None, **kwargs):
    r = requests.models.Response()
    r.status_code = status_code
    r.headers = headers or {}
    r.raw = FakeHTTPResponse(status_code, headers, content, kwargs)
    return r

Example 42

View license
    @classmethod
    def _make_response(cls, status_code=OK, content=None):
        """Only supports 'content-type': 'application/json'"""
        response = requests.models.Response()
        response.status_code = status_code
        if content:
            response.raw = six.BytesIO(
                jsonutils.dumps(content).encode('utf-8'))

        return response

Example 43

Project: mirocommunity
Source File: __init__.py
View license
    @staticmethod
    def get_response(content, code=200):
        response = Response()
        if hasattr(content, 'read'):
            content = content.read()
        response._content = content
        response.status_code = code
        return response

Example 44

Project: smartsheet-python-sdk
Source File: smartsheet.py
View license
    def __init__(self, op_result, resp=None, base_obj=None, operation=None):
        """Initialize OperationResult.

        Args:
            op_result (str): The result of an operation not including
                the binary payload portion, if one exists. Must be
                a JSON string.
            resp (requests.models.Response): A raw HTTP response.
                It will be used to stream the binary-body payload of the
                response.
            base_obj (smartsheet.Smartsheet): Configured core object
                for subsequent convenience method requests.
        """
        assert isinstance(op_result, six.string_types), \
            'op_result: expected string, got %r' % type(op_result)
        if resp is not None:
            assert isinstance(resp, requests.models.Response), \
                'resp: expected requests.models.Response, got %r' % \
                type(resp)
        self._base = base_obj
        self.op_result = op_result
        self.resp = resp
        self.dynamic_data_types = []
        self.operation = operation

Example 45

Project: pypowervm
Source File: test_adapter.py
View license
    def _mk_response(self, status, content=None):
        reasons = {200: 'OK', 204: 'No Content', 401: 'Unauthorized'}
        # Create a Response object, that will serve as a mock return value
        my_response = req_mod.Response()
        my_response.status_code = status
        my_response.reason = reasons[status]
        clen = '0'
        if status == 200 and content:
            clen = str(len(content))
        dict_headers = {
            'content-length': clen, 'x-powered-by': 'Servlet/3.0',
            'set-cookie': ('JSESSIONID=0000a41BnJsGTNQvBGERA3wR1nj:759878cb-4f'
                           '9a-4b05-a09a-3357abfea3b4; Path=/; Secure; HttpOnl'
                           'y, CCFWSESSION=E4C0FFBE9130431DBF1864171ECC6A6E; P'
                           'ath=/; Secure; HttpOnly'),
            'expires': 'Thu, 01 Dec 1994 16:00:00 GMT',
            'x-transaction-id': 'XT10000073',
            'cache-control': 'no-cache="set-cookie, set-cookie2"',
            'date': 'Wed, 23 Jul 2014 21:51:10 GMT',
            'content-type': 'application/vnd.ibm.powervm'}
        my_response.headers = req_struct.CaseInsensitiveDict(dict_headers)
        my_response._content = content
        return my_response

Example 46

Project: pypowervm
Source File: test_session.py
View license
    @mock.patch('pypowervm.util.validate_certificate')
    @mock.patch('requests.Session')
    def test_logon(self, mock_session, mock_validate_cert):
        """Ensure a Session can be created and log on to PowerVM."""

        # Init test data
        host = '0.0.0.0'
        user = 'user'
        pwd = 'pwd'
        auditmemento = 'audit'

        # Create a Response object, that will serve as a mock return value
        my_response = req_mod.Response()
        my_response.status_code = 200
        my_response.reason = 'OK'
        dict_headers = {'content-length': '576',
                        'x-powered-by': 'Servlet/3.0',
                        'set-cookie': 'JSESSIONID=0000a41BnJsGTNQvBGERA3wR1nj:'
                                      '759878cb-4f9a-4b05-a09a-3357abfea3b4; P'
                                      'ath=/; Secure; HttpOnly, CCFWSESSION=E4'
                                      'C0FFBE9130431DBF1864171ECC6A6E; Path=/;'
                                      ' Secure; HttpOnly',
                        'expires': 'Thu, 01 Dec 1994 16:00:00 GMT',
                        'x-transaction-id': 'XT10000073',
                        'cache-control': 'no-cache="set-cookie, set-cookie2"',
                        'date': 'Wed, 23 Jul 2014 21:51:10 GMT',
                        'content-type': 'application/vnd.ibm.powervm.web+xml; '
                                        'type=LogonResponse'}
        my_response.headers = req_struct.CaseInsensitiveDict(dict_headers)
        my_response._content = _logon_response_password

        # Mock out the method and class we are not currently testing
        session = mock_session.return_value
        session.request.return_value = my_response

        # Run the actual test
        result = adp.Session(host, user, pwd, auditmemento=auditmemento)

        # Verify the result
        self.assertTrue(result._logged_in)
        self.assertEqual('PUIoR6x0kP6fQqA7qZ8sLZQJ8MLx9JHfLCYzT4oGFSE2WaGIhaFX'
                         'IyQYvbqdKNS8QagjBpPi9NP7YR_h61SOJ3krS_RvKAp-oCf2p8x8'
                         'uvQrrDv-dUzc17IT5DkR7_jv2qc8iUD7DJ6Rw53a17rY0p63KqPg'
                         '9oUGd6Bn3fNDLiEwaBR4WICftVxUFj-tfWMOyZZY2hWEtN2K8ScX'
                         'vyFMe-w3SleyRbGnlR34jb0A99s=', result._sessToken)
        self.assertEqual(1, mock_validate_cert.call_count)
        # No X-MC-Type header => 'HMC' is assumed.
        self.assertEqual('HMC', result.mc_type)

        # Now test file-based authentication and X-MC-Type
        my_response._content = _logon_response_file

        # Local/HMC is bad
        self.assertRaises(pvmex.Error, adp.Session)

        my_response.headers['X-MC-Type'] = 'PVM'
        result = adp.Session()

        # Verify the result.
        self.assertTrue(result._logged_in)
        # Token read from token_file, as indicated by logon_file.xml response.
        self.assertEqual('file-based-auth-token', result._sessToken)
        # validate_certificate should not have been called again
        self.assertEqual(1, mock_validate_cert.call_count)
        self.assertEqual('PVM', result.mc_type)

Example 47

Project: pypowervm
Source File: test_traits.py
View license
    @mock.patch('requests.Session.request')
    def test_traits_into_wrappers(self, mock_request):
        # Note traits param is None, which reflects the real value of
        # self.traits during _logon's request.
        httpresp = req_mod.Response()
        httpresp._content = _logon_response_text
        httpresp.status_code = 200
        httpresp.headers = req_struct.CaseInsensitiveDict(
            {'X-MC-Type': 'PVM',
             'content-type':
                 'application/vnd.ibm.powervm.web+xml; type=LogonResponse'})
        mock_request.return_value = httpresp
        sess = adp.Session()
        self.assertEqual('PVM', sess.mc_type)
        self.assertIsNotNone(sess.traits)
        self.assertTrue(sess.traits.local_api)
        self.assertFalse(sess.traits._is_hmc)
        adapter = adp.Adapter(sess)
        self.assertEqual(sess.traits, adapter.traits)

        # Response => Feed => Entrys => EntryWrappers => sub-ElementWrappers
        httpresp._content = _feed_file
        resp = adapter.read('NetworkBridge')
        self.assertEqual(sess.traits, resp.adapter.traits)
        nblist = net.NetBridge.wrap(resp)
        for nb in nblist:
            self.assertIsInstance(nb, net.NetBridge)
            self.assertEqual(sess.traits, nb.traits)
        seas = nblist[0].seas
        for sea in seas:
            self.assertIsInstance(sea, net.SEA)
            self.assertEqual(sess.traits, sea.traits)
        trunk = seas[0].primary_adpt
        self.assertIsInstance(trunk, net.TrunkAdapter)
        self.assertEqual(sess.traits, trunk.traits)

        # Response => Entry => EntryWrapper => sub-EntryWrappers
        # => sub-sub-ElementWrapper
        httpresp._content = _entry_file
        resp = adapter.read('VolumeGroup', root_id='abc123')
        self.assertEqual(sess.traits, resp.adapter.traits)
        vgent = stor.VG.wrap(resp)
        self.assertIsInstance(vgent, stor.VG)
        self.assertEqual(sess.traits, vgent.traits)
        pvs = vgent.phys_vols
        for pvent in pvs:
            self.assertIsInstance(pvent, stor.PV)
            self.assertEqual(sess.traits, pvent.traits)

        # Building raw wrappers from scratch
        class MyEntryWrapper(ewrap.EntryWrapper):
            schema_type = 'SomeObject'

            @classmethod
            def bld(cls, adpt):
                return super(MyEntryWrapper, cls)._bld(adpt)

        mew = MyEntryWrapper.bld(adapter)
        self.assertIsInstance(mew, MyEntryWrapper)
        self.assertEqual(sess.traits, mew.traits)

        class MyElementWrapper(ewrap.ElementWrapper):
            schema_type = 'SomeObject'

            @classmethod
            def bld(cls, adpt):
                return super(MyElementWrapper, cls)._bld(adpt)

        mew = MyElementWrapper.bld(adapter)
        self.assertIsInstance(mew, MyElementWrapper)
        self.assertEqual(sess.traits, mew.traits)

Example 48

Project: pulp
Source File: adapters.py
View license
    def build_response(self, req, resp):
        """Builds a :class:`Response <requests.Response>` object from a urllib3
        response. This should not be called from user code, and is only exposed
        for use when subclassing the
        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`

        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
        :param resp: The urllib3 response object.
        """
        response = Response()

        # Fallback to None if there's no status_code, for whatever reason.
        response.status_code = getattr(resp, 'status', None)

        # Make headers case-insensitive.
        response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))

        # Set encoding.
        response.encoding = get_encoding_from_headers(response.headers)
        response.raw = resp
        response.reason = response.raw.reason

        if isinstance(req.url, bytes):
            response.url = req.url.decode('utf-8')
        else:
            response.url = req.url

        # Add new cookies from the server.
        extract_cookies_to_jar(response.cookies, req, resp)

        # Give the Response some context.
        response.request = req
        response.connection = self

        return response

Example 49

Project: stoq-plugins-public
Source File: FireEyeMAS.py
View license
    def __init__(self, responseObject, responseType='json'):

        if responseType not in self.valid_response_types:
            raise Exception('Invalid response type specified')

        self.response_type = responseType

        # Check if responseObject is requests response object
        if isinstance(responseObject, requests.models.Response):
            # Process requests response object depending on specified type
            if responseType == 'json':
                try:
                    self.response_object = responseObject.json()
                except ValueError:
                    # Attempt to cleanup malformed or unwanted JSON elements
                    # from FireEye and then use demjson to load the object
                    cleanedObject = re.sub(r'\n\s+', '', responseObject.text)
                    cleanedObject = re.sub(r'\n', '', cleanedObject)
                    cleanedObject = re.sub(r'(\"+)?N/A(\"+)?', '\"N/A\"', cleanedObject)
                    self.response_object = demjson.decode(cleanedObject)
                except:
                    message = 'JSON parsing error of response:\n{}'\
                              .format(responseObject.text)
                    raise Exception(message)
            elif responseType == 'xml':
                self.response_object = lxml.etree.fromstring(responseObject.content)
            elif responseType == 'text':
                self.response_object = responseObject.text
            else:  # placeholder for future types
                self.response_object = responseObject.text
        else:
            self.response_object = responseObject

Example 50

Project: shuup
Source File: test_telemetry.py
View license
@pytest.mark.django_db
def test_optin_optout(rf):
    with override_settings(SHUUP_TELEMETRY_ENABLED=True, DEBUG=True):
        with patch.object(requests, "post", return_value=Response()) as requestor:
            _clear_telemetry_submission()
            assert not set_opt_out(False)  # Not opted out
            assert not is_opt_out()
            try_send_telemetry()
            with pytest.raises(TelemetryNotSent) as ei:
                try_send_telemetry(raise_on_error=True)  # Still gracey
            assert ei.value.code == "grace"

            _backdate_installation_key()
            try_send_telemetry(max_age_hours=72)
            try_send_telemetry(max_age_hours=None)  # Forcibly re-send for the hell of it
            with pytest.raises(TelemetryNotSent) as ei:
                try_send_telemetry(raise_on_error=True)  # Don't ignore last-send; shouldn't send anyway
            assert ei.value.code == "age"

            assert len(requestor.mock_calls) == 2
            assert set_opt_out(True)
            assert is_opt_out()
            with pytest.raises(TelemetryNotSent) as ei:
                try_send_telemetry(max_age_hours=0, raise_on_error=True)
            assert ei.value.code == "optout"
            assert len(requestor.mock_calls) == 2