Skip to content

Commit ed435de

Browse files
authored
Merge pull request #70 from Stranger6667/dd/canonicalise-any-of
Canonicalise `anyOf` special cases when all subschemas have only the `type` keyword
2 parents b50af13 + 9352cf6 commit ed435de

File tree

4 files changed

+41
-3
lines changed

4 files changed

+41
-3
lines changed

CHANGELOG.md

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

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

src/hypothesis_jsonschema/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
The only public API is `from_schema`; check the docstring for details.
44
"""
55

6-
__version__ = "0.18.0"
6+
__version__ = "0.18.1"
77
__all__ = ["from_schema"]
88

99
from ._from_schema import from_schema

src/hypothesis_jsonschema/_canonicalise.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,23 @@ 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
526+
# into the parent schema
527+
del schema["anyOf"]
528+
new_types = canonicalish({"type": types})
529+
schema = merged([schema, new_types])
530+
assert isinstance(schema, dict) # merging was certainly valid
514531
if "allOf" in schema:
515532
schema["allOf"] = [
516533
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)