Skip to content

On validation error: add cause and context. #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion openapi_spec_validator/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import argparse
import sys

from jsonschema.exceptions import best_match

from openapi_spec_validator import (
openapi_v2_spec_validator, openapi_v3_spec_validator,
)
Expand All @@ -15,9 +17,37 @@
)


def print_validationerror(exc, errors="best-match"):
print("# Validation Error\n")
print(exc)
if exc.cause:
print("\n# Cause\n")
print(exc.cause)
if not exc.context:
return
if errors == "all":
print("\n\n# Due to one of those errors\n")
print("\n\n\n".join("## " + str(e) for e in exc.context))
elif errors == "best-match":
print("\n\n# Probably due to this subschema error\n")
print("## " + str(best_match(exc.context)))
if len(exc.context) > 1:
print(
"\n({} more subschemas errors,".format(len(exc.context) - 1),
"use --errors=all to see them.)",
)


def main(args=None):
parser = argparse.ArgumentParser()
parser.add_argument('filename', help="Absolute or relative path to file")
parser.add_argument(
"--errors",
choices=("best-match", "all"),
default="best-match",
help="""Control error reporting. Defaults to "best-match", """
"""use "all" to get all subschema errors.""",
)
parser.add_argument(
'--schema',
help="OpenAPI schema (default: 3.0.0)",
Expand Down Expand Up @@ -50,7 +80,7 @@ def main(args=None):
try:
validator.validate(spec, spec_url=spec_url)
except ValidationError as exc:
print(exc)
print_validationerror(exc, args.errors)
sys.exit(1)
except Exception as exc:
print(exc)
Expand Down
18 changes: 18 additions & 0 deletions tests/integration/data/v3.0/missing-description.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
openapi: 3.0.0

info:
title: test
description: test
version: 0.0.1

paths:
"/":
get:
description: Get the API root
responses:
200:
content:
application/json:
schema:
type: string
27 changes: 27 additions & 0 deletions tests/integration/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,33 @@ def test_schema_v2():
main(testargs)


def test_errors_on_missing_description_best(capsys):
"""An error is obviously printed given an empty schema."""
testargs = ['./tests/integration/data/v3.0/missing-description.yaml']
with pytest.raises(SystemExit):
main(testargs)
out, err = capsys.readouterr()
assert "Failed validating" in out
assert "'description' is a required property" in out
assert "'$ref' is a required property" not in out
assert '1 more subschemas errors' in out


def test_errors_on_missing_description_full(capsys):
"""An error is obviously printed given an empty schema."""
testargs = [
"./tests/integration/data/v3.0/missing-description.yaml",
"--errors=all"
]
with pytest.raises(SystemExit):
main(testargs)
out, err = capsys.readouterr()
assert "Failed validating" in out
assert "'description' is a required property" in out
assert "'$ref' is a required property" in out
assert '1 more subschema error' not in out


def test_schema_unknown():
"""Errors on running with unknown schema."""
testargs = ['--schema', 'x.x',
Expand Down