Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_validation_error_repr():
result = Example.validate_or_error({"a": "a"})
assert (
repr(result.error)
== "ValidationError([Message(text='This field is required.', code='required', index=['b'])])"
)
result = typesystem.String(max_length=10).validate_or_error("a" * 100)
assert (
repr(result.error)
== "ValidationError(text='Must have no more than 10 characters.', code='max_length')"
)
import decimal
import uuid
import pytest
import typesystem
import typesystem.formats
class Person(typesystem.Schema):
name = typesystem.String(max_length=100, allow_blank=False)
age = typesystem.Integer()
class Product(typesystem.Schema):
name = typesystem.String(max_length=100, allow_blank=False)
rating = typesystem.Integer(default=None)
def test_required():
class Example(typesystem.Schema):
field = typesystem.Integer()
value, error = Example.validate_or_error({})
assert dict(error) == {"field": "This field is required."}
class Example(typesystem.Schema):
field = typesystem.Integer(allow_null=True)
value, error = Example.validate_or_error({})
assert dict(value) == {"field": None}
def test_schema_uuid_serialization():
class User(typesystem.Schema):
id = typesystem.String(format="uuid")
username = typesystem.String()
item = User(id="b769df4a-18ec-480f-89ef-8ea961a82269", username="tom")
assert item.id == uuid.UUID("b769df4a-18ec-480f-89ef-8ea961a82269")
assert item["id"] == "b769df4a-18ec-480f-89ef-8ea961a82269"
def isinstance(self, datum):
if not isinstance(datum, numpy.generic):
# if not Numpy, check as pure Python
return typesystem.String(self.charset, self.maxlength).isinstance(datum)
ok = False
if self.charset == "bytes":
ok = isinstance(datum, numpy.string_)
if self.charset == "utf-32le":
# Numpy uses utf-32le to encode Unicode (on a little-endian machine, at least)
ok = isinstance(datum, numpy.unicode_)
if ok and self.maxlength is not None:
ok = ok and datum.dtype.itemsize <= self.maxlength
return ok
enforce_https = typesystem.Boolean(default=False)
mode = typesystem.Choice(
choices=(
("proxy", "Proxy"),
("redirect", "Redirect"),
),
default="proxy",
)
certificate_path = typesystem.String(allow_null=True)
key_path = typesystem.String(allow_null=True)
class Route(BaseSchema):
DEFAULT_SETTINGS = dict(Settings.validate({}))
source = typesystem.String()
target = typesystem.String()
settings = typesystem.Reference(Settings, default=DEFAULT_SETTINGS)
@classmethod
def validate(cls, data):
if "target" in data.keys():
data["target"] = ensure_protocol(data["target"])
return super().validate(data)
"title": typesystem.String(allow_blank=True),
"description": typesystem.Text(allow_blank=True),
"termsOfService": typesystem.String(format="url"),
"contact": typesystem.Reference("Contact", definitions=definitions),
"license": typesystem.Reference("License", definitions=definitions),
"version": typesystem.String(allow_blank=True),
},
pattern_properties={"^x-": typesystem.Any()},
additional_properties=False,
required=["title", "version"],
)
definitions["Contact"] = typesystem.Object(
properties={
"name": typesystem.String(allow_blank=True),
"url": typesystem.String(format="url"),
"email": typesystem.String(format="email"),
},
pattern_properties={"^x-": typesystem.Any()},
additional_properties=False,
)
definitions["License"] = typesystem.Object(
properties={"name": typesystem.String(), "url": typesystem.String(format="url")},
required=["name"],
pattern_properties={"^x-": typesystem.Any()},
additional_properties=False,
)
definitions["Paths"] = typesystem.Object(
pattern_properties={
"^/": typesystem.Reference("Path", definitions=definitions),
ensure_string(key): value_to_redis(self.fields[key], value)
for key, value in self.items()
if value is not None
}
class Settings(BaseSchema):
enforce_https = typesystem.Boolean(default=False)
mode = typesystem.Choice(
choices=(
("proxy", "Proxy"),
("redirect", "Redirect"),
),
default="proxy",
)
certificate_path = typesystem.String(allow_null=True)
key_path = typesystem.String(allow_null=True)
class Route(BaseSchema):
DEFAULT_SETTINGS = dict(Settings.validate({}))
source = typesystem.String()
target = typesystem.String()
settings = typesystem.Reference(Settings, default=DEFAULT_SETTINGS)
@classmethod
def validate(cls, data):
if "target" in data.keys():
data["target"] = ensure_protocol(data["target"])
return super().validate(data)
for key, value in self.items()
if value is not None
}
class Settings(BaseSchema):
enforce_https = typesystem.Boolean(default=False)
mode = typesystem.Choice(
choices=(
("proxy", "Proxy"),
("redirect", "Redirect"),
),
default="proxy",
)
certificate_path = typesystem.String(allow_null=True)
key_path = typesystem.String(allow_null=True)
class Route(BaseSchema):
DEFAULT_SETTINGS = dict(Settings.validate({}))
source = typesystem.String()
target = typesystem.String()
settings = typesystem.Reference(Settings, default=DEFAULT_SETTINGS)
@classmethod
def validate(cls, data):
if "target" in data.keys():
data["target"] = ensure_protocol(data["target"])
return super().validate(data)
# coding: utf-8
"""
여보세요 Form SchemaValidation
"""
import typesystem
class TriggerSchema(typesystem.Schema):
"""
Schema to define the structure of a Trigger
"""
description = typesystem.String(title="Description", max_length=200)
rss_url = typesystem.String(title="RSS URL", max_length=255)
joplin_folder = typesystem.String(title="Joplin Folder", max_length=80, allow_blank=True)
reddit = typesystem.String(title="Subreddit", max_length=80, allow_blank=True)
localstorage = typesystem.String(title="Markdown Folder", allow_blank=True)
mail = typesystem.Boolean(title="Send a mail ?", default=False)
mastodon = typesystem.Boolean(title="Publish on Mastodon ?", default=False)
status = typesystem.Boolean(title="Status", default=False)
import decimal
import typing
import typesystem
from sqlalchemy import orm
from typesystem.unique import Uniqueness
class Decimal(typesystem.Decimal):
def serialize(self, obj: typing.Any) -> typing.Any:
return decimal.Decimal(obj) if obj is not None else None
class Email(typesystem.String):
""" A field that validates an email """
custom_errors = {"pattern": "Must be a valid email."}
def __init__(self, **kwargs: typing.Any) -> None:
kwargs.setdefault(
"pattern", r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
)
kwargs.setdefault("format", "email")
self.errors.update(self.custom_errors)
super().__init__(**kwargs)
class Float(typesystem.Float):
def serialize(self, obj: typing.Any) -> typing.Any:
return float(obj) if obj is not None else None