2018-05-15 19:28:42 +02:00
|
|
|
# Set of helper functions to manipulate the OpenAPI files that define our REST
|
|
|
|
# API's specification.
|
|
|
|
import os
|
2019-07-08 14:08:02 +02:00
|
|
|
from typing import Any, Dict, List, Optional, Set
|
2018-05-15 19:28:42 +02:00
|
|
|
|
|
|
|
OPENAPI_SPEC_PATH = os.path.abspath(os.path.join(
|
|
|
|
os.path.dirname(__file__),
|
|
|
|
'../openapi/zulip.yaml'))
|
|
|
|
|
2018-06-20 19:31:24 +02:00
|
|
|
# A list of exceptions we allow when running validate_against_openapi_schema.
|
|
|
|
# The validator will ignore these keys when they appear in the "content"
|
|
|
|
# passed.
|
|
|
|
EXCLUDE_PROPERTIES = {
|
2018-06-20 23:03:01 +02:00
|
|
|
'/register': {
|
|
|
|
'post': {
|
|
|
|
'200': ['max_message_id', 'realm_emoji']
|
|
|
|
}
|
|
|
|
}
|
2018-06-20 19:31:24 +02:00
|
|
|
}
|
|
|
|
|
2018-08-07 23:40:07 +02:00
|
|
|
class OpenAPISpec():
|
|
|
|
def __init__(self, path: str) -> None:
|
|
|
|
self.path = path
|
2018-08-08 01:35:41 +02:00
|
|
|
self.last_update = None # type: Optional[float]
|
2019-07-29 02:11:44 +02:00
|
|
|
self.data = None # type: Optional[Dict[str, Any]]
|
2018-08-07 23:40:07 +02:00
|
|
|
|
|
|
|
def reload(self) -> None:
|
2018-08-08 22:33:49 +02:00
|
|
|
# Because importing yamole (and in turn, yaml) takes
|
|
|
|
# significant time, and we only use python-yaml for our API
|
|
|
|
# docs, importing it lazily here is a significant optimization
|
|
|
|
# to `manage.py` startup.
|
2018-09-07 01:30:19 +02:00
|
|
|
#
|
|
|
|
# There is a bit of a race here...we may have two processes
|
|
|
|
# accessing this module level object and both trying to
|
|
|
|
# populate self.data at the same time. Hopefully this will
|
|
|
|
# only cause some extra processing at startup and not data
|
|
|
|
# corruption.
|
2018-08-08 22:33:49 +02:00
|
|
|
from yamole import YamoleParser
|
2018-08-07 23:40:07 +02:00
|
|
|
with open(self.path) as f:
|
|
|
|
yaml_parser = YamoleParser(f)
|
2018-09-07 01:30:19 +02:00
|
|
|
|
2018-08-07 23:40:07 +02:00
|
|
|
self.data = yaml_parser.data
|
2018-09-07 01:30:19 +02:00
|
|
|
self.last_update = os.path.getmtime(self.path)
|
2018-08-07 23:40:07 +02:00
|
|
|
|
|
|
|
def spec(self) -> Dict[str, Any]:
|
|
|
|
"""Reload the OpenAPI file if it has been modified after the last time
|
|
|
|
it was read, and then return the parsed data.
|
|
|
|
"""
|
|
|
|
last_modified = os.path.getmtime(self.path)
|
|
|
|
# Using != rather than < to cover the corner case of users placing an
|
|
|
|
# earlier version than the current one
|
|
|
|
if self.last_update != last_modified:
|
|
|
|
self.reload()
|
2018-09-07 01:30:19 +02:00
|
|
|
assert(self.data)
|
2018-08-07 23:40:07 +02:00
|
|
|
return self.data
|
2018-06-20 19:31:24 +02:00
|
|
|
|
2018-05-31 19:41:17 +02:00
|
|
|
class SchemaError(Exception):
|
|
|
|
pass
|
2018-05-15 19:28:42 +02:00
|
|
|
|
2018-08-07 23:40:07 +02:00
|
|
|
openapi_spec = OpenAPISpec(OPENAPI_SPEC_PATH)
|
|
|
|
|
2018-05-15 19:28:42 +02:00
|
|
|
def get_openapi_fixture(endpoint: str, method: str,
|
|
|
|
response: Optional[str]='200') -> Dict[str, Any]:
|
2018-05-31 19:41:17 +02:00
|
|
|
"""Fetch a fixture from the full spec object.
|
|
|
|
"""
|
2018-08-07 23:40:07 +02:00
|
|
|
return (openapi_spec.spec()['paths'][endpoint][method.lower()]['responses']
|
2018-05-15 19:28:42 +02:00
|
|
|
[response]['content']['application/json']['schema']
|
|
|
|
['example'])
|
|
|
|
|
2019-07-08 14:08:02 +02:00
|
|
|
def get_openapi_paths() -> Set[str]:
|
|
|
|
return set(openapi_spec.spec()['paths'].keys())
|
|
|
|
|
2019-08-17 01:21:08 +02:00
|
|
|
def get_openapi_parameters(endpoint: str, method: str,
|
|
|
|
include_url_parameters: bool=True) -> List[Dict[str, Any]]:
|
2019-07-15 22:33:16 +02:00
|
|
|
openapi_endpoint = openapi_spec.spec()['paths'][endpoint][method.lower()]
|
|
|
|
# We do a `.get()` for this last bit to distinguish documented
|
|
|
|
# endpoints with no parameters (empty list) from undocumented
|
|
|
|
# endpoints (KeyError exception).
|
2019-08-17 01:21:08 +02:00
|
|
|
parameters = openapi_endpoint.get('parameters', [])
|
|
|
|
# Also, we skip parameters defined in the URL.
|
|
|
|
if not include_url_parameters:
|
|
|
|
parameters = [parameter for parameter in parameters if
|
|
|
|
parameter['in'] != 'path']
|
|
|
|
return parameters
|
2018-05-31 19:41:17 +02:00
|
|
|
|
|
|
|
def validate_against_openapi_schema(content: Dict[str, Any], endpoint: str,
|
2018-06-18 16:32:30 +02:00
|
|
|
method: str, response: str) -> None:
|
2018-05-31 19:41:17 +02:00
|
|
|
"""Compare a "content" dict with the defined schema for a specific method
|
|
|
|
in an endpoint.
|
|
|
|
"""
|
2018-08-07 23:40:07 +02:00
|
|
|
schema = (openapi_spec.spec()['paths'][endpoint][method.lower()]['responses']
|
2018-06-18 16:32:30 +02:00
|
|
|
[response]['content']['application/json']['schema'])
|
2018-05-31 19:41:17 +02:00
|
|
|
|
2018-06-20 19:31:24 +02:00
|
|
|
exclusion_list = (EXCLUDE_PROPERTIES.get(endpoint, {}).get(method, {})
|
|
|
|
.get(response, []))
|
|
|
|
|
2018-05-31 19:41:17 +02:00
|
|
|
for key, value in content.items():
|
2018-06-20 19:31:24 +02:00
|
|
|
# Ignore in the validation the keys in EXCLUDE_PROPERTIES
|
|
|
|
if key in exclusion_list:
|
|
|
|
continue
|
|
|
|
|
2018-05-31 19:41:17 +02:00
|
|
|
# Check that the key is defined in the schema
|
|
|
|
if key not in schema['properties']:
|
2018-06-18 16:47:20 +02:00
|
|
|
raise SchemaError('Extraneous key "{}" in the response\'s '
|
2018-05-31 19:41:17 +02:00
|
|
|
'content'.format(key))
|
|
|
|
|
|
|
|
# Check that the types match
|
|
|
|
expected_type = to_python_type(schema['properties'][key]['type'])
|
|
|
|
actual_type = type(value)
|
|
|
|
if expected_type is not actual_type:
|
|
|
|
raise SchemaError('Expected type {} for key "{}", but actually '
|
|
|
|
'got {}'.format(expected_type, key, actual_type))
|
|
|
|
|
|
|
|
# Check that at least all the required keys are present
|
|
|
|
for req_key in schema['required']:
|
|
|
|
if req_key not in content.keys():
|
|
|
|
raise SchemaError('Expected to find the "{}" required key')
|
|
|
|
|
|
|
|
def to_python_type(py_type: str) -> type:
|
|
|
|
"""Transform an OpenAPI-like type to a Pyton one.
|
|
|
|
https://swagger.io/docs/specification/data-models/data-types
|
|
|
|
"""
|
|
|
|
TYPES = {
|
|
|
|
'string': str,
|
|
|
|
'number': float,
|
|
|
|
'integer': int,
|
|
|
|
'boolean': bool,
|
|
|
|
'array': list,
|
|
|
|
'object': dict
|
|
|
|
}
|
|
|
|
|
|
|
|
return TYPES[py_type]
|