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_model_field_validate_only_when_field_is_set():
class M0(Model):
bar = StringType()
def validate_bar(self, data, value):
if data['bar'] and 'bar' not in data['bar']:
raise ValidationError('Illegal value')
class M1(Model):
foo = StringType(required=True)
def validate_foo(self, data, value):
if 'foo' not in data['foo']:
raise ValidationError('Illegal value')
m = M0({})
m.validate()
def test_nested_model_override_mapping_methods():
"""
overriding mapping methods on child models should not cause issues
with validation on the parent.
"""
class Nested(Model):
items, values, get, keys = IntType(), IntType(), IntType(), IntType()
class Root(Model):
keys = ModelType(Nested)
root = Root({"keys": {"items": 1, "values": 1, "get": 1, "keys": 1}})
root.validate()
for key in ["items", "values", "get", "keys"]:
assert getattr(root.keys, key) == 1
def test_attribute_default_to_none_if_no_value():
class User(Model):
name = StringType()
u = User()
assert u.name is None
def test_list_with_default_type():
class CategoryStatsInfo(Model):
slug = StringType()
class PlayerInfo(Model):
categories = ListType(ModelType(CategoryStatsInfo))
math_stats = CategoryStatsInfo(dict(slug="math"))
twilight_stats = CategoryStatsInfo(dict(slug="twilight"))
info = PlayerInfo({
"categories": [{"slug": "math"}, {"slug": "twilight"}]
})
assert info.categories == [math_stats, twilight_stats]
d = info.serialize()
assert d == {
"categories": [{"slug": "math"}, {"slug": "twilight"}],
year5 = FloatType(required=True)
year7 = FloatType(required=True)
year10 = FloatType(required=True)
year30 = FloatType(required=True)
class InvestorSituationModel(Model):
date = StringType(required=True)
new_investor = FloatType(required=True)
final_investor = FloatType(required=True)
new_natural_person = FloatType(required=True)
new_non_natural_person = FloatType(required=True)
final_natural_person = FloatType(required=True)
final_non_natural_person = FloatType(required=True)
unit = StringType(required=True)
class HkexTradeOverviewModel(Model):
market = StringType(required=True)
direction = StringType(required=True)
date = StringType(required=True)
total_turnover = FloatType(required=True)
buy_turnover = FloatType(required=True)
sell_turnover = FloatType(required=True)
total_trade_count = IntType(required=True)
buy_trade_count = IntType(required=True)
sell_trade_count = IntType(required=True)
dqb = FloatType(required=True)
dqb_ratio = FloatType(required=True)
class HkexTradeTopTenModel(Model):
market = StringType(required=True)
direction = StringType(required=True)
date = StringType(required=True)
from schematics.models import Model
from schematics.types import DateType, StringType
class CourtOrderModel(Model):
number = StringType(required=True)
name = StringType(required=True)
date = DateType(required=True)
text = StringType(required=True)
body = StringType()
class CourtOrderReferenceModel(Model):
number = StringType(required=True)
source = StringType(required=True)
class CourtOrderESAJModel(Model):
number = StringType(required=True)
decision = StringType(required=True)
decision_date = DateType(required=True)
status = StringType()
source_numbers = StringType()
reporter = StringType()
category = StringType()
subject = StringType()
petitioner = StringType()
petitioner_attorneys = StringType()
requested = StringType()
raise ValidationError("One or more fields must be defined.")
def _validate_field_names_unique(fields):
"Field names must be unique"
if next(duplicated(f.name for f in fields), None):
raise ValidationError("Names must be unique")
def _validate_field_labels_unique(fields):
"Field labels must be unique"
if next(duplicated(f.label for f in fields), None):
raise ValidationError("Labels must be unique")
class _UserTemplateModel(Model):
name = StringType(required=True, serialized_name='Name')
object_label = StringType(serialized_name='Object label',
default='{ItemNumber:04}')
thumbnail_width_pixels = DecimalType(
default=InselectDocument.THUMBNAIL_DEFAULT_WIDTH,
min_value=InselectDocument.THUMBNAIL_MIN_WIDTH,
max_value=InselectDocument.THUMBNAIL_MAX_WIDTH,
serialized_name='Thumbnail width pixels')
cropped_file_suffix = StringType(default='.jpg',
choices=IMAGE_SUFFIXES,
serialized_name='Cropped file suffix')
fields = ListType(ModelType(_FieldModel),
serialized_name='Fields',
validators=[_validate_fields_not_empty,
_validate_field_names_unique,
_validate_field_labels_unique])
import datetime
from schematics.models import Model
from schematics.serialize import to_json, to_python
from schematics.types import (StringType,
DateTimeType,
IntType)
from schematics.types.compound import (ModelType,
ListType)
###
### Models
###
class Action(Model):
"""An `Action` associates an action name with a list of tags.
"""
value = StringType(required=True, max_length=256)
tags = ListType(StringType())
class SingleTask(Model):
"""A `SingleTask` associates a creation date with an `Action` instance.
"""
action = ModelType(Action)
created_date = DateTimeType(default=datetime.datetime.now)
class TaskList(Model):
"""A `TaskList` associated a creation date and updated_date with a list of
`Action` instances.
# pair is used for authenticating to the MySQL servers against
# any hostgroup
backend = IntType(choices=[0, 1], default=1)
# If set to 1, this (username, password) pair is used for authenticating
# to the ProxySQL instance
frontend = IntType(choices=[0, 1], default=1)
max_connections = IntType(default=10000)
def __hash__(self):
return hash('%s__%s' % (self.username, self.backend))
class ProxySQLConfig(Model):
"""A model that defines ProxySQL configuration needed by proxysql-tools."""
host = StringType(required=True)
admin_port = StringType(required=True)
admin_username = StringType(required=True)
admin_password = StringType(required=True)
monitor_username = StringType(required=True)
monitor_password = StringType(required=True)
virtual_ip = StringType()
virtual_netmask = StringType()
a_setting = BooleanType()
is_active = BooleanType()
class Options:
private_fields=['is_active']
public_fields=['username', 'name']
class Comment(Model):
text = StringType()
username = StringType()
email = EmailType()
class Options:
public_fields=['username', 'text']
class BlogPost(Model):
title = StringType()
content = StringType()
author = ModelType(Author)
post_date = DateTimeType(default=datetime.datetime.now)
comments = ListType(ModelType(Comment))
deleted = BooleanType()
class Options:
private_fields=['personal_thoughts']
public_fields=['author', 'content', 'comments']
author = Author(name='james', username='j2d2', email='jdennis@gmail.com',
a_setting=True, is_active=True)
print 'AUTHOR ]%s' % ('-' * 40)
print '- as python: ', to_python(author), '\n'