Skip to content

Commit

Permalink
Use sys.exit for return codes and tidy up POST
Browse files Browse the repository at this point in the history
Co-authored-by: Casper Welzel Andersen <CasperWA@users.noreply.github.com>
  • Loading branch information
ml-evs and CasperWA committed Aug 31, 2020
1 parent 5b75926 commit 5695cb4
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 15 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/deps_lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ jobs:
- name: Pass generated OpenAPI schemas through validator.swagger.io
run: |
invoke run-swagger-validator openapi/openapi.json
invoke run-swagger-validator openapi/index_openapi.json
invoke swagger-validator openapi/openapi.json
invoke swagger-validator openapi/index_openapi.json
- name: Check OpenAPI Schemas have not changed
run: invoke check-openapi-diff
Expand Down
1 change: 0 additions & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
pytest==6.0.1
pytest-cov==2.10.1
codecov==2.1.9
openapi-spec-validator==0.2.9
jsondiff==1.2.0
pylint==2.6.0
black==20.8b1
Expand Down
25 changes: 13 additions & 12 deletions tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,36 +297,37 @@ def write_file(full_path: Path, content: str):
)


@task(help={"filename": "The JSON file containing the OpenAPI schema to validate"})
def run_swagger_validator(_, fname):
@task(help={"fname": "The JSON file containing the OpenAPI schema to validate"})
def swagger_validator(_, fname):
"""This task can be used in the CI to test the generated OpenAPI schemas
with the online swagger validator.
Returns:
non-zero exit code if validation fails, otherwise returns 0.
Non-zero exit code if validation fails, otherwise returns `0`.
"""

import requests

def print_error(string):
print(f"\033[31m{string}\033[0m")

swagger_url = "https://validator.swagger.io/validator/debug"
with open(fname, "r") as f:
schema = json.load(f)
response = requests.post(swagger_url, json=schema)

if response.status_code != 200:
raise RuntimeError(f"Server returned status code {response.status_code}.")
print_error(f"Server returned status code {response.status_code}.")
sys.exit(1)

try:
json_response = response.json()
except json.JSONDecodeError:
raise json.JSONDecodeError(
f"Unable to parse validator response as JSON: {response}"
)(response.json().get("messages", "Failed to get error messages from response"))
print_error(f"Unable to parse validator response as JSON: {response}")
sys.exit(1)

if len(json_response) > 0:
raise RuntimeError(
response.json().get(
"messages", "Failed to get error messages from response"
)
)
print_error(f"Schema file {fname} did not pass validation.\n")
print_error(json.dumps(response.json(), indent=2))
sys.exit(1)

0 comments on commit 5695cb4

Please sign in to comment.