def test_traits(trait, failcases, passcases):
obj = T.HasTraits() # needed to pass to validate()
for passcase in passcases:
trait._validate(obj, passcase)
for failcase in failcases:
with pytest.raises(T.TraitError):
trait._validate(obj, failcase)
python类TraitError()的实例源码
def test_hastraits_defaults():
class Foo(jst.JSONHasTraits):
_additional_traits = [T.Integer()]
name = T.Unicode()
f = Foo(name="Bob", age=40)
f.set_trait('year', 2000)
assert set(f.trait_names()) == {'name', 'age', 'year'}
with pytest.raises(T.TraitError):
f.set_trait('foo', 'abc')
with pytest.raises(T.TraitError):
f.set_trait('age', 'blah')
def test_AnyOfObject():
class Foo(jst.JSONHasTraits):
intval = T.Integer()
flag = T.Bool()
class Bar(jst.JSONHasTraits):
strval = T.Unicode()
flag = T.Bool()
class FooBar(jst.AnyOfObject):
_classes = [Foo, Bar]
FooBar(strval='hello', flag=True)
FooBar(intval=5, flag=True)
with pytest.raises(T.TraitError):
FooBar(strval=666, flag=False)
with pytest.raises(T.TraitError):
FooBar(strval='hello', flag='bad arg')
with pytest.raises(T.TraitError):
FooBar(intval='bad arg', flag=False)
with pytest.raises(T.TraitError):
FooBar(intval=42, flag='bad arg')
# Test from_dict
FooBar.from_dict({'strval': 'hello', 'flag': True})
FooBar.from_dict({'intval': 42, 'flag': False})
def test_to_from_dict_with_defaults():
dct = {'x': 4, 'y': {'val': 'hello', 'other_val': 'hello 2'}}
obj = Foo.from_dict(dct)
dct2 = obj.to_dict()
assert dct == dct2
dct = {'x': 4, 'z': 'blah', 'y': {'val': 'hello'}}
with pytest.raises(T.TraitError):
Foo.from_dict(dct)
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_max_length(self, proposal):
if not len(proposal['value']) == self._npoints:
raise t.TraitError(
'len({class_name}().{trait_name}) must be equal to {class_name}().nsegments + 1. Proposed {trait_name} is {proposal}'.format(
class_name=proposal['owner'].__class__.__name__,
trait_name=proposal['trait'].name,
proposal=proposal['value']
)
)
return proposal['value']
def _less_than_maximum_real_power_check(self, proposal):
if not proposal['value'] <= self.maximum_real_power:
raise t.TraitError(
'{class_name}().{trait_name} must be a less than or equal to {class_name}().maximum_real_power.'.format(
class_name=proposal['owner'].__class__.__name__,
trait_name=proposal['trait'].name
)
)
else:
return proposal['value']
def test_required_keyword():
schema = {
'type': 'object',
'definitions': {
'positiveInteger': {'type': 'integer', 'minimum': 0},
'twoNumbers': {'properties': {'num1': {'type': 'number'},
'num2': {'type': 'number'}}}
},
'properties': {
'string1': {'type': 'string'},
'string2': {'type': 'string'},
'integer1': {'type': 'integer'},
'integer2': {'type': 'integer'},
'number1': {'type': 'number'},
'number2': {'type': 'number'},
'bool1': {'type': 'boolean'},
'bool2': {'type': 'boolean'},
'null1': {'type': 'null'},
'null2': {'type': 'null'},
'enum1': {'enum': [1, 2, 3]},
'enum2': {'enum': [1, 2, 3]},
'array1': {'type': 'array', 'items': {'type': 'integer'}},
'array2': {'type': 'array', 'items': {'type': 'integer'}},
'traitref1': {'$ref': '#/definitions/positiveInteger'},
'traitref2': {'$ref': '#/definitions/positiveInteger'},
'objref1': {'$ref': '#/definitions/twoNumbers'},
'objref2': {'$ref': '#/definitions/twoNumbers'},
'typelist1': {'type': ['string', 'integer']},
'typelist2': {'type': ['string', 'integer']},
},
'required': ['string1', 'integer1', 'number1',
'bool1', 'null1', 'enum1', 'array1',
'traitref1', 'objref1', 'typelist1']
}
js = JSONSchema(schema).traitlets
js.load_module('_schema', reload_module=True)
from _schema import Root
assert Root()._required_traits == js.required
r = Root()
with pytest.raises(T.TraitError) as err:
r.to_dict()
assert err.match("Required trait '[a-z]+1' is undefined")
def test_default_generator(default_generator):
g = default_generator
assert g.name == 'GenCo1'
assert g.generator_bus == 'Bus1'
assert g.generation_type == 'NATURALGAS'
assert g.maximum_real_power == 100
assert g.ramp_up_rate == 100
assert g.ramp_down_rate == 100
assert len(g.cost_curve_points) == 4
assert len(g.cost_curve_values) == 4
with pt.raises(T.TraitError):
g.ramp_up_rate = 100.5
with pt.raises(T.TraitError):
g.ramp_down_rate = 100.5
assert g.ramp_up_rate == 100
assert g.ramp_down_rate == 100
with pt.raises(AttributeError) as excinfo:
g.ramp_rate
assert 'ramp_down_rate' in str(excinfo.value) and 'ramp_up_rate' in str(excinfo.value)
with pt.raises(T.TraitError):
g.nsegments = 0
with pt.raises(T.TraitError):
g.initial_real_power = 100.5
with pt.raises(T.TraitError):
g.initial_imag_power = 100.5
with pt.raises(T.TraitError) as excinfo:
g.cost_curve_points = [0, 1, 2]
assert 'must be equal to' in str(excinfo.value)
with pt.raises(T.TraitError) as excinfo:
g.cost_curve_values = [0, 1, 2]
assert 'must be equal to' in str(excinfo.value)