Skip to content

Commit

Permalink
Enable the rest of the rulesets we care about and fix minor things.
Browse files Browse the repository at this point in the history
  • Loading branch information
Julian committed Jan 6, 2024
1 parent 03ec8d2 commit 0ce7200
Show file tree
Hide file tree
Showing 18 changed files with 120 additions and 116 deletions.
9 changes: 3 additions & 6 deletions jsonschema/_format.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from __future__ import annotations

from contextlib import suppress
from datetime import date, datetime
from uuid import UUID
import datetime
import ipaddress
import re
import typing
Expand Down Expand Up @@ -398,17 +398,14 @@ def is_regex(instance: object) -> bool:
def is_date(instance: object) -> bool:
if not isinstance(instance, str):
return True
return bool(
_RE_DATE.fullmatch(instance)
and datetime.date.fromisoformat(instance)
)
return bool(_RE_DATE.fullmatch(instance) and date.fromisoformat(instance))


@_checks_drafts(draft3="time", raises=ValueError)
def is_draft3_time(instance: object) -> bool:
if not isinstance(instance, str):
return True
return bool(datetime.datetime.strptime(instance, "%H:%M:%S"))
return bool(datetime.strptime(instance, "%H:%M:%S")) # noqa: DTZ007


with suppress(ImportError):
Expand Down
2 changes: 1 addition & 1 deletion jsonschema/_keywords.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ def unevaluatedProperties(validator, unevaluatedProperties, instance, schema):
):
# FIXME: Include context for each unevaluated property
# indicating why it's invalid under the subschema.
unevaluated_keys.append(property)
unevaluated_keys.append(property) # noqa: PERF401

if unevaluated_keys:
if unevaluatedProperties is False:
Expand Down
51 changes: 24 additions & 27 deletions jsonschema/_legacy_keywords.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,20 +202,19 @@ def type_draft3(validator, types, instance, schema):
if not errors:
return
all_errors.extend(errors)
else:
if validator.is_type(instance, type):
elif validator.is_type(instance, type):
return
else:
reprs = []
for type in types:
try:
reprs.append(repr(type["name"]))
except Exception:
reprs.append(repr(type))
yield ValidationError(
f"{instance!r} is not of type {', '.join(reprs)}",
context=all_errors,
)

reprs = []
for type in types:
try:
reprs.append(repr(type["name"]))
except Exception: # noqa: BLE001
reprs.append(repr(type))
yield ValidationError(
f"{instance!r} is not of type {', '.join(reprs)}",
context=all_errors,
)


def contains_draft6_draft7(validator, contains, instance, schema):
Expand Down Expand Up @@ -280,11 +279,11 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):

if "items" in schema:
if "additionalItems" in schema:
return list(range(0, len(instance)))
return list(range(len(instance)))

if validator.is_type(schema["items"], "object"):
return list(range(0, len(instance)))
evaluated_indexes += list(range(0, len(schema["items"])))
return list(range(len(instance)))
evaluated_indexes += list(range(len(schema["items"])))

if "if" in schema:
if validator.evolve(schema=schema["if"]).is_valid(instance):
Expand All @@ -295,11 +294,10 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):
evaluated_indexes += find_evaluated_item_indexes_by_schema(
validator, instance, schema["then"],
)
else:
if "else" in schema:
evaluated_indexes += find_evaluated_item_indexes_by_schema(
validator, instance, schema["else"],
)
elif "else" in schema:
evaluated_indexes += find_evaluated_item_indexes_by_schema(
validator, instance, schema["else"],
)

for keyword in ["contains", "unevaluatedItems"]:
if keyword in schema:
Expand Down Expand Up @@ -411,11 +409,10 @@ def find_evaluated_property_keys_by_schema(validator, instance, schema):
evaluated_keys += find_evaluated_property_keys_by_schema(
validator, instance, schema["then"],
)
else:
if "else" in schema:
evaluated_keys += find_evaluated_property_keys_by_schema(
validator, instance, schema["else"],
)
elif "else" in schema:
evaluated_keys += find_evaluated_property_keys_by_schema(
validator, instance, schema["else"],
)

return evaluated_keys

Expand All @@ -437,7 +434,7 @@ def unevaluatedProperties_draft2019(validator, uP, instance, schema):
):
# FIXME: Include context for each unevaluated property
# indicating why it's invalid under the subschema.
unevaluated_keys.append(property)
unevaluated_keys.append(property) # noqa: PERF401

if unevaluated_keys:
if uP is False:
Expand Down
2 changes: 1 addition & 1 deletion jsonschema/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def remove(self, *types) -> TypeChecker:
try:
type_checkers = type_checkers.remove(each)
except KeyError:
raise UndefinedTypeCheck(each)
raise UndefinedTypeCheck(each) from None
return evolve(self, type_checkers=type_checkers)


Expand Down
31 changes: 12 additions & 19 deletions jsonschema/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ def format_as_index(container, indices):
The indices to format.
"""

if not indices:
return container
return f"{container}[{']['.join(repr(index) for index in indices)}]"
Expand All @@ -75,7 +74,6 @@ def find_additional_properties(instance, schema):
Assumes ``instance`` is dict-like already.
"""

properties = schema.get("properties", {})
patterns = "|".join(schema.get("patternProperties", {}))
for property in instance:
Expand All @@ -89,7 +87,6 @@ def extras_msg(extras):
"""
Create an error message for extra items or properties.
"""

verb = "was" if len(extras) == 1 else "were"
return ", ".join(repr(extra) for extra in extras), verb

Expand All @@ -100,7 +97,6 @@ def ensure_list(thing):
Otherwise, return it unchanged.
"""

if isinstance(thing, str):
return [thing]
return thing
Expand Down Expand Up @@ -147,7 +143,6 @@ def unbool(element, true=object(), false=object()):
"""
A hack to make True and 1 and False and 0 unique for ``uniq``.
"""

if element is True:
return true
elif element is False:
Expand Down Expand Up @@ -185,7 +180,7 @@ def uniq(container):

def find_evaluated_item_indexes_by_schema(validator, instance, schema):
"""
Get all indexes of items that get evaluated under the current schema
Get all indexes of items that get evaluated under the current schema.
Covers all keywords related to unevaluatedItems: items, prefixItems, if,
then, else, contains, unevaluatedItems, allOf, oneOf, anyOf
Expand All @@ -195,7 +190,7 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):
evaluated_indexes = []

if "items" in schema:
return list(range(0, len(instance)))
return list(range(len(instance)))

ref = schema.get("$ref")
if ref is not None:
Expand Down Expand Up @@ -226,7 +221,7 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):
)

if "prefixItems" in schema:
evaluated_indexes += list(range(0, len(schema["prefixItems"])))
evaluated_indexes += list(range(len(schema["prefixItems"])))

if "if" in schema:
if validator.evolve(schema=schema["if"]).is_valid(instance):
Expand All @@ -237,11 +232,10 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):
evaluated_indexes += find_evaluated_item_indexes_by_schema(
validator, instance, schema["then"],
)
else:
if "else" in schema:
evaluated_indexes += find_evaluated_item_indexes_by_schema(
validator, instance, schema["else"],
)
elif "else" in schema:
evaluated_indexes += find_evaluated_item_indexes_by_schema(
validator, instance, schema["else"],
)

for keyword in ["contains", "unevaluatedItems"]:
if keyword in schema:
Expand All @@ -263,7 +257,7 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):

def find_evaluated_property_keys_by_schema(validator, instance, schema):
"""
Get all keys of items that get evaluated under the current schema
Get all keys of items that get evaluated under the current schema.
Covers all keywords related to unevaluatedProperties: properties,
additionalProperties, unevaluatedProperties, patternProperties,
Expand Down Expand Up @@ -346,10 +340,9 @@ def find_evaluated_property_keys_by_schema(validator, instance, schema):
evaluated_keys += find_evaluated_property_keys_by_schema(
validator, instance, schema["then"],
)
else:
if "else" in schema:
evaluated_keys += find_evaluated_property_keys_by_schema(
validator, instance, schema["else"],
)
elif "else" in schema:
evaluated_keys += find_evaluated_property_keys_by_schema(
validator, instance, schema["else"],
)

return evaluated_keys
2 changes: 1 addition & 1 deletion jsonschema/benchmarks/nested_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"https://json-schema.org/draft/2020-12/vocab/validation": True,
"https://json-schema.org/draft/2020-12/vocab/meta-data": True,
"https://json-schema.org/draft/2020-12/vocab/format-annotation": True,
"https://json-schema.org/draft/2020-12/vocab/content": True
"https://json-schema.org/draft/2020-12/vocab/content": True,
},
"$dynamicAnchor": "meta",

Expand Down
2 changes: 1 addition & 1 deletion jsonschema/benchmarks/subcomponents.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"type": "array",
"minLength": 1,
"maxLength": 1,
"items": {"type": "integer"}
"items": {"type": "integer"},
}

hmap = HashTrieMap()
Expand Down
2 changes: 1 addition & 1 deletion jsonschema/benchmarks/unused_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

registry = Registry().with_resource(
"urn:example:foo",
DRAFT201909.create_resource({})
DRAFT201909.create_resource({}),
)

schema = {"$ref": "https://json-schema.org/draft/2019-09/schema"}
Expand Down
26 changes: 13 additions & 13 deletions jsonschema/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
try:
from pkgutil import resolve_name
except ImportError:
from pkgutil_resolve_name import resolve_name # type: ignore
from pkgutil_resolve_name import resolve_name # type: ignore[no-redef]

from attrs import define, field

Expand Down Expand Up @@ -53,17 +53,17 @@ def from_arguments(cls, arguments, stdout, stderr):

def load(self, path):
try:
file = open(path)
except FileNotFoundError:
file = open(path) # noqa: SIM115, PTH123
except FileNotFoundError as error:
self.filenotfound_error(path=path, exc_info=sys.exc_info())
raise _CannotLoadFile()
raise _CannotLoadFile() from error

with file:
try:
return json.load(file)
except JSONDecodeError:
except JSONDecodeError as error:
self.parsing_error(path=path, exc_info=sys.exc_info())
raise _CannotLoadFile()
raise _CannotLoadFile() from error

def filenotfound_error(self, **kwargs):
self._stderr.write(self._formatter.filenotfound_error(**kwargs))
Expand Down Expand Up @@ -95,7 +95,7 @@ def filenotfound_error(self, path, exc_info):
return self._ERROR_MSG.format(
path=path,
type="FileNotFoundError",
body="{!r} does not exist.".format(path),
body=f"{path!r} does not exist.",
)

def parsing_error(self, path, exc_info):
Expand Down Expand Up @@ -126,7 +126,7 @@ class _PlainFormatter:
_error_format = field()

def filenotfound_error(self, path, exc_info):
return "{!r} does not exist.\n".format(path)
return f"{path!r} does not exist.\n"

def parsing_error(self, path, exc_info):
return "Failed to parse {}: {}\n".format(
Expand Down Expand Up @@ -209,7 +209,7 @@ def _resolve_name_with_default(name):
)


def parse_args(args):
def parse_args(args): # noqa: D103
arguments = vars(parser.parse_args(args=args or ["--help"]))
if arguments["output"] != "plain" and arguments["error_format"]:
raise parser.error(
Expand All @@ -231,11 +231,11 @@ def _validate_instance(instance_path, instance, validator, outputter):
return invalid


def main(args=sys.argv[1:]):
def main(args=sys.argv[1:]): # noqa: D103
sys.exit(run(arguments=parse_args(args=args)))


def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin):
def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin): # noqa: D103
outputter = _Outputter.from_arguments(
arguments=arguments,
stdout=stdout,
Expand Down Expand Up @@ -266,11 +266,11 @@ def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin):
def load(_):
try:
return json.load(stdin)
except JSONDecodeError:
except JSONDecodeError as error:
outputter.parsing_error(
path="<stdin>", exc_info=sys.exc_info(),
)
raise _CannotLoadFile()
raise _CannotLoadFile() from error
instances = ["<stdin>"]

resolver = _RefResolver(
Expand Down
4 changes: 2 additions & 2 deletions jsonschema/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def _contents(self):
"message", "cause", "context", "validator", "validator_value",
"path", "schema_path", "instance", "schema", "parent",
)
return dict((attr, getattr(self, attr)) for attr in attrs)
return {attr: getattr(self, attr) for attr in attrs}

def _matches_type(self):
try:
Expand Down Expand Up @@ -464,7 +464,7 @@ def best_match(errors, key=relevance):
# Calculate the minimum via nsmallest, because we don't recurse if
# all nested errors have the same relevance (i.e. if min == max == all)
smallest = heapq.nsmallest(2, best.context, key=key)
if len(smallest) == 2 and key(smallest[0]) == key(smallest[1]):
if len(smallest) == 2 and key(smallest[0]) == key(smallest[1]): # noqa: PLR2004
return best
best = smallest[0]
return best
4 changes: 2 additions & 2 deletions jsonschema/tests/_suite.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ def __repr__(self): # pragma: no cover

@property
def fully_qualified_name(self): # pragma: no cover
return " > ".join(
return " > ".join( # noqa: FLY002
[
self.version.name,
self.subject,
Expand Down Expand Up @@ -251,7 +251,7 @@ def validate(self, Validator, **kwargs):
**kwargs,
)
if os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0": # pragma: no cover
breakpoint()
breakpoint() # noqa: T100
validator.validate(instance=self.data)

def validate_ignoring_errors(self, Validator): # pragma: no cover
Expand Down
Loading

0 comments on commit 0ce7200

Please sign in to comment.