def add_mocks_to_method(self, resource_method):
"""Resource method decorator which supplies a mock
response if a client specifies `mock=True`.
Please see `osp_api.mocks`. A naming convention is used
to automatically find and use the appropriate mock as a
response.
Warning:
Mocks bypass any authentication (and possibly
other decorators, too!).
"""
resource_class_name, resource_type = self.resource_method_info(
resource_method,
)
if resource_type == ResourceType.collection:
index_before_suffix = -10
mock_suffix = '_collection'
elif resource_type == ResourceType.singleton:
index_before_suffix = -9
mock_suffix = '_singleton'
# Get the "resource name," e.g., "TopWorksCollection" becomes
# "top-works_collection."
resource_name = ''
for i, letter in enumerate(resource_class_name[:index_before_suffix]):
if i == 0:
resource_name += letter.lower()
elif letter.isupper():
resource_name += '-' + letter.lower()
else:
resource_name += letter
http_method = resource_method.__name__
mock_name = resource_name + mock_suffix + '_' + http_method
@wraps(resource_method)
def wrapped_resource_method(*args, **kwargs):
"""Replace the existing method with this one."""
if bool(flask.request.args.get('mock')):
mock_response = utils.load_json_mock(mock_name)
return mock_response
else:
return resource_method(*args, **kwargs)
return wrapped_resource_method
# FIXME: eventually this will be redone to tell ElasticSearch to use
# an index consisting of records a year of age or older. The age is
# measured by class year (when it was taught in a syllabus) and NOT
# simply when it was added to our database.
评论列表
文章目录