本文整理汇总了Python中requests_mock.Adapter方法的典型用法代码示例。如果您正苦于以下问题:Python requests_mock.Adapter方法的具体用法?Python requests_mock.Adapter怎么用?Python requests_mock.Adapter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests_mock
的用法示例。
在下文中一共展示了requests_mock.Adapter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prepare_test_env
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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)
示例2: test_client_do_basic
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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'
示例3: test_cancel_ordered_certificate
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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)
示例4: __init__
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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))
示例5: test_invalid_protocol
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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,
)
示例6: test_forest_session_request_authenticated_with_user_token
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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
示例7: test_forest_session_request_authenticated_with_qmi_auth
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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
示例8: sm_adap
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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
示例9: test_post
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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)
示例10: test_get_all
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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()
示例11: test_get_unicode
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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()
示例12: test_get_metadata_and_attachments
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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()
示例13: test_upsert_exception
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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.")
示例14: test_delete
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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()
示例15: test_publish
# 需要导入模块: import requests_mock [as 别名]
# 或者: from requests_mock import Adapter [as 别名]
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()