Skip to content

Commit 10975a9

Browse files
committed
Narrower handling around unresolved refs
1 parent f203cde commit 10975a9

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed

openapi_schema_validator/_keywords.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from jsonschema._utils import find_additional_properties
1111
from jsonschema.exceptions import FormatError
1212
from jsonschema.exceptions import ValidationError
13+
from jsonschema.exceptions import _WrappedReferencingError
14+
from referencing.exceptions import Unresolvable
1315

1416

1517
def handle_discriminator(
@@ -53,7 +55,15 @@ def handle_discriminator(
5355

5456
try:
5557
validator._validate_reference(ref=ref, instance=instance)
56-
except Exception:
58+
except _WrappedReferencingError as error:
59+
if isinstance(error.__cause__, Unresolvable):
60+
yield ValidationError(
61+
f"{instance!r} reference {ref!r} could not be resolved",
62+
context=[],
63+
)
64+
return
65+
raise
66+
except Unresolvable:
5767
yield ValidationError(
5868
f"{instance!r} reference {ref!r} could not be resolved",
5969
context=[],

tests/integration/test_validators.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
from base64 import b64encode
2+
from typing import Any
3+
from typing import cast
24

35
import pytest
46
from jsonschema import ValidationError
@@ -353,6 +355,57 @@ def test_oneof_required(self, validator_class):
353355
result = validator.validate(instance)
354356
assert result is None
355357

358+
def test_discriminator_does_not_swallow_unexpected_ref_errors(
359+
self, monkeypatch
360+
):
361+
schema = {
362+
"$ref": "#/components/schemas/Route",
363+
"components": {
364+
"schemas": {
365+
"Route": {
366+
"oneOf": [
367+
{"$ref": "#/components/schemas/MountainHiking"}
368+
],
369+
"discriminator": {
370+
"propertyName": "discipline",
371+
"mapping": {
372+
"mountain_hiking": "#/components/schemas/MountainHiking"
373+
},
374+
},
375+
},
376+
"MountainHiking": {
377+
"type": "object",
378+
"properties": {
379+
"discipline": {"type": "string"},
380+
"length": {"type": "integer"},
381+
},
382+
"required": ["discipline", "length"],
383+
},
384+
},
385+
},
386+
}
387+
388+
def fail_validate_reference(*args: Any, **kwargs: Any) -> None:
389+
raise RuntimeError("boom")
390+
391+
monkeypatch.setattr(
392+
cast(Any, OAS30Validator),
393+
"_validate_reference",
394+
fail_validate_reference,
395+
)
396+
397+
validator = OAS30Validator(
398+
schema,
399+
format_checker=oas30_format_checker,
400+
)
401+
with pytest.raises(RuntimeError, match="boom"):
402+
validator.validate(
403+
{
404+
"discipline": "mountain_hiking",
405+
"length": 10,
406+
}
407+
)
408+
356409
@pytest.mark.parametrize(
357410
"schema_type",
358411
[

0 commit comments

Comments
 (0)