本文整理汇总了Python中httmock.urlmatch方法的典型用法代码示例。如果您正苦于以下问题:Python httmock.urlmatch方法的具体用法?Python httmock.urlmatch怎么用?Python httmock.urlmatch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类httmock
的用法示例。
在下文中一共展示了httmock.urlmatch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_iter_tag_users
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [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)
示例2: test_process_single_event
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [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)
示例3: test_supply_jwks
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [as 别名]
def test_supply_jwks(self):
rsa_key = PublicKey.RSA.generate(2048)
jwks = jwk.KEYS()
jwks.wrap_add(rsa_key)
scheme = u"https"
issuer = u"issuer.com"
self._key_uri_supplier.supply.return_value = scheme + u"://" + issuer
@httmock.urlmatch(scheme=scheme, netloc=issuer)
def _mock_response_with_jwks(url, response): # pylint: disable=unused-argument
return jwks.dump_jwks()
with httmock.HTTMock(_mock_response_with_jwks):
actual_jwks = self._jwks_uri_supplier.supply(issuer)
self.assertEquals(1, len(actual_jwks))
actual_key = actual_jwks[0].key
self.assertEquals(rsa_key.n, actual_key.n)
self.assertEquals(rsa_key.e, actual_key.e)
示例4: mock_response
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [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)
示例5: test_get_qe_deployments
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [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]
示例6: test_cycle_qe_deployments
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [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)
示例7: test_validate_bitbucket_trigger
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [as 别名]
def test_validate_bitbucket_trigger(app):
url_hit = [False]
@urlmatch(netloc=r"bitbucket.org")
def handler(url, request):
url_hit[0] = True
return {
"status_code": 200,
"content": "oauth_token=foo&oauth_token_secret=bar",
}
with HTTMock(handler):
validator = BitbucketTriggerValidator()
url_scheme_and_hostname = URLSchemeAndHostname("http", "localhost:5000")
unvalidated_config = ValidatorContext(
{"BITBUCKET_TRIGGER_CONFIG": {"CONSUMER_KEY": "foo", "CONSUMER_SECRET": "bar",},},
url_scheme_and_hostname=url_scheme_and_hostname,
)
validator.validate(unvalidated_config)
assert url_hit[0]
示例8: test_validate_elasticsearch
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [as 别名]
def test_validate_elasticsearch(unvalidated_config, expected, app):
validator = ElasticsearchValidator()
path = unvalidated_config.get("index_prefix") or INDEX_NAME_PREFIX
path = "/" + path + "*"
unvalidated_config = ValidatorContext(unvalidated_config)
@urlmatch(netloc=r"", path=path)
def handler(url, request):
return {"status_code": 200, "content": b"{}"}
with HTTMock(handler):
if expected is not None:
with pytest.raises(expected):
validator.validate(unvalidated_config)
else:
validator.validate(unvalidated_config)
示例9: test_validate_google_login
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [as 别名]
def test_validate_google_login(app):
url_hit = [False]
@urlmatch(netloc=r"www.googleapis.com", path="/oauth2/v3/token")
def handler(_, __):
url_hit[0] = True
return {"status_code": 200, "content": ""}
validator = GoogleLoginValidator()
with HTTMock(handler):
unvalidated_config = ValidatorContext(
{"GOOGLE_LOGIN_CONFIG": {"CLIENT_ID": "foo", "CLIENT_SECRET": "bar",},}
)
unvalidated_config.http_client = build_requests_session()
validator.validate(unvalidated_config)
assert url_hit[0]
示例10: test_google_oauth
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [as 别名]
def test_google_oauth(self):
@urlmatch(netloc=r"accounts.google.com", path="/o/oauth2/token")
def account_handler(_, request):
parsed = dict(urllib.parse.parse_qsl(request.body))
if parsed["code"] == "somecode":
content = {"access_token": "someaccesstoken"}
return py_json.dumps(content)
else:
return {"status_code": 400, "content": '{"message": "Invalid code"}'}
@urlmatch(netloc=r"www.googleapis.com", path="/oauth2/v1/userinfo")
def user_handler(_, __):
content = {
"id": "someid",
"email": "someemail@example.com",
"verified_email": True,
}
return py_json.dumps(content)
with HTTMock(account_handler, user_handler):
self.invoke_oauth_tests(
"google_oauth_callback", "google_oauth_attach", "google", "someid", "someemail"
)
示例11: test_github_oauth
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [as 别名]
def test_github_oauth(self):
@urlmatch(netloc=r"github.com", path="/login/oauth/access_token")
def account_handler(url, _):
parsed = dict(urllib.parse.parse_qsl(url.query))
if parsed["code"] == "somecode":
content = {"access_token": "someaccesstoken"}
return py_json.dumps(content)
else:
return {"status_code": 400, "content": '{"message": "Invalid code"}'}
@urlmatch(netloc=r"github.com", path="/api/v3/user")
def user_handler(_, __):
content = {"id": "someid", "login": "someusername"}
return py_json.dumps(content)
@urlmatch(netloc=r"github.com", path="/api/v3/user/emails")
def email_handler(_, __):
content = [{"email": "someemail@example.com", "verified": True, "primary": True,}]
return py_json.dumps(content)
with HTTMock(account_handler, email_handler, user_handler):
self.invoke_oauth_tests(
"github_oauth_callback", "github_oauth_attach", "github", "someid", "someusername"
)
示例12: gen_mock_api
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [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
示例13: gen_pb_mock_api
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [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
示例14: test_post_results
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [as 别名]
def test_post_results(self):
"""
Test the post_results method, ensuring a requests call is made.
"""
args = rc.parse_cli_args(self.mock_argv())
client = rc.RefstackClient(args)
client.logger.info = MagicMock()
content = {'duration_seconds': 0,
'cpid': 'test-id',
'results': [{'name': 'tempest.passed.test', 'uid': None}]}
expected_response = json.dumps({'test_id': 42})
@httmock.urlmatch(netloc=r'(.*\.)?127.0.0.1$', path='/v1/results/')
def refstack_api_mock(url, request):
return expected_response
with httmock.HTTMock(refstack_api_mock):
client.post_results("http://127.0.0.1", content)
client.logger.info.assert_called_with(
'http://127.0.0.1/v1/results/ Response: '
'%s' % expected_response)
示例15: test_post_results_with_sign
# 需要导入模块: import httmock [as 别名]
# 或者: from httmock import urlmatch [as 别名]
def test_post_results_with_sign(self):
"""
Test the post_results method, ensuring a requests call is made.
"""
argv = self.mock_argv(command='upload', priv_key='rsa_key')
argv.append('fake.json')
args = rc.parse_cli_args(argv)
client = rc.RefstackClient(args)
client.logger.info = MagicMock()
content = {'duration_seconds': 0,
'cpid': 'test-id',
'results': [{'name': 'tempest.passed.test'}]}
expected_response = json.dumps({'test_id': 42})
@httmock.urlmatch(netloc=r'(.*\.)?127.0.0.1$', path='/v1/results/')
def refstack_api_mock(url, request):
return expected_response
with httmock.HTTMock(refstack_api_mock):
rsapath = os.path.join(self.test_path, 'rsa_key')
client.post_results("http://127.0.0.1", content, sign_with=rsapath)
client.logger.info.assert_called_with(
'http://127.0.0.1/v1/results/ Response: %s' %
expected_response)