Search code examples
pythonvalidationschemaconfiguration-files

validate yaml file with dynaconf or schema in python


I have a fairly yaml file corresponding to nested dict, which I want to validate with dynaconf. I'm following the guide here: https://www.dynaconf.com/validation/ but their example is pretty simple, and I can't find a way to validate data which corresponds to nested dictionaries, like in my example below:

---
item1:
    - prod1: val1
    - prod2
        - proda: vala
        - prodb: |
            valb1
            valb2
version: 1
---
item2:
    prodx: valx

For instance I would like to make sure that vala, valb2, valx all should exist.

settings = Dynaconf(
    settings_files=['file.yml'],
    validators=[
        Validator("proda", must_exist=True, eq='vala'),
        Validator("version", must_exist=True, is_type_of=int),
        ...
    ]

Or, if you know something else, like "schema" library, which could be more suitable for this job let me know. p.s. I also want to keep multiple yaml configs in one file, separated by ---


Solution

  • As a rule of thumb, when it comes to open source tools, go through both the docs and the tests suit.

    Ex from one of their many tests:

    YAML = """
    server:
        hostname: "localhost"
        port: 22
        users:
          - "Bruno"
          - "Lula"
    app:
        name: "testname"
        path: "/tmp/app_startup"
        args:
            arg1: "a"
            arg2: "b"
            arg3: "c"
    hasemptyvalues:
        key1:
        key2:
        key3: null
        key4: "@empty"
    """
    
    @pytest.fixture
    def yaml_validators_good():
        return [
            Validator(
                "server.hostname", "server.port", "server.users", must_exist=True
            ),
            Validator(
                "app.name",
                "app.path",
                "app.args.arg1",
                "app.args.arg2",
                "app.args.arg3",
                must_exist=True,
            ),
        ]
    
    
    @pytest.fixture
    def yaml_validators_bad():
        return [
            Validator("missing.value", must_exist=True),
            Validator("app.missing", must_exist=True),
            Validator("app.args.missing", must_exist=True),
        ]