Skip to content

Fix issue #669 and add test case. #721

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 13 commits into from
Oct 15, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
23 changes: 21 additions & 2 deletions jsonschema/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import argparse
import errno
import json
import os
import sys
import traceback

Expand All @@ -15,7 +16,7 @@
from jsonschema import __version__
from jsonschema._reflect import namedAny
from jsonschema.exceptions import SchemaError
from jsonschema.validators import validator_for
from jsonschema.validators import validator_for, RefResolver


class _CannotLoadFile(Exception):
Expand Down Expand Up @@ -178,6 +179,15 @@ def _namedAnyWithDefault(name):
of the class.
""",
)
parser.add_argument(
"--base-uri",
action="store_true",
help="""
use this option to indicate that the schema contains some references
to some local files. With this option, the validator will try to
resolve those references as paths relative to the given schema.
""",
)
parser.add_argument(
"--version",
action="version",
Expand Down Expand Up @@ -251,7 +261,16 @@ def load(_):
raise _CannotLoadFile()
instances = ["<stdin>"]

validator = arguments["validator"](schema)
if arguments["base_uri"]:
file_prefix = "file:///{}/" if "nt" == os.name else "file://{}/"
schema_dirname = os.path.dirname(arguments["schema"])
resolver = RefResolver(
base_uri=file_prefix.format(os.path.abspath(schema_dirname)),
referrer=schema,
)
else:
resolver = None
validator = arguments["validator"](schema, resolver=resolver)
exit_code = 0
for each in instances:
try:
Expand Down
17 changes: 17 additions & 0 deletions jsonschema/tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -683,6 +683,23 @@ def test_successful_validation__of_just_the_schema_pretty_output(self):
stderr="",
)

def test_successful_validation_with_specifying_base_uri(self):
schema = """\
{"type": "object", "properties": {"KEY1":
{"$ref": "schema.json#definitions/schemas"}},
"definitions": {"schemas": {"type": "string"}}}
"""
fp = open("schema.json", "w+")
fp.write(schema)
fp.close()
self.assertOutputs(
files=dict(some_schema=schema, some_instance='{"KEY1": "1"}'),
argv=["-i", "some_instance", "--base-uri", "some_schema"],
stdout="",
stderr="",
)
os.remove("schema.json")

def test_real_validator(self):
self.assertOutputs(
files=dict(some_schema='{"minimum": 30}', some_instance="37"),
Expand Down