Python requests_mock.Adapter() Examples
The following are 30
code examples of requests_mock.Adapter().
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_mock
, or try the search function
.
Example #1
Source File: vxapi.py From VxAPI with GNU General Public License v3.0 | 7 votes |
def prepare_test_env(self): if is_test_env is True: adapter = requests_mock.Adapter() imported_scenarios = __import__('tests._requests_scenarios.{}'.format(os.environ['VX_TEST_SCENARIO']), fromlist=[None]) for scenario in imported_scenarios.scenarios: scenario['url'] = '{}/api/v2{}'.format(self.config['server'], scenario['url']) if 'headers' in scenario: if 'api-limits' in scenario['headers']: scenario['headers']['api-limits'] = json.dumps(scenario['headers']['api-limits']) if 'submission-limits' in scenario['headers']: scenario['headers']['submission-limits'] = json.dumps(scenario['headers']['submission-limits']) adapter.register_uri(**scenario) self.request_session.mount('mock', adapter)
Example #2
Source File: test_sessionmanager.py From pyrh with MIT License | 6 votes |
def sm_adap(monkeypatch): from pyrh.models import SessionManager sample_user = { "username": "user@example.com", "password": "some password", } monkeypatch.setattr("pyrh.urls.OAUTH", MOCK_URL) monkeypatch.setattr("pyrh.urls.OAUTH_REVOKE", MOCK_URL) monkeypatch.setattr("pyrh.urls.build_challenge", lambda x: MOCK_URL) session_manager = SessionManager(**sample_user) adapter = requests_mock.Adapter() session_manager.session.mount("mock", adapter) return session_manager, adapter
Example #3
Source File: test_socrata.py From sodapy with MIT License | 6 votes |
def test_get_all(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter) setup_mock(adapter, "GET", "bike_counts_page_1.json", 200, query="$offset=0") setup_mock(adapter, "GET", "bike_counts_page_2.json", 200, query="$offset=1000") response = client.get_all(DATASET_IDENTIFIER) assert inspect.isgenerator(response) data = list(response) assert len(data) == 1001 assert data[0]["date"] == "2016-09-21T15:45:00.000" assert data[-1]["date"] == "2016-10-02T01:45:00.000" client.close()
Example #4
Source File: resilient_rest_mock.py From resilient-python-api with MIT License | 6 votes |
def __init__(self, org_name=None, email=None): self.email = email or "api@example.com" self.org_name = org_name or "Test Org" LOG.info("Initialize ResilientMock %s %s", self.email, self.org_name) self.adapter = requests_mock.Adapter() for endpoint, handler in self.registered_endpoints.items(): # Register with regex since some endpoints embed the org_id in the path LOG.info("Registering %s %s to %s", endpoint.type, endpoint.uri, str(handler)) self.adapter.add_matcher(lambda request, method=endpoint.type, callback=handler, uri=endpoint.uri: self._custom_matcher(method, uri, lambda request: callback(self, request), request))
Example #5
Source File: test_digicert.py From lemur with Apache License 2.0 | 6 votes |
def test_cancel_ordered_certificate(mock_pending_cert): import requests_mock from lemur.plugins.lemur_digicert.plugin import DigiCertIssuerPlugin mock_pending_cert.external_id = 1234 subject = DigiCertIssuerPlugin() adapter = requests_mock.Adapter() adapter.register_uri( "PUT", "mock://www.digicert.com/services/v2/order/certificate/1234/status", status_code=204, ) adapter.register_uri( "PUT", "mock://www.digicert.com/services/v2/order/certificate/111/status", status_code=404, ) subject.session.mount("mock", adapter) data = {"note": "Test"} subject.cancel_ordered_certificate(mock_pending_cert, **data) # A non-existing order id, does not raise exception because if it doesn't exist, then it doesn't matter mock_pending_cert.external_id = 111 subject.cancel_ordered_certificate(mock_pending_cert, **data)
Example #6
Source File: test_socrata.py From sodapy with MIT License | 6 votes |
def test_get_unicode(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter) response_data = "get_songs_unicode.txt" setup_mock(adapter, "GET", response_data, 200) response = client.get(DATASET_IDENTIFIER) assert isinstance(response, list) assert len(response) == 10 client.close()
Example #7
Source File: test_compiler.py From pyquil with Apache License 2.0 | 6 votes |
def test_invalid_protocol(): device_name = "test_device" mock_url = "not-http-or-tcp://mock-qpu-compiler" config = PyquilConfig(TEST_CONFIG_PATHS) session = get_session(config=config) mock_adapter = requests_mock.Adapter() session.mount("", mock_adapter) device = Device( name="not_actually_device_name", raw={"device_name": device_name, "isa": DUMMY_ISA_DICT} ) with pytest.raises(UserMessageError): QPUCompiler( quilc_endpoint=session.config.quilc_url, qpu_compiler_endpoint=mock_url, device=device, session=session, )
Example #8
Source File: test_socrata.py From sodapy with MIT License | 6 votes |
def test_get_metadata_and_attachments(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter) response_data = "get_song_metadata.txt" setup_old_api_mock(adapter, "GET", response_data, 200) response = client.get_metadata(DATASET_IDENTIFIER) assert isinstance(response, dict) assert "newBackend" in response assert "attachments" in response["metadata"] response = client.download_attachments(DATASET_IDENTIFIER) assert isinstance(response, list) assert len(response) == 0 client.close()
Example #9
Source File: test_socrata.py From sodapy with MIT License | 6 votes |
def test_upsert_exception(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter) response_data = "403_response_json.txt" setup_mock(adapter, "POST", response_data, 403, reason="Forbidden") data = [ { "theme": "Surfing", "artist": "Wavves", "title": "King of the Beach", "year": "2010", } ] try: client.upsert(DATASET_IDENTIFIER, data) except Exception as e: assert isinstance(e, requests.exceptions.HTTPError) else: raise AssertionError("No exception raised for bad request.")
Example #10
Source File: test_base_connection.py From pyquil with Apache License 2.0 | 6 votes |
def test_forest_session_request_authenticated_with_user_token(): config = PyquilConfig(TEST_CONFIG_PATHS) config.config_parsers["QCS_CONFIG"].set( "Rigetti Forest", "qmi_auth_token_path", api_fixture_path("qmi_auth_token_invalid.json") ) config.config_parsers["QCS_CONFIG"].set( "Rigetti Forest", "user_auth_token_path", api_fixture_path("user_auth_token_valid.json") ) config.config_parsers["QCS_CONFIG"].set("Rigetti Forest", "url", "mock://forest") config._parse_auth_tokens() session = ForestSession(config=config) mock_adapter = requests_mock.Adapter() session.mount("mock", mock_adapter) url = "%s/devices" % config.forest_url headers = { # access token from ./data/user_auth_token_valid.json. "Authorization": "Bearer secret" } mock_adapter.register_uri("GET", url, status_code=200, json=[{"id": 0}], headers=headers) devices = session.get(url).json() assert len(devices) == 1 assert devices[0]["id"] == 0
Example #11
Source File: test_base_connection.py From pyquil with Apache License 2.0 | 6 votes |
def test_forest_session_request_authenticated_with_qmi_auth(): config = PyquilConfig(TEST_CONFIG_PATHS) config.config_parsers["QCS_CONFIG"].set( "Rigetti Forest", "qmi_auth_token_path", api_fixture_path("qmi_auth_token_valid.json") ) config.config_parsers["QCS_CONFIG"].set( "Rigetti Forest", "user_auth_token_path", api_fixture_path("user_auth_token_invalid.json") ) config.config_parsers["QCS_CONFIG"].set("Rigetti Forest", "url", "mock://forest") config._parse_auth_tokens() session = ForestSession(config=config) mock_adapter = requests_mock.Adapter() session.mount("mock", mock_adapter) url = "%s/devices" % config.forest_url headers = { # access token from ./data/qmi_auth_token_valid.json. "X-QMI-AUTH-TOKEN": "secret" } mock_adapter.register_uri("GET", url, status_code=200, json=[{"id": 0}], headers=headers) devices = session.get(url).json() assert len(devices) == 1 assert devices[0]["id"] == 0
Example #12
Source File: test_socrata.py From sodapy with MIT License | 6 votes |
def test_delete(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata( DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter, ) uri = "{}{}{}/{}.json".format(PREFIX, DOMAIN, OLD_API_PATH, DATASET_IDENTIFIER) adapter.register_uri("DELETE", uri, status_code=200) response = client.delete(DATASET_IDENTIFIER) assert response.status_code == 200 try: client.delete("foobar") except Exception as e: assert isinstance(e, requests_mock.exceptions.NoMockAddress) finally: client.close()
Example #13
Source File: test_socrata.py From sodapy with MIT License | 6 votes |
def test_publish(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata( DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter, ) response_data = "create_foobar.txt" setup_publish_mock(adapter, "POST", response_data, 200) response = client.publish(DATASET_IDENTIFIER) assert isinstance(response, dict) assert len(response.get("id")) == 9 client.close()
Example #14
Source File: test_socrata.py From sodapy with MIT License | 6 votes |
def test_import_non_data_file(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata( DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter, ) response_data = "successblobres.txt" nondatasetfile_path = "tests/test_data/nondatasetfile.zip" setup_import_non_data_file(adapter, "POST", response_data, 200) with open(nondatasetfile_path, "rb") as f: files = {"file": ("nondatasetfile.zip", f)} response = client.create_non_data_file({}, files) assert isinstance(response, dict) assert response.get("blobFileSize") == 496 client.close()
Example #15
Source File: test_socrata.py From sodapy with MIT License | 6 votes |
def test_replace_non_data_file(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata( DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter, ) response_data = "successblobres.txt" nondatasetfile_path = "tests/test_data/nondatasetfile.zip" setup_replace_non_data_file(adapter, "POST", response_data, 200) with open(nondatasetfile_path, "rb") as fin: file = {"file": ("nondatasetfile.zip", fin)} response = client.replace_non_data_file(DATASET_IDENTIFIER, {}, file) assert isinstance(response, dict) assert response.get("blobFileSize") == 496 client.close()
Example #16
Source File: test_sessionmanager.py From pyrh with MIT License | 6 votes |
def test_post(mock_login, sm): import json from requests.exceptions import HTTPError adapter = requests_mock.Adapter() sm.session.mount("mock", adapter) mock_url = "mock://test.com" expected = [ {"text": '{"error": "login error"}', "status_code": 401}, {"text": '{"test": "321"}', "status_code": 200}, {"text": '{"error": "resource not found"}', "status_code": 404}, ] adapter.register_uri("POST", mock_url, expected) resp1 = sm.post(mock_url) with pytest.raises(HTTPError) as e: sm.post(mock_url) assert resp1 == json.loads(expected[1]["text"]) assert mock_login.call_count == 1 assert "404 Client Error" in str(e.value)
Example #17
Source File: test_client.py From luno-python with MIT License | 6 votes |
def test_client_do_basic(): c = Client() c.set_base_url('mock://test/') adapter = requests_mock.Adapter() c.session.mount('mock', adapter) adapter.register_uri('GET', 'mock://test/', text='ok') with pytest.raises(Exception): res = c.do('GET', '/') adapter.register_uri('GET', 'mock://test/', text='{"key":"value"}') res = c.do('GET', '/') assert res['key'] == 'value' adapter.register_uri('GET', 'mock://test/', text='{}', status_code=400) res = c.do('GET', '/') # no exception, because no error present adapter.register_uri('GET', 'mock://test/', text='{"error_code":"code","error":"message"}', status_code=400) with pytest.raises(APIError) as e: res = c.do('GET', '/') assert e.value.code == 'code' assert e.value.message == 'message'
Example #18
Source File: test_token.py From postcard_creator_wrapper with Apache License 2.0 | 5 votes |
def create_token(): global adapter_token adapter_token = requests_mock.Adapter() Token._create_session = create_mocked_session return Token(_protocol='mock://')
Example #19
Source File: test_sessionmanager.py From pyrh with MIT License | 5 votes |
def test_get(mock_login, sm): import json from requests.exceptions import HTTPError adapter = requests_mock.Adapter() sm.session.mount("mock", adapter) mock_url = "mock://test.com" expected = [ {"text": '{"test": "123"}', "status_code": 200}, {"text": '{"error": "login error"}', "status_code": 401}, {"text": '{"test": "321"}', "status_code": 200}, {"text": '{"error": "resource not found"}', "status_code": 404}, ] adapter.register_uri("GET", mock_url, expected) resp1 = sm.get(mock_url) resp2 = sm.get(mock_url) with pytest.raises(HTTPError) as e: sm.get(mock_url) assert resp1 == json.loads(expected[0]["text"]) assert resp2 == json.loads(expected[2]["text"]) assert mock_login.call_count == 1 assert "404 Client Error" in str(e.value)
Example #20
Source File: test_socrata.py From sodapy with MIT License | 5 votes |
def test_get_datasets(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter) setup_datasets_mock(adapter, "get_datasets.txt", 200, params={"limit": "7"}) response = client.datasets(limit=7) assert isinstance(response, list) assert len(response) == 7
Example #21
Source File: test_token.py From postcard_creator_wrapper with Apache License 2.0 | 5 votes |
def create_postcard_creator(): global adapter_pcc adapter_pcc = requests_mock.Adapter() PostcardCreator._create_session = create_mocked_session token = create_token() token.token_expires_in = 3600 token.token_type = 'Bearer' token.token = 0 return PostcardCreator(token=token, _protocol='mock://')
Example #22
Source File: utils.py From MechanicalSoup with MIT License | 5 votes |
def prepare_mock_browser(scheme='mock'): mock = requests_mock.Adapter() browser = mechanicalsoup.StatefulBrowser(requests_adapters={scheme: mock}) return browser, mock
Example #23
Source File: test_socrata.py From sodapy with MIT License | 5 votes |
def test_get(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata(DOMAIN, APPTOKEN, session_adapter=mock_adapter) response_data = "get_songs.txt" setup_mock(adapter, "GET", response_data, 200) response = client.get(DATASET_IDENTIFIER) assert isinstance(response, list) assert len(response) == 10 client.close()
Example #24
Source File: test_kubehttpclient.py From controller with MIT License | 5 votes |
def setUp(self): self.adapter = requests_mock.Adapter() self.path = '/foo' self.url = settings.SCHEDULER_URL + self.path # use the real scheduler client. self.scheduler = scheduler.KubeHTTPClient(settings.SCHEDULER_URL) self.scheduler.session.mount(self.url, self.adapter)
Example #25
Source File: test_socrata.py From sodapy with MIT License | 5 votes |
def test_upsert(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata( DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter, ) response_data = "upsert_songs.txt" data = [ { "theme": "Surfing", "artist": "Wavves", "title": "King of the Beach", "year": "2010", } ] setup_mock(adapter, "POST", response_data, 200) response = client.upsert(DATASET_IDENTIFIER, data) assert isinstance(response, dict) assert response.get("Rows Created") == 1 client.close()
Example #26
Source File: test_socrata.py From sodapy with MIT License | 5 votes |
def test_replace(): mock_adapter = {} mock_adapter["prefix"] = PREFIX adapter = requests_mock.Adapter() mock_adapter["adapter"] = adapter client = Socrata( DOMAIN, APPTOKEN, username=USERNAME, password=PASSWORD, session_adapter=mock_adapter, ) response_data = "replace_songs.txt" data = [ { "theme": "Surfing", "artist": "Wavves", "title": "King of the Beach", "year": "2010", }, { "theme": "History", "artist": "Best Friends Forever", "title": "Abe Lincoln", "year": "2008", }, ] setup_mock(adapter, "PUT", response_data, 200) response = client.replace(DATASET_IDENTIFIER, data) assert isinstance(response, dict) assert response.get("Rows Created") == 2 client.close()
Example #27
Source File: conftest.py From confluent-kafka-python with Apache License 2.0 | 5 votes |
def __init__(self, conf): super(MockSchemaRegistryClient, self).__init__(conf) adapter = requests_mock.Adapter() adapter.register_uri('GET', self.compatibility, json=self.get_compatibility_callback) adapter.register_uri('PUT', self.compatibility, json=self.put_compatibility_callback) adapter.register_uri('GET', self.schemas, json=self.get_schemas_callback) adapter.register_uri('DELETE', self.subjects, json=self.delete_subject_callback) adapter.register_uri('GET', self.subjects, json=self.get_subject_callback) adapter.register_uri('POST', self.subjects, json=self.post_subject_callback) adapter.register_uri('GET', self.subject_versions, json=self.get_subject_version_callback) adapter.register_uri('DELETE', self.subject_versions, json=self.delete_subject_version_callback) adapter.register_uri('POST', self.subject_versions, json=self.post_subject_version_callback) adapter.add_matcher(self._auth_matcher) self._rest_client.session.mount('http://', adapter)
Example #28
Source File: 05_mocking.py From Python-Microservices-Development with MIT License | 5 votes |
def setUp(self): self.app = TestApp(app) # mocking the request calls session = get_connector(app) self.adapter = requests_mock.Adapter() session.mount('http://', self.adapter)
Example #29
Source File: test_commerce.py From gw2-api-interface with MIT License | 5 votes |
def mock_adapter(): """Creates a mock adapter instance. As this is a pytest fixture, tests only need to provide an argument with the name `mock_adapter` gain access to the mock adapter. Returns: A mock adapter. This exposes the register_uri function which can be used to mock requests. """ return requests_mock.Adapter()
Example #30
Source File: test_continents.py From gw2-api-interface with MIT License | 5 votes |
def mock_adapter(): """Creates a mock adapter instance. As this is a pytest fixture, tests only need to provide an argument with the name `mock_adapter` gain access to the mock adapter. Returns: A mock adapter. This exposes the register_uri function which can be used to mock requests. """ return requests_mock.Adapter()