def render_string(self):
height = '%spx' % min(self._string.count('\n') * 16 + 36, 600)
try:
self.textarea = ipy.Textarea(self._string[:self.CHUNK],
layout=Layout(width='100%', height=height))
except traitlets.TraitError:
self.textarea = ipy.Textarea('[NOT SHOWN - UNABLE TO DECODE FILE]',
layout=Layout(height='300px',
**self.TEXTAREA_KWARGS))
return
finally:
self.children = [self.textarea]
self._current_pos = self.CHUNK
if len(self._string) > self.CHUNK:
self.textarea.value += self.TRUNCATE_MESSAGE
self.load_more_button = ipy.Button(description='See more')
self.load_more_button.on_click(self.load_more)
self.children = self.children + (self.load_more_button,)
python类TraitError()的实例源码
def validate(self, obj, value):
"""
Validate that the passed in value is a valid memory specification
It could either be a pure int, when it is taken as a byte value.
If it has one of the suffixes, it is converted into the appropriate
pure byte value.
"""
if isinstance(value, (int, float)):
return int(value)
try:
num = float(value[:-1])
except ValueError:
raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))
suffix = value[-1]
if suffix not in self.UNIT_SUFFIXES:
raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value))
else:
return int(float(num) * self.UNIT_SUFFIXES[suffix])
def __init__(self, **kwargs):
# make a copy of the _metadata so we can modify locally
self._metadata = self._metadata.copy()
# Add default traits if needed
default = self._get_additional_traits()
# TODO: protect against overwriting class attributes defined above.
# perhaps use double underscores?
if default:
all_traits = self.traits()
self.add_traits(**{key: default for key in kwargs
if key not in all_traits})
# Validate keywords to make sure they are valid traits
all_traits = list(self.traits())
for k in kwargs:
if k not in all_traits:
raise T.TraitError("Invalid trait: {0}. Options for "
"this class: {1}".format(k, all_traits))
super(JSONHasTraits, self).__init__(**kwargs)
def __init__(self, *args, **kwargs):
classes = list(self._class_defs())
if len(classes) == 0 or self.__class__ in self._class_defs():
return super(AnyOfObject, self).__init__(*args, **kwargs)
for cls in self._class_defs():
# TODO: add a second pass where we allow additional properties?
if all(key in cls.class_traits() for key in kwargs):
try:
cls(*args, **kwargs)
except (T.TraitError, ValueError):
pass
else:
assert issubclass(cls, JSONHasTraits)
self.__class__ = cls
return super(JSONHasTraits, self).__init__(*args, **kwargs)
raise T.TraitError("{cls}: initialization arguments not "
"valid in any wrapped classes"
"".format(cls=self.__class__.__name__))
def validate(self, obj, value):
if self.allow_undefined and value is undefined:
return value
# Should validate against only one of the trait types
valid_count = 0
with obj.cross_validation_lock:
for trait_type in self.trait_types:
try:
v = trait_type._validate(obj, value)
except T.TraitError:
continue
valid_count += 1
if valid_count == 1:
# In the case of an element trait, the name is None
if self.name is not None:
setattr(obj, '_' + self.name + '_metadata',
trait_type.metadata)
return v
self.error(obj, value)
def validate(self, obj, value):
if self.allow_undefined and value is undefined:
return value
try:
self.not_this.validate(obj, value)
except T.TraitError:
return value
else:
self.error(obj, value)
##########################################################################
# Visitor Pattern
#
# This implements to_dict() and from_dict() using an External Visitor Pattern
# built for the above classes.
def clsvisit_JSONHasTraits(self, cls, dct, *args, **kwargs):
try:
obj = cls()
except TypeError: # Argument missing
obj = cls('')
additional_traits = cls._get_additional_traits()
# Extract all other items, assigning to appropriate trait
reverse_name_map = {v:k for k, v in obj._trait_name_map.items()}
for schema_key, val in dct.items():
if schema_key in obj._metadata:
obj._metadata[schema_key] = val
else:
trait_key = reverse_name_map.get(schema_key, schema_key)
subtrait = obj.traits().get(trait_key, additional_traits)
if not subtrait:
raise T.TraitError("trait {0} not valid in class {1}"
"".format(trait_key, cls))
obj.set_trait(trait_key,
self.visit(subtrait, val, *args, **kwargs))
return obj
def test_hastraits_required():
class Foo(jst.JSONHasTraits):
_required_traits = ['name']
name = jst.JSONString()
age = jst.JSONNumber()
f1 = Foo(name="Sue", age=32)
f2 = Foo(age=32)
# contains all required pieces
f1.to_dict()
with pytest.raises(T.TraitError) as err:
f2.to_dict()
assert err.match("Required trait 'name' is undefined")
def test_AnyOfObject_subclasses():
class FooBar(jst.AnyOfObject):
pass
class Foo(FooBar):
bar = jst.JSONString()
class Bar(FooBar):
bar = jst.JSONNumber()
with pytest.raises(T.TraitError):
FooBar(bar=None)
with pytest.raises(T.TraitError):
FooBar(num=16)
assert FooBar(bar='hello').__class__ == Foo
assert FooBar(bar='blah').bar == 'blah'
assert FooBar(bar=14).__class__ == Bar
assert FooBar(bar=42).bar == 42
def test_to_python():
class Foo(jst.JSONHasTraits):
_required_traits = ['a', 'b']
a = jst.JSONNumber()
b = jst.JSONString()
class Bar(jst.JSONHasTraits):
c = jst.JSONArray(jst.JSONNumber())
d = jst.JSONInstance(Foo)
e = jst.JSONArray(jst.JSONInstance(Foo))
D = {'c': [1, 2, 3], 'd': {'a': 5, 'b': 'blah'},
'e': [{'a': 3, 'b': 'foo'}, {'a': 4, 'b': 'bar'}]}
obj = Bar.from_dict(D)
obj2 = eval(obj.to_python())
assert obj2.to_dict() == obj.to_dict() == D
# Make sure there is an error if required traits are missing
foo = Foo(a=4)
with pytest.raises(T.TraitError):
foo.to_python()
def test_assign_enum_value__with_other_enum_raises_error(self):
example = self.Example()
with self.assertRaises(TraitError):
example.color = OtherColor.green
def test_assign_bad_enum_value_name__raises_error(self):
# -- CONVERT: string => Enum value (item)
bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"]
for value in bad_enum_names:
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_enum_value_number__raises_error(self):
# -- CONVERT: number => Enum value (item)
bad_numbers = [-1, 0, 5]
for value in bad_numbers:
self.assertIsInstance(value, int)
assert UseEnum(Color).select_by_number(value, None) is None
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_value_with_to_enum_or_none(self):
class Example2(HasTraits):
color = UseEnum(Color, allow_none=True)
example = Example2()
with self.assertRaises(TraitError):
example.color = "BAD_VALUE"
def docker_build_host_validate(self, proposal):
parts = urlparse(proposal.value)
if parts.scheme != 'unix' or parts.netloc != '':
raise TraitError("Only unix domain sockets on same node are supported for build_docker_host")
return proposal.value
def test_assign_enum_value__with_other_enum_raises_error(self):
example = self.Example()
with self.assertRaises(TraitError):
example.color = OtherColor.green
def test_assign_bad_enum_value_name__raises_error(self):
# -- CONVERT: string => Enum value (item)
bad_enum_names = ["UNKNOWN_COLOR", "RED", "Green", "blue2"]
for value in bad_enum_names:
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_enum_value_number__raises_error(self):
# -- CONVERT: number => Enum value (item)
bad_numbers = [-1, 0, 5]
for value in bad_numbers:
self.assertIsInstance(value, int)
assert UseEnum(Color).select_by_number(value, None) is None
example = self.Example()
with self.assertRaises(TraitError):
example.color = value
def test_assign_bad_value_with_to_enum_or_none(self):
class Example2(HasTraits):
color = UseEnum(Color, allow_none=True)
example = Example2()
with self.assertRaises(TraitError):
example.color = "BAD_VALUE"
def _validate_current(self, proposal):
if proposal.value not in self.values:
raise TraitError("Current value not part of the values.")
return proposal.value
def _urlpath_validate(self, proposal):
if proposal['value'].endswith('/'):
raise TraitError("urlpath cannot end with a /")
return proposal['value']
def test_shape_validator():
trait = None
value = Mock()
correct = (1, 1)
validator = shape_validator(*correct)
value.shape = correct
assert validator(trait, value).shape == value.shape
incorrect = (1, 2)
value.shape = incorrect
pytest.raises(traitlets.TraitError, validator, trait, value)
def test_length_validator():
trait = None
value = np.array((1.0, 1.0))
lengths = np.sqrt(2), 1.0
validator = length_validator(*lengths)
assert np.allclose(validator(trait, value), value)
value = np.array((0.0, 0.0))
pytest.raises(traitlets.TraitError, validator, trait, value)
def test_error(self):
s = R.Stitch('')
assert s.error == 'continue'
s.error = 'raise'
assert s.error == 'raise'
with pytest.raises(TraitError):
s.error = 'foo'
def test_testcases_traitlets(testcase):
testcase = testcases[testcase]
modulename = '_schema'
schema = testcase['schema']
valid = testcase.get('valid', [])
invalid = testcase.get('invalid', [])
traitlets_obj = JSONSchema(schema)
for key, code in traitlets_obj.source_tree().items():
if key in ['jstraitlets.py', 'tests']:
continue
# Print code here... useful for debugging when errors happen
print(70 * '#')
print(code)
print()
schema = traitlets_obj.load_module(modulename, reload_module=True)
for instance in valid:
schema.Root.from_dict(instance)
for instance in invalid:
with pytest.raises(T.TraitError):
r = schema.Root.from_dict(instance)
r.to_dict() # catches unfilled requirements
def _validate_numeric(trait, obj, value,
minimum=undefined, maximum=undefined,
exclusiveMinimum=undefined, exclusiveMaximum=undefined,
multipleOf=undefined, **extra_kwds):
if value is None:
return value
if minimum is not undefined:
exclusive = exclusiveMinimum is not undefined and exclusiveMinimum
if value < minimum or (exclusive and value == minimum):
raise T.TraitError(
"The value of the '{name}' trait of {klass} instance should "
"not be less than {min_bound}, but a value of {value} was "
"specified".format(
name=trait.name, klass=class_of(obj),
value=value, min_bound=minimum))
if maximum is not undefined:
exclusive = exclusiveMaximum is not undefined and exclusiveMaximum
if value > maximum or (exclusive and value == maximum):
raise T.TraitError(
"The value of the '{name}' trait of {klass} instance should "
"not be greater than {max_bound}, but a value of {value} was "
"specified".format(
name=trait.name, klass=class_of(obj),
value=value, max_bound=maximum))
if multipleOf is not undefined:
if value % multipleOf != 0:
raise T.TraitError(
"The value of the '{name}' trait of {klass} instance should "
"be a multiple of {multiple}, but a value of {value} was "
"specified".format(
name=trait.name, klass=class_of(obj),
value=value, multiple=multipleOf))
return value
def validate(self, obj, value):
if self.allow_undefined and value is undefined:
return value
value = super(JSONArray, self).validate(obj, value)
if self.uniqueItems and not _has_unique_elements(value):
raise T.TraitError(
"The value of the '{name}' trait of {klass} instance should "
"have unique elements".format(
name=self.name, klass=class_of(obj)))
return value
# Need to bypass the dynamic default in T.Container() in the case that
# the trait is undefined
def generic_visit(self, trait, dct, *args, **kwargs):
if dct is None or dct is undefined:
return dct
if isinstance(dct, (six.integer_types, six.string_types, bool, float)):
return dct
else:
raise T.TraitError('cannot set {0} to {1}'.format(trait, dct))
def visit_Union(self, trait, dct, *args, **kwargs):
try:
return self.generic_visit(trait, dct)
except T.TraitError:
for subtrait in trait.trait_types:
try:
return self.visit(subtrait, dct)
except T.TraitError:
pass
raise # no valid trait found
def clsvisit_AnyOfObject(self, trait, dct, *args, **kwargs):
# TODO: match additional_traits as well?
for subcls in trait._class_defs():
if all(key in subcls.class_traits() for key in dct):
try:
obj = self.clsvisit(subcls, dct)
except (T.TraitError, ValueError):
pass
else:
return trait(**{name: getattr(obj, name)
for name in obj.trait_names()})
else:
raise T.TraitError("{cls}: dict representation not "
"valid in any wrapped classes"
"".format(cls=trait.__name__))