Skip to content

Commit 0ce7200

Browse files
committed
Enable the rest of the rulesets we care about and fix minor things.
1 parent 03ec8d2 commit 0ce7200

18 files changed

+120
-116
lines changed

jsonschema/_format.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
from __future__ import annotations
22

33
from contextlib import suppress
4+
from datetime import date, datetime
45
from uuid import UUID
5-
import datetime
66
import ipaddress
77
import re
88
import typing
@@ -398,17 +398,14 @@ def is_regex(instance: object) -> bool:
398398
def is_date(instance: object) -> bool:
399399
if not isinstance(instance, str):
400400
return True
401-
return bool(
402-
_RE_DATE.fullmatch(instance)
403-
and datetime.date.fromisoformat(instance)
404-
)
401+
return bool(_RE_DATE.fullmatch(instance) and date.fromisoformat(instance))
405402

406403

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

413410

414411
with suppress(ImportError):

jsonschema/_keywords.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -414,7 +414,7 @@ def unevaluatedProperties(validator, unevaluatedProperties, instance, schema):
414414
):
415415
# FIXME: Include context for each unevaluated property
416416
# indicating why it's invalid under the subschema.
417-
unevaluated_keys.append(property)
417+
unevaluated_keys.append(property) # noqa: PERF401
418418

419419
if unevaluated_keys:
420420
if unevaluatedProperties is False:

jsonschema/_legacy_keywords.py

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -202,20 +202,19 @@ def type_draft3(validator, types, instance, schema):
202202
if not errors:
203203
return
204204
all_errors.extend(errors)
205-
else:
206-
if validator.is_type(instance, type):
205+
elif validator.is_type(instance, type):
207206
return
208-
else:
209-
reprs = []
210-
for type in types:
211-
try:
212-
reprs.append(repr(type["name"]))
213-
except Exception:
214-
reprs.append(repr(type))
215-
yield ValidationError(
216-
f"{instance!r} is not of type {', '.join(reprs)}",
217-
context=all_errors,
218-
)
207+
208+
reprs = []
209+
for type in types:
210+
try:
211+
reprs.append(repr(type["name"]))
212+
except Exception: # noqa: BLE001
213+
reprs.append(repr(type))
214+
yield ValidationError(
215+
f"{instance!r} is not of type {', '.join(reprs)}",
216+
context=all_errors,
217+
)
219218

220219

221220
def contains_draft6_draft7(validator, contains, instance, schema):
@@ -280,11 +279,11 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):
280279

281280
if "items" in schema:
282281
if "additionalItems" in schema:
283-
return list(range(0, len(instance)))
282+
return list(range(len(instance)))
284283

285284
if validator.is_type(schema["items"], "object"):
286-
return list(range(0, len(instance)))
287-
evaluated_indexes += list(range(0, len(schema["items"])))
285+
return list(range(len(instance)))
286+
evaluated_indexes += list(range(len(schema["items"])))
288287

289288
if "if" in schema:
290289
if validator.evolve(schema=schema["if"]).is_valid(instance):
@@ -295,11 +294,10 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):
295294
evaluated_indexes += find_evaluated_item_indexes_by_schema(
296295
validator, instance, schema["then"],
297296
)
298-
else:
299-
if "else" in schema:
300-
evaluated_indexes += find_evaluated_item_indexes_by_schema(
301-
validator, instance, schema["else"],
302-
)
297+
elif "else" in schema:
298+
evaluated_indexes += find_evaluated_item_indexes_by_schema(
299+
validator, instance, schema["else"],
300+
)
303301

304302
for keyword in ["contains", "unevaluatedItems"]:
305303
if keyword in schema:
@@ -411,11 +409,10 @@ def find_evaluated_property_keys_by_schema(validator, instance, schema):
411409
evaluated_keys += find_evaluated_property_keys_by_schema(
412410
validator, instance, schema["then"],
413411
)
414-
else:
415-
if "else" in schema:
416-
evaluated_keys += find_evaluated_property_keys_by_schema(
417-
validator, instance, schema["else"],
418-
)
412+
elif "else" in schema:
413+
evaluated_keys += find_evaluated_property_keys_by_schema(
414+
validator, instance, schema["else"],
415+
)
419416

420417
return evaluated_keys
421418

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

442439
if unevaluated_keys:
443440
if uP is False:

jsonschema/_types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def remove(self, *types) -> TypeChecker:
166166
try:
167167
type_checkers = type_checkers.remove(each)
168168
except KeyError:
169-
raise UndefinedTypeCheck(each)
169+
raise UndefinedTypeCheck(each) from None
170170
return evolve(self, type_checkers=type_checkers)
171171

172172

jsonschema/_utils.py

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ def format_as_index(container, indices):
6060
6161
The indices to format.
6262
"""
63-
6463
if not indices:
6564
return container
6665
return f"{container}[{']['.join(repr(index) for index in indices)}]"
@@ -75,7 +74,6 @@ def find_additional_properties(instance, schema):
7574
7675
Assumes ``instance`` is dict-like already.
7776
"""
78-
7977
properties = schema.get("properties", {})
8078
patterns = "|".join(schema.get("patternProperties", {}))
8179
for property in instance:
@@ -89,7 +87,6 @@ def extras_msg(extras):
8987
"""
9088
Create an error message for extra items or properties.
9189
"""
92-
9390
verb = "was" if len(extras) == 1 else "were"
9491
return ", ".join(repr(extra) for extra in extras), verb
9592

@@ -100,7 +97,6 @@ def ensure_list(thing):
10097
10198
Otherwise, return it unchanged.
10299
"""
103-
104100
if isinstance(thing, str):
105101
return [thing]
106102
return thing
@@ -147,7 +143,6 @@ def unbool(element, true=object(), false=object()):
147143
"""
148144
A hack to make True and 1 and False and 0 unique for ``uniq``.
149145
"""
150-
151146
if element is True:
152147
return true
153148
elif element is False:
@@ -185,7 +180,7 @@ def uniq(container):
185180

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

197192
if "items" in schema:
198-
return list(range(0, len(instance)))
193+
return list(range(len(instance)))
199194

200195
ref = schema.get("$ref")
201196
if ref is not None:
@@ -226,7 +221,7 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):
226221
)
227222

228223
if "prefixItems" in schema:
229-
evaluated_indexes += list(range(0, len(schema["prefixItems"])))
224+
evaluated_indexes += list(range(len(schema["prefixItems"])))
230225

231226
if "if" in schema:
232227
if validator.evolve(schema=schema["if"]).is_valid(instance):
@@ -237,11 +232,10 @@ def find_evaluated_item_indexes_by_schema(validator, instance, schema):
237232
evaluated_indexes += find_evaluated_item_indexes_by_schema(
238233
validator, instance, schema["then"],
239234
)
240-
else:
241-
if "else" in schema:
242-
evaluated_indexes += find_evaluated_item_indexes_by_schema(
243-
validator, instance, schema["else"],
244-
)
235+
elif "else" in schema:
236+
evaluated_indexes += find_evaluated_item_indexes_by_schema(
237+
validator, instance, schema["else"],
238+
)
245239

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

264258
def find_evaluated_property_keys_by_schema(validator, instance, schema):
265259
"""
266-
Get all keys of items that get evaluated under the current schema
260+
Get all keys of items that get evaluated under the current schema.
267261
268262
Covers all keywords related to unevaluatedProperties: properties,
269263
additionalProperties, unevaluatedProperties, patternProperties,
@@ -346,10 +340,9 @@ def find_evaluated_property_keys_by_schema(validator, instance, schema):
346340
evaluated_keys += find_evaluated_property_keys_by_schema(
347341
validator, instance, schema["then"],
348342
)
349-
else:
350-
if "else" in schema:
351-
evaluated_keys += find_evaluated_property_keys_by_schema(
352-
validator, instance, schema["else"],
353-
)
343+
elif "else" in schema:
344+
evaluated_keys += find_evaluated_property_keys_by_schema(
345+
validator, instance, schema["else"],
346+
)
354347

355348
return evaluated_keys

jsonschema/benchmarks/nested_schemas.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
"https://json-schema.org/draft/2020-12/vocab/validation": True,
1919
"https://json-schema.org/draft/2020-12/vocab/meta-data": True,
2020
"https://json-schema.org/draft/2020-12/vocab/format-annotation": True,
21-
"https://json-schema.org/draft/2020-12/vocab/content": True
21+
"https://json-schema.org/draft/2020-12/vocab/content": True,
2222
},
2323
"$dynamicAnchor": "meta",
2424

jsonschema/benchmarks/subcomponents.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
"type": "array",
1212
"minLength": 1,
1313
"maxLength": 1,
14-
"items": {"type": "integer"}
14+
"items": {"type": "integer"},
1515
}
1616

1717
hmap = HashTrieMap()

jsonschema/benchmarks/unused_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
registry = Registry().with_resource(
1515
"urn:example:foo",
16-
DRAFT201909.create_resource({})
16+
DRAFT201909.create_resource({}),
1717
)
1818

1919
schema = {"$ref": "https://json-schema.org/draft/2019-09/schema"}

jsonschema/cli.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
try:
1515
from pkgutil import resolve_name
1616
except ImportError:
17-
from pkgutil_resolve_name import resolve_name # type: ignore
17+
from pkgutil_resolve_name import resolve_name # type: ignore[no-redef]
1818

1919
from attrs import define, field
2020

@@ -53,17 +53,17 @@ def from_arguments(cls, arguments, stdout, stderr):
5353

5454
def load(self, path):
5555
try:
56-
file = open(path)
57-
except FileNotFoundError:
56+
file = open(path) # noqa: SIM115, PTH123
57+
except FileNotFoundError as error:
5858
self.filenotfound_error(path=path, exc_info=sys.exc_info())
59-
raise _CannotLoadFile()
59+
raise _CannotLoadFile() from error
6060

6161
with file:
6262
try:
6363
return json.load(file)
64-
except JSONDecodeError:
64+
except JSONDecodeError as error:
6565
self.parsing_error(path=path, exc_info=sys.exc_info())
66-
raise _CannotLoadFile()
66+
raise _CannotLoadFile() from error
6767

6868
def filenotfound_error(self, **kwargs):
6969
self._stderr.write(self._formatter.filenotfound_error(**kwargs))
@@ -95,7 +95,7 @@ def filenotfound_error(self, path, exc_info):
9595
return self._ERROR_MSG.format(
9696
path=path,
9797
type="FileNotFoundError",
98-
body="{!r} does not exist.".format(path),
98+
body=f"{path!r} does not exist.",
9999
)
100100

101101
def parsing_error(self, path, exc_info):
@@ -126,7 +126,7 @@ class _PlainFormatter:
126126
_error_format = field()
127127

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

131131
def parsing_error(self, path, exc_info):
132132
return "Failed to parse {}: {}\n".format(
@@ -209,7 +209,7 @@ def _resolve_name_with_default(name):
209209
)
210210

211211

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

233233

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

237237

238-
def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin):
238+
def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin): # noqa: D103
239239
outputter = _Outputter.from_arguments(
240240
arguments=arguments,
241241
stdout=stdout,
@@ -266,11 +266,11 @@ def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin):
266266
def load(_):
267267
try:
268268
return json.load(stdin)
269-
except JSONDecodeError:
269+
except JSONDecodeError as error:
270270
outputter.parsing_error(
271271
path="<stdin>", exc_info=sys.exc_info(),
272272
)
273-
raise _CannotLoadFile()
273+
raise _CannotLoadFile() from error
274274
instances = ["<stdin>"]
275275

276276
resolver = _RefResolver(

jsonschema/exceptions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def _contents(self):
161161
"message", "cause", "context", "validator", "validator_value",
162162
"path", "schema_path", "instance", "schema", "parent",
163163
)
164-
return dict((attr, getattr(self, attr)) for attr in attrs)
164+
return {attr: getattr(self, attr) for attr in attrs}
165165

166166
def _matches_type(self):
167167
try:
@@ -464,7 +464,7 @@ def best_match(errors, key=relevance):
464464
# Calculate the minimum via nsmallest, because we don't recurse if
465465
# all nested errors have the same relevance (i.e. if min == max == all)
466466
smallest = heapq.nsmallest(2, best.context, key=key)
467-
if len(smallest) == 2 and key(smallest[0]) == key(smallest[1]):
467+
if len(smallest) == 2 and key(smallest[0]) == key(smallest[1]): # noqa: PLR2004
468468
return best
469469
best = smallest[0]
470470
return best

jsonschema/tests/_suite.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ def __repr__(self): # pragma: no cover
209209

210210
@property
211211
def fully_qualified_name(self): # pragma: no cover
212-
return " > ".join(
212+
return " > ".join( # noqa: FLY002
213213
[
214214
self.version.name,
215215
self.subject,
@@ -251,7 +251,7 @@ def validate(self, Validator, **kwargs):
251251
**kwargs,
252252
)
253253
if os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0": # pragma: no cover
254-
breakpoint()
254+
breakpoint() # noqa: T100
255255
validator.validate(instance=self.data)
256256

257257
def validate_ignoring_errors(self, Validator): # pragma: no cover

0 commit comments

Comments
 (0)