Container Types: Dict
schema.dict
- declare
- generate
- validate
- substitute
Declares a schema that can be any dict.
from d42 import schema
sch = schema.dict
Generates a random dict.
from d42 import schema
sch = schema.dict
generated = fake(sch)
assert isinstance(generated, dict)
In the current implementation, the fake
function always returns {}
Validates the value against the dict schema. If the type is correct, the schema.dict
object can match any dictionary and will always return True
.
from d42 import schema
sch = schema.dict
assert sh == {}
assert sh == {"id": 1}
assert sh != [] # incorrect type
Substitutes the value into the dict schema if the validation has passed.
from d42 import schema
sch = schema.dict
assert sch % {} == schema.dict({})
assert sch % {"id": 1} == schema.dict({"id": schema.int(1)})
The from_native function is used to convert the Python objects to d42 types.
schema.dict(keys
)
- declare
- generate
- validate
- substitute
Declares a schema for a dictionary. The contstructor takes a dictionary of key-value pairs, where the keys are strings representing the dictionary keys, and the values are schema objects representing the value types.
from d42 import schema
sch = schema.dict({
"id": schema.int.min(1),
"name": schema.str.len(1, ...)
})
By default, only the keys specified in the dictionary are allowed in the dictionary. To allow other keys, use the ... syntax:
from d42 import schema
sch = schema.dict({
"id": schema.int.min(1),
"name": schema.str.len(1, ...),
...: ...
})
Generates a random dictionary that satisfies the schema.
from d42 import schema, fake
sch = schema.dict({
"id": schema.int.min(1),
"name": schema.str.len(1, ...)
})
generated = fake(sch)
assert isinstance(generated, dict)
assert isinstance(generated["id"], int) and generated["id"] >= 1
assert isinstance(generated["id"], str) and len(generated["name"]) >= 1
Validates a dictionary against a schema object.
from d42 import schema
sch = schema.dict({
"id": schema.int.min(1),
"name": schema.str.len(1, ...)
})
assert sch == {"id": 1, "name": "Bob"}
assert sch == {"id": 2, "name": "Alice"}
assert sch != {"id": 0, "name": "Bob"} # incorrect `id` value
assert sch != {"id": 1} # missing `name` key
assert sch != {"id": 1, "name": "Bob", "is_deleted": False} # extra `is_deleted` key
Substitutes the values of a dictionary with the corresponding schema object.
from d42 import schema
sch = schema.dict({
"id": schema.int.min(1),
"name": schema.str.len(1, ...)
})
assert sch % {"id": 1, "name": "Bob"} == schema.dict({
"id": schema.int(1).min(1),
"name": schema.str("Bob").len(1, ...)
})