本文整理汇总了Python中httmock.response方法的典型用法代码示例。如果您正苦于以下问题:Python httmock.response方法的具体用法?Python httmock.response怎么用?Python httmock.response使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类httmock
的用法示例。
在下文中一共展示了httmock.response方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wechat_api_mock
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def wechat_api_mock(url, request):
path = url.path.replace("/cgi-bin/", "").replace("/", "_")
if path.startswith("_"):
path = path[1:]
res_file = os.path.join(_FIXTURE_PATH, f"{path}.json")
content = {
"errcode": 99999,
"errmsg": f"can not find fixture {res_file}",
}
headers = {"Content-Type": "application/json"}
try:
with open(res_file, "rb") as f:
content = json.loads(f.read().decode("utf-8"))
except (IOError, ValueError) as e:
print(e)
return response(200, content, headers, request=request)
示例2: wechat_api_mock
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def wechat_api_mock(url, request):
path = (url.path[1:] if url.path.startswith("/") else url.path).replace("/", "_")
res_file = os.path.join(_FIXTURE_PATH, f"{path}.json")
content = {
"errcode": 99999,
"errmsg": f"can not find fixture {res_file}",
}
headers = {"Content-Type": "application/json"}
try:
with open(res_file, "rb") as f:
content = json.loads(f.read().decode("utf-8"))
except (IOError, ValueError):
pass
content_sign = content.pop("sign", "")
content_xml = dict_to_xml(content, content_sign)
return response(200, content_xml, headers, request=request)
示例3: wechat_api_mock
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def wechat_api_mock(url, request):
path = url.path.replace("/cgi-bin/", "").replace("/", "_")
if path.startswith("_"):
path = path[1:]
res_file = os.path.join(_FIXTURE_PATH, f"{path}.json")
content = {
"errcode": 99999,
"errmsg": f"can not find fixture {res_file}",
}
headers = {"Content-Type": "application/json"}
try:
with open(res_file, "rb") as f:
content = json.loads(f.read().decode("utf-8"))
except (IOError, ValueError) as e:
content["errmsg"] = f"Loads fixture {res_file} failed, error: {e}"
return response(200, content, headers, request=request)
示例4: test_iter_tag_users
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def test_iter_tag_users(self):
@urlmatch(netloc=r"(.*\.)?api\.weixin\.qq\.com$", path=r".*user/tag/get")
def next_openid_mock(url, request):
"""伪造第二页的请求"""
data = json.loads(request.body.decode())
if not data.get("next_openid"):
return wechat_api_mock(url, request)
# 根据拿到的第二页请求响应 是没有data和next_openid的
content = {"count": 0}
headers = {"Content-Type": "application/json"}
return response(200, content, headers, request=request)
with HTTMock(next_openid_mock, wechat_api_mock):
users = list(self.client.tag.iter_tag_users(101))
self.assertEqual(2, len(users))
self.assertIn("OPENID1", users)
self.assertIn("OPENID2", users)
示例5: test_process_single_event
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def test_process_single_event(self):
from main import process_single_event
from httmock import response, HTTMock, urlmatch
@urlmatch(netloc=r'(api.nexmo.com|yunpian.com)')
def response_content(url, request):
print(url)
headers = {'Content-Type': 'application/json'}
if url.netloc == 'api.nexmo.com':
return response(200, '{}', headers)
elif url.netloc == 'yunpian.com':
return response(200, '{"code": 0}', headers)
else:
raise Exception('Meh!')
with HTTMock(response_content):
process_single_event(alarm_example)
示例6: foxfour_esi
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def foxfour_esi(url, request):
resp = {
"killmail_id": 30290604,
"killmail_time": "2013-05-05T18:09:00Z",
"victim": {
"damage_taken": 570,
"ship_type_id": 670,
"character_id": 92168909,
"corporation_id": 109299958,
"alliance_id": 434243723,
},
# Skipping the items array as it's not used
"items": None,
# Ditto for attackers
"attackers": None,
"solar_system_id": 30002062
}
return response(content=json.dumps(resp))
示例7: mock_response
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def mock_response(
content, url=None, path='', headers=None, response_url=None, status_code=200, cookies=None, func=None
):
"""Universal handler for specify mocks inplace"""
if func is None:
def mocked(url, request):
mock = response(
status_code=status_code, content=content, request=request, headers=headers
)
if cookies:
mock.cookies = cookies
mock.url = response_url if response_url else url
return mock
else:
mocked = func
if url:
parsed = urlparse(url)
return urlmatch(netloc=parsed.netloc, path=parsed.path)(func=mocked)
elif path:
return urlmatch(path=path)(func=mocked)
else:
return all_requests(func=mocked)
示例8: test_cache_hit
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def test_cache_hit(self):
@httmock.all_requests
def prime_cache(url, request):
headers = {'content-type': 'application/json',
'Cache-Control': 'max-age=300;'}
return httmock.response(200, '{}'.encode('utf-8'), headers)
with httmock.HTTMock(prime_cache):
self.assertEqual(self.api()._dict, {})
@httmock.all_requests
def cached_request(url, request):
raise RuntimeError(
'A cached request should never yield a HTTP request')
with httmock.HTTMock(cached_request):
self.api._data = None
self.assertEqual(self.api()._dict, {})
示例9: test_cache_invalidate
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def test_cache_invalidate(self):
@httmock.all_requests
def prime_cache(url, request):
headers = {'content-type': 'application/json',
'Cache-Control': 'max-age=300;'}
return httmock.response(
200, '{"cached": true}'.encode('utf-8'), headers)
# Prime cache and force the expiration
with httmock.HTTMock(prime_cache):
self.api()
# Nuke _data so the .get() is actually being called the next call
self.api._data = None
for key in self.api.cache._dict:
# Make sure the cache is concidered 'expired'
self.api.cache._dict[key]['expires'] = 0
@httmock.all_requests
def expired_request(url, request):
self.assertTrue(isinstance(request, PreparedRequest))
return httmock.response(200, '{}'.encode('utf-8'))
with httmock.HTTMock(expired_request):
self.api()
示例10: test_get_qe_deployments
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def test_get_qe_deployments(kube_config, expected_api, expected_query):
config = KubernetesConfig(**kube_config)
url_hit = [False]
@urlmatch(netloc=r"www.customhost.com")
def handler(request, _):
assert request.path == expected_api
assert request.query == expected_query
url_hit[0] = True
return response(200, "{}")
with HTTMock(handler):
KubernetesAccessorSingleton._instance = None
assert KubernetesAccessorSingleton.get_instance(config).get_qe_deployments() is not None
assert url_hit[0]
示例11: test_cycle_qe_deployments
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def test_cycle_qe_deployments(kube_config, deployment_names, expected_api_hits):
KubernetesAccessorSingleton._instance = None
config = KubernetesConfig(**kube_config)
url_hit = [False] * len(expected_api_hits)
i = [0]
@urlmatch(netloc=r"www.customhost.com", method="PATCH")
def handler(request, _):
assert request.path == expected_api_hits[i[0]]
url_hit[i[0]] = True
i[0] += 1
return response(200, "{}")
with HTTMock(handler):
KubernetesAccessorSingleton.get_instance(config).cycle_qe_deployments(deployment_names)
assert all(url_hit)
示例12: wechat_api_mock
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def wechat_api_mock(url, request):
path = url.path.replace('/cgi-bin/', '').replace('/', '_')
if path.startswith('_'):
path = path[1:]
res_file = os.path.join(FIXTURE_PATH, '%s.json' % path)
content = {
'errcode': 99999,
'errmsg': 'can not find fixture %s' % res_file,
}
headers = {
'Content-Type': 'application/json'
}
try:
with open(res_file, 'rb') as f:
content = json.loads(f.read().decode('utf-8'))
except (IOError, ValueError) as e:
print(e)
return response(200, content, headers, request=request)
示例13: api_weixin_mock
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def api_weixin_mock(url, request):
path = url.path.replace('/cgi-bin/', '').replace('/', '_')
if path.startswith('_'):
path = path[1:]
res_file = os.path.join(FIXTURE_PATH, '%s.json' % path)
content = {
'errcode': 99999,
'errmsg': 'can not find fixture %s' % res_file,
}
headers = {
'Content-Type': 'application/json'
}
try:
with open(res_file, 'rb') as f:
content = json.loads(f.read().decode('utf-8'))
except (IOError, ValueError) as e:
print(e)
return response(200, content, headers, request=request)
示例14: gen_mock_api
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def gen_mock_api(check):
@urlmatch(netloc=r'(.*\.)?endpoint')
def datahub_api_mock(url, request):
check(request)
path = url.path.replace('/', '.')[1:]
res_file = os.path.join(_FIXTURE_PATH, '%s.json' % path)
status_code = 200
content = {
}
headers = {
'Content-Type': 'application/json',
'x-datahub-request-id': 0
}
try:
with open(res_file, 'rb') as f:
content = json.loads(f.read().decode('utf-8'))
if 'ErrorCode' in content:
status_code = 500
except (IOError, ValueError) as e:
content['ErrorMessage'] = 'Loads fixture %s failed, error: %s' % (res_file, e)
return response(status_code, content, headers, request=request)
return datahub_api_mock
示例15: gen_pb_mock_api
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import response [as 别名]
def gen_pb_mock_api(check):
@urlmatch(netloc=r'(.*\.)?endpoint')
def datahub_pb_api_mock(url, request):
check(request)
path = url.path.replace('/', '.')[1:]
res_file = os.path.join(_FIXTURE_PATH, '%s.bin' % path)
status_code = 200
content = {
}
headers = {
'Content-Type': 'application/x-protobuf',
'x-datahub-request-id': 0
}
try:
with open(res_file, 'rb') as f:
content = f.read()
except (IOError, InvalidParameterException) as e:
content['ErrorMessage'] = 'Loads fixture %s failed, error: %s' % (res_file, e)
return response(status_code, content, headers, request=request)
return datahub_pb_api_mock