Beispiel YAML:
Code: Select all
TOP_LEVEL_KEY:
first_level:
can_be_any_value:
some_setting: value
second_level:
any_value:
some_setting: value2
SOME_OTHER_TOP_LEVEL:
....
< /code>
First_level und Second_level sind in einer Enum -Liste vordefiniert. Es kann eine unbestimmte Anzahl von Stufen geben. < /P>
Schema: < /p>
yaml_schema = {
'$defs': {
'ConfigLevel': {
'type': 'object',
'propertyNames': {
'enum': [
'first_level',
'second_level',
]
},
"additionalProperties": {
'type': 'object', # the 'can_by_any_value' objects
"additionalProperties": {
'type': 'object',
'properties': {
'some_setting': {
'type': 'string'
},
},
"additionalProperties": {
'$ref': '#/$defs/ConfigLevel'
}
}
}
}
},
'type': 'object',
'additionalProperties': {
'$ref': '#/$defs/ConfigLevel'
}
}
< /code>
Beispiel Wie geschrieben wird mit: < /p>
fehlgeschlagenjsonschema.exceptions.ValidationError: 'can_by_any_value' is not one of ['first_level', 'second_level']
< /code>
Aber dieses YAML wird < /p>
validierenTOP_LEVEL_KEY:
first_level:
can_be_any_value:
some_setting: value
second_level:
any_value:
some_setting: value2
Beispiel pyTest: < /p>
Code: Select all
import pytest
import yaml
from jsonschema import validate
@pytest.fixture(scope="module")
def yaml_fixture() -> str:
return """
TOP_LEVEL:
first_level:
can_be_any_value:
some_setting: value
second_level:
can_by_any_value:
some_setting: value2
"""
def test_validate_yaml(yaml_fixture):
validate(yaml.safe_load(yaml_fixture), yaml_schema)