|
2 | 2 | from unittest.mock import patch |
3 | 3 |
|
4 | 4 | import pytest |
| 5 | +from referencing import Registry |
| 6 | +from referencing import Resource |
5 | 7 |
|
6 | 8 | from openapi_schema_validator import OAS32Validator |
7 | 9 | from openapi_schema_validator import validate |
@@ -56,3 +58,63 @@ def test_oas32_validate_does_not_fetch_remote_metaschemas(schema): |
56 | 58 | validate({"email": "foo@bar.com"}, schema, cls=OAS32Validator) |
57 | 59 |
|
58 | 60 | urlopen.assert_not_called() |
| 61 | + |
| 62 | + |
| 63 | +def test_validate_blocks_implicit_remote_http_references_by_default(): |
| 64 | + schema = {"$ref": "http://example.com/remote-schema.json"} |
| 65 | + |
| 66 | + with patch("urllib.request.urlopen") as urlopen: |
| 67 | + with pytest.raises(Exception, match="Unresolvable"): |
| 68 | + validate({}, schema) |
| 69 | + |
| 70 | + urlopen.assert_not_called() |
| 71 | + |
| 72 | + |
| 73 | +def test_validate_blocks_implicit_file_references_by_default(): |
| 74 | + schema = {"$ref": "file:///etc/hosts"} |
| 75 | + |
| 76 | + with patch("urllib.request.urlopen") as urlopen: |
| 77 | + with pytest.raises(Exception, match="Unresolvable"): |
| 78 | + validate({}, schema) |
| 79 | + |
| 80 | + urlopen.assert_not_called() |
| 81 | + |
| 82 | + |
| 83 | +def test_validate_local_references_still_work_by_default(): |
| 84 | + schema = {"$defs": {"Value": {"type": "integer"}}, "$ref": "#/$defs/Value"} |
| 85 | + |
| 86 | + with patch("urllib.request.urlopen") as urlopen: |
| 87 | + result = validate(1, schema) |
| 88 | + |
| 89 | + assert result is None |
| 90 | + urlopen.assert_not_called() |
| 91 | + |
| 92 | + |
| 93 | +def test_validate_honors_explicit_registry(): |
| 94 | + schema = { |
| 95 | + "type": "object", |
| 96 | + "properties": {"name": {"$ref": "urn:name-schema"}}, |
| 97 | + } |
| 98 | + name_schema = Resource.from_contents( |
| 99 | + { |
| 100 | + "$schema": "https://json-schema.org/draft/2020-12/schema", |
| 101 | + "type": "string", |
| 102 | + } |
| 103 | + ) |
| 104 | + registry = Registry().with_resources( |
| 105 | + [("urn:name-schema", name_schema)], |
| 106 | + ) |
| 107 | + |
| 108 | + result = validate({"name": "John"}, schema, registry=registry) |
| 109 | + |
| 110 | + assert result is None |
| 111 | + |
| 112 | + |
| 113 | +def test_validate_can_allow_implicit_remote_references(): |
| 114 | + schema = {"$ref": "http://example.com/remote-schema.json"} |
| 115 | + |
| 116 | + with patch("urllib.request.urlopen") as urlopen: |
| 117 | + with pytest.raises(Exception): |
| 118 | + validate({}, schema, allow_remote_references=True) |
| 119 | + |
| 120 | + assert urlopen.called |
0 commit comments