Skip to content

Commit f165e86

Browse files
committed
Canonicalise anyOf special cases when all subschemas have only the type keyword
1 parent b50af13 commit f165e86

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# Changelog
22

3+
- Canonicalise `anyOf` special cases when all subschemas have only the `type` keyword
4+
35
#### 0.18.0 - 2020-09-10
46
- Performance improvements from careful caching (#62)
57
- Use a validator that corresponds to the input schema draft version (#66)

src/hypothesis_jsonschema/_canonicalise.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,21 @@ def canonicalish(schema: JSONType) -> Dict[str, Any]:
511511
return FALSEY
512512
if len(schema) == len(schema["anyOf"]) == 1:
513513
return schema["anyOf"][0] # type: ignore
514+
types = []
515+
# Turn
516+
# {"anyOf": [{"type": "string"}, {"type": "null"}]}
517+
# into
518+
# {"type": ["string", "null"]}
519+
for subschema in schema["anyOf"]:
520+
if "type" in subschema and len(subschema) == 1:
521+
types.extend(get_type(subschema))
522+
else:
523+
break
524+
else:
525+
# All subschemas have only the "type" keyword, then we merge all types into the parent schema
526+
del schema["anyOf"]
527+
new_types = canonicalish({"type": types})
528+
schema = merged([schema, new_types])
514529
if "allOf" in schema:
515530
schema["allOf"] = [
516531
json.loads(enc)

tests/test_canonicalise.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -200,8 +200,26 @@ def test_canonicalises_to_empty(schema):
200200
{"anyOf": [{"type": "number"}, {"type": "array"}]},
201201
]
202202
},
203-
# TODO: collapse into {"type": ["string", "number", "array"]}
204-
{"anyOf": [{"type": "array"}, {"type": "number"}, {"type": "string"}]},
203+
{"type": ["number", "string", "array"]},
204+
),
205+
(
206+
{
207+
"anyOf": [
208+
{"type": "integer"},
209+
{"type": "number"},
210+
]
211+
},
212+
{"type": "number"},
213+
),
214+
(
215+
{
216+
"anyOf": [
217+
{"type": "string"},
218+
{"type": "number"},
219+
],
220+
"type": ["string", "object"],
221+
},
222+
{"type": "string"},
205223
),
206224
({"uniqueItems": False}, {}),
207225
(

0 commit comments

Comments
 (0)