Python requests.models.Response() Examples

The following are 30 code examples of requests.models.Response(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module requests.models , or try the search function .
Example #1
Source File: services.py    From bioservices with GNU General Public License v3.0 7 votes vote down vote up
def _interpret_returned_request(self, res, frmt):
        # must be a Response
        if isinstance(res, Response) is False:
            return res
        # if a response, there is a status code that should be ok
        if not res.ok:
            reason = res.reason
            self.logging.warning("status is not ok with {0}".format(reason))
            return res.status_code
        if frmt == "json":
            try:
                return res.json()
            except:
                return res
        # finally
        return res.content 
Example #2
Source File: crawler.py    From ITWSV with MIT License 7 votes vote down vote up
def __init__(self, response: Response, url: str, empty: bool = False):
        """Create a new Page object.

        @type response: Response
        @param response: a requests Response instance.

        @type url: str
        @param url: URL of the Page.

        @type empty: bool
        @param empty: whether the Page is empty (body length == 0)"""
        self._response = response
        self._url = url
        self._base = None
        self._soup = None
        self._is_empty = empty
        try:
            self._tld = get_tld(url)
        except TldDomainNotFound:
            self._tld = urlparse(url).netloc 
Example #3
Source File: test_api_object.py    From coinbase-python with Apache License 2.0 7 votes vote down vote up
def test_new_api_object(self):
        def api_client(x): return x
        obj = new_api_object(api_client, simple_data)
        self.assertIsInstance(obj, APIObject)
        self.assertIsNone(obj.response)
        self.assertIsNone(obj.pagination)
        self.assertIsNone(obj.warnings)

        response = Response()

        def pagination(x): return x

        def warnings(x): return x
        obj = new_api_object(
            api_client, simple_data, response=response, pagination=pagination,
            warnings=warnings)
        self.assertIs(obj.response, response)
        self.assertIs(obj.pagination, pagination)
        self.assertIs(obj.warnings, warnings) 
Example #4
Source File: test_exceptions.py    From python-gnocchiclient with Apache License 2.0 6 votes vote down vote up
def test_from_response_404_with_detail(self):
        r = models.Response()
        r.status_code = 404
        r.headers['Content-Type'] = "application/json"
        r._content = json.dumps({
            "code": 404,
            "description": {
                "cause": "Aggregation method does not exist for this metric",
                "detail": {
                    "aggregation_method": "rate:mean",
                    "metric": "a914dad6-b8f6-42f6-b090-6daa29725caf",
                }},
            "title": "Not Found"
        }).encode('utf-8')
        exc = exceptions.from_response(r)
        self.assertIsInstance(exc, exceptions.ClientException) 
Example #5
Source File: test_flask.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test(self):
        patience = 100
        while True:
            try:
                response = requests.get("http://localhost:{}".format(self.port))
                break
            except ConnectionError:
                patience -= 1
                if not patience:
                    self.fail(
                        "Couldn't get response from app, (Python executable {})".format(
                            sys.executable
                        )
                    )
                else:
                    sleep(0.1)

        self.assertIsInstance(response, Response)
        self.assertIn("Hello There!", response.text) 
Example #6
Source File: bulk_daemon.py    From search-MjoLniR with MIT License 6 votes vote down vote up
def on_file_available(self, uri: str, response: Response) -> None:
        # Metadata we aren't interested in
        if os.path.basename(uri)[0] == '_':
            return
        lines = _decode_response_as_text_lines(uri, response)
        """Import a file in elasticsearch bulk import format."""
        log.info('Importing from uri %s', uri)
        good, missing, errors = bulk_import(
            client=self.elastic,
            index=self.index_name,
            doc_type="_doc",
            actions=pair(line.strip() for line in lines),
            expand_action_callback=expand_string_actions,
            **self.bulk_kwargs)
        self.good_imports += good
        self.errored_imports += errors 
Example #7
Source File: base.py    From python-salesforce-client with MIT License 6 votes vote down vote up
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 #8
Source File: hashivault_pki_ca_set.py    From ansible-modules-hashivault with MIT License 6 votes vote down vote up
def hashivault_pki_ca_set(module):
    params = module.params
    client = hashivault_auth_client(params)
    mount_point = params.get('mount_point').strip('/')
    pem_bundle = params.get('pem_bundle')

    # check if engine is enabled
    changed, err = check_secrets_engines(module, client)
    if err:
        return err

    result = {'changed': changed}
    if module.check_mode:
        return result

    data = client.secrets.pki.submit_ca_information(pem_bundle=pem_bundle, mount_point=mount_point)
    if data:
        from requests.models import Response
        if isinstance(data, Response):
            result['data'] = data.text
        else:
            result['data'] = data

    return result 
Example #9
Source File: hashivault_pki_ca_set.py    From ansible-modules-hashivault with MIT License 6 votes vote down vote up
def hashivault_pki_ca_set(module):
    params = module.params
    client = hashivault_auth_client(params)
    mount_point = params.get('mount_point').strip('/')
    pem_bundle = params.get('pem_bundle')

    # check if engine is enabled
    changed, err = check_secrets_engines(module, client)
    if err:
        return err

    result = {'changed': changed}
    if module.check_mode:
        return result

    data = client.secrets.pki.submit_ca_information(pem_bundle=pem_bundle, mount_point=mount_point)
    if data:
        from requests.models import Response
        if isinstance(data, Response):
            result['data'] = data.text
        else:
            result['data'] = data

    return result 
Example #10
Source File: test_datastore_taxii.py    From cti-python-stix2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_objects(self, **filter_kwargs):
        self._verify_can_read()
        query_params = _filter_kwargs_to_query_params(filter_kwargs)
        assert isinstance(query_params, dict)
        full_filter = BasicFilter(query_params)
        objs = full_filter.process_filter(
            self.objects,
            ("id", "type", "version"),
            self.manifests,
            100,
        )[0]
        if objs:
            return stix2.v21.Bundle(objects=objs)
        else:
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status() 
Example #11
Source File: test_datastore_taxii.py    From cti-python-stix2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_object(self, id, **filter_kwargs):
        self._verify_can_read()
        query_params = _filter_kwargs_to_query_params(filter_kwargs)
        assert isinstance(query_params, dict)
        full_filter = BasicFilter(query_params)

        # In this endpoint we must first filter objects by id beforehand.
        objects = [x for x in self.objects if x["id"] == id]
        if objects:
            filtered_objects = full_filter.process_filter(
                objects,
                ("version",),
                self.manifests,
                100,
            )[0]
        else:
            filtered_objects = []
        if filtered_objects:
            return stix2.v21.Bundle(objects=filtered_objects)
        else:
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status() 
Example #12
Source File: test_datastore_taxii.py    From cti-python-stix2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_objects(self, **filter_kwargs):
        self._verify_can_read()
        query_params = _filter_kwargs_to_query_params(filter_kwargs)
        assert isinstance(query_params, dict)
        full_filter = BasicFilter(query_params)
        objs = full_filter.process_filter(
            self.objects,
            ("id", "type", "version"),
            self.manifests,
            100,
        )[0]
        if objs:
            return stix2.v20.Bundle(objects=objs)
        else:
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status() 
Example #13
Source File: test_forms.py    From ocl_web with Mozilla Public License 2.0 6 votes vote down vote up
def test_when_defaultLocales_is_not_provided_then_form_is_not_valid(self, mock_get):
        form_data = {
            'short_code': 'col',
            'name': 'col',
            'full_name': 'collection',
            'collection_type': 'Dictionary',
            'public_access': 'Edit',
            'default_locale': 'en',
            'supported_locales': 'en'
        }

        response = Response()
        response.json = lambda: [{'locale': 'en', 'display_name': 'en'}]
        mock_get.return_value = response

        form = CollectionCreateForm(data=form_data)
        self.assertTrue(form.is_valid()) 
Example #14
Source File: test_forms.py    From ocl_web with Mozilla Public License 2.0 6 votes vote down vote up
def test_when_all_valid_data_is_provided_then_new_collection_should_be_made(self, mock_get):
        form_data = {
            'short_code': 'col',
            'name': 'col',
            'full_name': 'collection',
            'collection_type': 'Dictionary',
            'public_access': 'Edit',
            'default_locale': 'en',
            'supported_locales': 'en'
        }
        response = Response()
        response.json = lambda: [{'locale': 'en', 'display_name': 'en'}]
        mock_get.return_value = response

        form = CollectionCreateForm(data=form_data)
        self.assertTrue(form.is_valid()) 
Example #15
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 6 votes vote down vote up
def test_getContextForOrgColVersion_contextForOrgReceived(self, mock_get):
        colResponse = MagicMock(spec=Response)
        colResponse.json.return_value = "collection_version"
        mock_get.return_value = colResponse
        collectionVersionEditView = views.CollectionVersionEditView()
        collectionVersionEditView.request = FakeRequest()
        collectionVersionEditView.collection = {'id': 'mycolid'}
        collectionVersionEditView.kwargs = {
            'org': 'testOrgId',
            'id': 'v1'
        }
        collectionVersionEditView.get_form_class()
        context = collectionVersionEditView.get_context_data();
        self.assertEquals(context['kwargs']['org'], "testOrgId")
        self.assertEquals(context['kwargs']['id'], "v1")
        self.assertTrue(context['collection_version'], 'collection_version')
        self.assertNotIn('user', context) 
Example #16
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 6 votes vote down vote up
def test_getContextForUserColVersion_contextForUserReceived(self, mock_get):
        colResponse = MagicMock(spec=Response)
        colResponse.json.return_value = "collection_version"
        mock_get.return_value = colResponse
        collectionVersionEditView = views.CollectionVersionEditView()
        collectionVersionEditView.request = FakeRequest()
        collectionVersionEditView.collection = {'id': 'mycolid'}
        collectionVersionEditView.kwargs = {
            'user': 'testUserId',
            'id': 'v1'
        }
        collectionVersionEditView.get_form_class()
        context = collectionVersionEditView.get_context_data()
        self.assertNotIn('org', context)
        self.assertEquals(context['kwargs']['user'], "testUserId")
        self.assertEquals(context['kwargs']['id'], "v1")
        self.assertTrue(context['collection_version'], 'collection_version') 
Example #17
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 6 votes vote down vote up
def test_getContextForCollectionReferences_contextRecieved(self, mock_get):
        referenceResponse = MagicMock(spec=Response)
        references = ["Some Results"]
        referenceResponse.json.return_value = references
        referenceResponse.status_code = 200
        referenceResponse.headers = []

        mock_get.return_value = referenceResponse

        collectionReferencesView = views.CollectionReferencesView()
        collectionReferencesView.request = FakeRequest()

        hash = {'collection': 'test', 'org': 'org1'}
        collectionReferencesView.kwargs = hash
        context = collectionReferencesView.get_context_data()

        self.assertEquals(context['kwargs'], hash)
        self.assertEquals(context['selected_tab'], 'References')
        self.assertEquals(context['collection'], references) 
Example #18
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 6 votes vote down vote up
def test_getContextForCollectionConcepts_contextRecieved(self, mock_get):
        conceptResponse = MagicMock(spec=Response)
        collection = []
        conceptResponse.json.return_value = collection
        conceptResponse.status_code = 200
        conceptResponse.headers = []
        mock_get.return_value = conceptResponse

        collectionConceptsView = views.CollectionConceptsView()
        collectionConceptsView.request = FakeRequest()

        hash = {'collection': 'test', 'org': 'org1'}
        collectionConceptsView.kwargs = hash
        context = collectionConceptsView.get_context_data()

        self.assertEquals(context['kwargs'], hash)
        self.assertEquals(context['selected_tab'], 'Concepts')
        self.assertEquals(context['results'], collection)
        self.assertEquals(context['pagination_url'], '/foobar')
        self.assertEquals(context['search_query'], '')
        self.assertIsInstance(context['search_filters'], SearchFilterList)
        # TODO: Revise sort assertion to work with new sort option definitions
        # self.assertEquals(context['search_sort_options'], ['Best Match', 'Last Update (Desc)', 'Last Update (Asc)', 'Name (Asc)', 'Name (Desc)'])
        self.assertEquals(context['search_sort'], '')
        self.assertEquals(context['search_facets_json'], None) 
Example #19
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 6 votes vote down vote up
def test_searchParamIsNoneAndResopnseCodeIs200_shouldReturnAllOrgCollections(self, mock_api_get):
        org_id = "org_id"
        # self.search_response.
        result = ['col1','col2','col3']
        response_mock  = MagicMock(spec=Response, status_code=200, headers={'content-type': "application/json"}
                                   , text=json.dumps({'status': True,"facets": {
                "dates": {},
                "fields": {},
                "queries": {}
            },"results": result
            }))
        response_mock.json.return_value = result
        mock_api_get.return_value = response_mock
        orgReadBaseView = views.OrganizationReadBaseView()
        orgReadBaseView.request = FakeRequest()

        searcher = orgReadBaseView.get_org_collections(org_id, search_params={'resourceFilter':'col'})
        self.assertEquals(searcher.search_results, result) 
Example #20
Source File: test_datastore_taxii.py    From cti-python-stix2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_object(self, id, **filter_kwargs):
        self._verify_can_read()
        query_params = _filter_kwargs_to_query_params(filter_kwargs)
        assert isinstance(query_params, dict)
        full_filter = BasicFilter(query_params)

        # In this endpoint we must first filter objects by id beforehand.
        objects = [x for x in self.objects if x["id"] == id]
        if objects:
            filtered_objects = full_filter.process_filter(
                objects,
                ("version",),
                self.manifests,
                100,
            )[0]
        else:
            filtered_objects = []
        if filtered_objects:
            return stix2.v20.Bundle(objects=filtered_objects)
        else:
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status() 
Example #21
Source File: test_datastore_taxii.py    From cti-python-stix2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_404():
    """a TAXIICollectionSource.get() call that receives an HTTP 404 response
    code from the taxii2client should be be returned as None.

    TAXII spec states that a TAXII server can return a 404 for nonexistent
    resources or lack of access. Decided that None is acceptable reponse
    to imply that state of the TAXII endpoint.
    """

    class TAXIICollection404():
        can_read = True

        def get_object(self, id, version=None):
            resp = Response()
            resp.status_code = 404
            resp.raise_for_status()

    ds = stix2.TAXIICollectionSource(TAXIICollection404())

    # this will raise 404 from mock TAXII Client but TAXIICollectionStore
    # should handle gracefully and return None
    stix_obj = ds.get("indicator--1")
    assert stix_obj is None 
Example #22
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 5 votes vote down vote up
def test_getContextForCol_contextForCollectionReceived(self, mock_get):
        colResponse = MagicMock(spec=Response)
        colResponse.json.return_value = "testCollection"
        mock_get.return_value = colResponse
        collectionDeleteView = views.CollectionDeleteView()
        collectionDeleteView.request = FakeRequest()
        collectionDeleteView.collection = {'id': 'mycolid'}
        collectionDeleteView.kwargs = {
            'collection_id': 'testColId',
        }
        context = collectionDeleteView.get_context_data();
        self.assertEquals(context['collection'], 'testCollection') 
Example #23
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 5 votes vote down vote up
def test_whenDeleteSuccessfull_thenReturnCollectionDeletedMessage(self, mock_delete, mock_message):
        colResponse = MagicMock(spec=Response, status_code=204)
        mock_delete.return_value = colResponse
        form = CollectionDeleteForm()
        collectionDeleteView = views.CollectionDeleteView()
        collectionDeleteView.request = FakeRequest()
        collectionDeleteView.kwargs = {
            'org': 'testOrgId',
        }

        result = collectionDeleteView.form_valid(form)
        mock_message.add_message.asser_called_with("error", "Error") 
Example #24
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 5 votes vote down vote up
def test_getContextForOrgCol_contextForOrgReceived(self, mock_get):
        colResponse = MagicMock(spec=Response)
        colResponse.json.return_value = "testOrg"
        mock_get.return_value = colResponse
        collectionEditView = views.CollectionEditView()
        collectionEditView.request = FakeRequest()
        collectionEditView.collection = {'id': 'mycolid'}
        collectionEditView.kwargs = {
            'org': 'testOrgId',
        }
        context = collectionEditView.get_context_data();
        self.assertEquals(context['org'], "testOrg")
        self.assertIsNone(context['ocl_user'])
        self.assertFalse(context['from_user'])
        self.assertTrue(context['from_org']) 
Example #25
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 5 votes vote down vote up
def test_getContextForUserCol_contextForUserReceived(self, mock_get):
        colResponse = MagicMock(spec=Response)
        colResponse.json.return_value = "testUser"
        mock_get.return_value = colResponse
        collectionEditView = views.CollectionEditView()
        collectionEditView.request = FakeRequest()
        collectionEditView.collection = {'id': 'mycolid'}
        collectionEditView.kwargs = {
            'user': 'testUserId',
        }
        context = collectionEditView.get_context_data();
        self.assertIsNone(context['org'])
        self.assertEquals(context['ocl_user'], "testUser")
        self.assertTrue(context['from_user'])
        self.assertFalse(context['from_org']) 
Example #26
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 5 votes vote down vote up
def test_getContextForOrgCol_contextForOrgReceived(self, mock_get):
        colResponse = MagicMock(spec=Response)
        colResponse.json.return_value = "testOrg"
        mock_get.return_value = colResponse
        collectionCreateView = views.CollectionCreateView()
        collectionCreateView.request = FakeRequest()
        collectionCreateView.kwargs = {
            'org': 'testOrgId',
        }
        context = collectionCreateView.get_context_data();
        self.assertEquals(context['org'], "testOrg")
        self.assertIsNone(context['ocl_user'])
        self.assertFalse(context['from_user'])
        self.assertTrue(context['from_org']) 
Example #27
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 5 votes vote down vote up
def test_whenRetireSuccessfull_thenReturnSourceDeletedMessage(self, mock_delete, mock_message):
        colResponse = MagicMock(spec=Response, status_code=204)
        mock_delete.return_value = colResponse
        form = MappingRetireForm()
        mappingRetireView = views.MappingRetireView()
        mappingRetireView.request = FakeRequest()
        mappingRetireView.kwargs = {
            'source_id': 'testSourceId',
            'mapping_id': 'testMapping_id'
        }
        form.cleaned_data={'comment':'updated'}
        mappingRetireView.form_valid(form)
        mock_message.assert_called_once_with(mappingRetireView.request, messages.INFO, ('Mapping retired')) 
Example #28
Source File: test_views.py    From ocl_web with Mozilla Public License 2.0 5 votes vote down vote up
def test_getContextForMapping_contextForMappingReceived(self, mock_get):
        colResponse = MagicMock(spec=Response)
        colResponse.json.return_value = "testMapping"
        mock_get.return_value = colResponse
        mappingRetireView = views.MappingRetireView()
        mappingRetireView.request = FakeRequest()
        mappingRetireView.kwargs = {
            'source_id': 'testSourceId',
            'mapping_id': 'testMapping_id'
        }
        context = mappingRetireView.get_context_data();
        self.assertEqual(context['mapping'], 'testMapping') 
Example #29
Source File: test_interface.py    From genieparser with Apache License 2.0 5 votes vote down vote up
def test_empty(self):
        empty_response = Mock(spec=Response)
        empty_response.json.return_value = {'response': []}
        empty_response.status_code = 200

        empty_output = {'get.return_value': empty_response}
        self.device1 = Mock(**empty_output)

        obj = Interface(device=self.device1)
        with self.assertRaises(SchemaEmptyParserError):
            obj.parse() 
Example #30
Source File: test_interface.py    From genieparser with Apache License 2.0 5 votes vote down vote up
def test_golden(self):
        golden_response = Mock(spec=Response)
        golden_response.json.side_effect = [self.golden_response_output1, self.golden_response_output2]
        golden_response.status_code = 200

        golden_output = {'get.return_value': golden_response}
        self.device = Mock(**golden_output)

        obj = Interface(device=self.device)
        parsed_output = obj.parse()
        self.assertEqual(parsed_output, self.golden_parsed_output)