How to use the typesystem.fields.String function in typesystem

To help you get started, we’ve selected a few typesystem examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github encode / typesystem / tests / test_fields.py View on Github external
def test_string():
    validator = String()
    validated = validator.validate_or_error("abc")
    assert validated
    assert validated.value == "abc"
    assert validated.error is None

    validator = String()
    value, error = validator.validate_or_error("")
    assert error == ValidationError(text="Must not be blank.", code="blank")

    validator = String()
    value, error = validator.validate_or_error(None)
    assert error == ValidationError(text="May not be null.", code="null")

    validator = String()
    value, error = validator.validate_or_error(123)
    assert error == ValidationError(text="Must be a string.", code="type")

    validator = String(max_length=10)
    value, error = validator.validate_or_error("abc" * 10)
    assert error == ValidationError(
        text="Must have no more than 10 characters.", code="max_length"
    )

    validator = String(min_length=3)
    value, error = validator.validate_or_error("a")
    assert error == ValidationError(
github encode / typesystem / tests / test_fields.py View on Github external
validator = String(allow_null=True)
    value, error = validator.validate_or_error(None)
    assert value is None
    assert error is None

    validator = String(allow_null=True)
    value, error = validator.validate_or_error("")
    assert value is None
    assert error is None

    validator = String(allow_null=True)
    value, error = validator.validate_or_error(" ")
    assert value is None
    assert error is None

    validator = String(pattern="^[abc]*$")
    value, error = validator.validate_or_error("cba")
    assert value == "cba"

    validator = String(pattern="^[abc]*$")
    value, error = validator.validate_or_error("cbxa")
    assert error == ValidationError(
        text="Must match the pattern /^[abc]*$/.", code="pattern"
    )

    validator = String(pattern=re.compile("ABC", re.IGNORECASE))
    value, error = validator.validate_or_error("abc")
    assert value == "abc"

    validator = String()
    value, error = validator.validate_or_error(" ")
    assert error == ValidationError(text="Must not be blank.", code="blank")
github encode / typesystem / tests / test_fields.py View on Github external
def test_uuid():
    validator = String(format="uuid")
    value, error = validator.validate_or_error("93e19019-c7a6-45fe-8936-f6f4d550f35f")
    assert value == uuid.UUID("93e19019-c7a6-45fe-8936-f6f4d550f35f")

    validator = String(format="uuid")
    value, error = validator.validate_or_error("1245a678-1234-1234-1234-123412341234")
    assert error == ValidationError(text="Must be valid UUID format.", code="format")
github encode / typesystem / typesystem / fields.py View on Github external
if obj is None:
            return None

        if isinstance(self.items, list):
            return [
                serializer.serialize(value)
                for serializer, value in zip(self.items, obj)
            ]

        if self.items is None:
            return obj

        return [self.items.serialize(value) for value in obj]


class Text(String):
    def __init__(self, **kwargs: typing.Any) -> None:
        super().__init__(format="text", **kwargs)


class Date(String):
    def __init__(self, **kwargs: typing.Any) -> None:
        super().__init__(format="date", **kwargs)


class Time(String):
    def __init__(self, **kwargs: typing.Any) -> None:
        super().__init__(format="time", **kwargs)


class DateTime(String):
    def __init__(self, **kwargs: typing.Any) -> None:
github encode / typesystem / typesystem / json_schema.py View on Github external
definitions = SchemaDefinitions()

JSONSchema = (
    Object(
        properties={
            "$ref": String(),
            "type": String() | Array(items=String()),
            "enum": Array(unique_items=True, min_items=1),
            "definitions": Object(
                additional_properties=Reference("JSONSchema", definitions=definitions)
            ),
            # String
            "minLength": Integer(minimum=0),
            "maxLength": Integer(minimum=0),
            "pattern": String(format="regex"),
            "format": String(),
            # Numeric
            "minimum": Number(),
            "maximum": Number(),
            "exclusiveMinimum": Number(),
            "exclusiveMaximum": Number(),
            "multipleOf": Number(exclusive_minimum=0),
            # Object
            "properties": Object(
                additional_properties=Reference("JSONSchema", definitions=definitions)
            ),
            "minProperties": Integer(minimum=0),
            "maxProperties": Integer(minimum=0),
            "patternProperties": Object(
                additional_properties=Reference("JSONSchema", definitions=definitions)
            ),
github encode / typesystem / typesystem / forms.py View on Github external
def template_for_field(self, field: Field) -> str:
        assert not isinstance(
            field, Object
        ), "Forms do not support rendering Object fields"

        if isinstance(field, Choice):
            return "forms/select.html"
        elif isinstance(field, Boolean):
            return "forms/checkbox.html"
        if isinstance(field, String) and field.format == "text":
            return "forms/textarea.html"
        return "forms/input.html"
github encode / typesystem / typesystem / json_schema.py View on Github external
"pattern",
    "patternProperties",
    "properties",
    "propertyNames",
    "required",
    "type",
    "uniqueItems",
}


definitions = SchemaDefinitions()

JSONSchema = (
    Object(
        properties={
            "$ref": String(),
            "type": String() | Array(items=String()),
            "enum": Array(unique_items=True, min_items=1),
            "definitions": Object(
                additional_properties=Reference("JSONSchema", definitions=definitions)
            ),
            # String
            "minLength": Integer(minimum=0),
            "maxLength": Integer(minimum=0),
            "pattern": String(format="regex"),
            "format": String(),
            # Numeric
            "minimum": Number(),
            "maximum": Number(),
            "exclusiveMinimum": Number(),
            "exclusiveMaximum": Number(),
            "multipleOf": Number(exclusive_minimum=0),
github encode / typesystem / typesystem / json_schema.py View on Github external
"default": data.get("default", NO_DEFAULT),
        }
        return Integer(**kwargs)

    elif type_string == "string":
        min_length = data.get("minLength", 0)
        kwargs = {
            "allow_null": allow_null,
            "allow_blank": min_length == 0,
            "min_length": min_length if min_length > 1 else None,
            "max_length": data.get("maxLength", None),
            "format": data.get("format"),
            "pattern": data.get("pattern", None),
            "default": data.get("default", NO_DEFAULT),
        }
        return String(**kwargs)

    elif type_string == "boolean":
        kwargs = {"allow_null": allow_null, "default": data.get("default", NO_DEFAULT)}
        return Boolean(**kwargs)

    elif type_string == "array":
        items = data.get("items", None)
        if items is None:
            items_argument: typing.Union[None, Field, typing.List[Field]] = None
        elif isinstance(items, list):
            items_argument = [
                from_json_schema(item, definitions=definitions) for item in items
            ]
        else:
            items_argument = from_json_schema(items, definitions=definitions)