|
2 | 2 | import argparse |
3 | 3 | import sys |
4 | 4 |
|
| 5 | +from jsonschema.exceptions import best_match |
| 6 | + |
5 | 7 | from openapi_spec_validator import ( |
6 | 8 | openapi_v2_spec_validator, openapi_v3_spec_validator, |
7 | 9 | ) |
|
15 | 17 | ) |
16 | 18 |
|
17 | 19 |
|
| 20 | +def print_validationerror(exc, errors="best-match"): |
| 21 | + print("# Validation Error\n") |
| 22 | + print(exc) |
| 23 | + if exc.cause: |
| 24 | + print("\n# Cause\n") |
| 25 | + print(exc.cause) |
| 26 | + if not exc.context: |
| 27 | + return |
| 28 | + if errors == "all": |
| 29 | + print("\n\n# Due to one of those errors\n") |
| 30 | + print("\n\n\n".join("## " + str(e) for e in exc.context)) |
| 31 | + elif errors == "best-match": |
| 32 | + print("\n\n# Probably due to this subschema error\n") |
| 33 | + print("## " + str(best_match(exc.context))) |
| 34 | + if len(exc.context) > 1: |
| 35 | + print( |
| 36 | + "\n({} more subschemas errors,".format(len(exc.context) - 1), |
| 37 | + "use --errors=all to see them.)", |
| 38 | + ) |
| 39 | + |
| 40 | + |
18 | 41 | def main(args=None): |
19 | 42 | parser = argparse.ArgumentParser() |
20 | 43 | parser.add_argument('filename', help="Absolute or relative path to file") |
| 44 | + parser.add_argument( |
| 45 | + "--errors", |
| 46 | + choices=("best-match", "all"), |
| 47 | + default="best-match", |
| 48 | + help="""Control error reporting. Defaults to "best-match", """ |
| 49 | + """use "all" to get all subschema errors.""", |
| 50 | + ) |
21 | 51 | parser.add_argument( |
22 | 52 | '--schema', |
23 | 53 | help="OpenAPI schema (default: 3.0.0)", |
@@ -50,7 +80,7 @@ def main(args=None): |
50 | 80 | try: |
51 | 81 | validator.validate(spec, spec_url=spec_url) |
52 | 82 | except ValidationError as exc: |
53 | | - print(exc) |
| 83 | + print_validationerror(exc, args.errors) |
54 | 84 | sys.exit(1) |
55 | 85 | except Exception as exc: |
56 | 86 | print(exc) |
|
0 commit comments