def test_structure_simple_from_dict_default(converter, cl_and_vals, data):
"""Test structuring non-nested attrs classes with default value."""
cl, vals = cl_and_vals
obj = cl(*vals)
attrs_with_defaults = [a for a in fields(cl)
if a.default is not NOTHING]
to_remove = data.draw(lists(elements=sampled_from(attrs_with_defaults),
unique=True))
for a in to_remove:
if isinstance(a.default, Factory):
setattr(obj, a.name, a.default.factory())
else:
setattr(obj, a.name, a.default)
dumped = asdict(obj)
for a in to_remove:
del dumped[a.name]
assert obj == converter.structure(dumped, cl)
python类Factory()的实例源码
def factory(distribution_type, provenance=None):
"""
Factory method for creating the appropriate Orchestrator sub-class
based on format type.
Parameters
----------
distribution_type : string
Type of distribution subclass to create. Current options are:
'conda', 'debian', 'neurodebian', 'pypi'
provenance : dict
Keyword args to be passed to initialize class instance
Returns
-------
distribution : object
Distribution class or its instance (when provenance is not None)
"""
class_name = distribution_type.capitalize() + 'Distribution'
module = import_module('niceman.distributions.' + distribution_type.lower())
class_ = getattr(module, class_name)
return class_ if provenance is None else class_(**provenance)
def test_AsyncResource_defaults():
@attr.s
class MyAR(tabc.AsyncResource):
record = attr.ib(default=attr.Factory(list))
async def aclose(self):
self.record.append("ac")
async with MyAR() as myar:
assert isinstance(myar, MyAR)
assert myar.record == []
assert myar.record == ["ac"]
def just_class(tup):
# tup: Tuple[List[Tuple[_CountingAttr, Strategy]],
# Tuple[Type, Sequence[Any]]]
nested_cl = tup[1][0]
nested_cl_args = tup[1][1]
default = attr.Factory(lambda: nested_cl(*nested_cl_args))
combined_attrs = list(tup[0])
combined_attrs.append((attr.ib(type=nested_cl, default=default),
just(nested_cl(*nested_cl_args))))
return _create_hyp_class(combined_attrs)
def list_of_class(tup):
nested_cl = tup[1][0]
nested_cl_args = tup[1][1]
default = attr.Factory(lambda: [nested_cl(*nested_cl_args)])
combined_attrs = list(tup[0])
combined_attrs.append((attr.ib(type=List[nested_cl], default=default),
just([nested_cl(*nested_cl_args)])))
return _create_hyp_class(combined_attrs)
def dict_of_class(tup):
nested_cl = tup[1][0]
nested_cl_args = tup[1][1]
default = attr.Factory(lambda: {"cls": nested_cl(*nested_cl_args)})
combined_attrs = list(tup[0])
combined_attrs.append((attr.ib(type=Dict[str, nested_cl], default=default),
just({'cls': nested_cl(*nested_cl_args)})))
return _create_hyp_class(combined_attrs)
def just_class(tup):
nested_cl = tup[1][0]
default = attr.Factory(nested_cl)
combined_attrs = list(tup[0])
combined_attrs.append((attr.ib(default=default), st.just(nested_cl())))
return _create_hyp_class(combined_attrs)
def dict_of_class(tup):
nested_cl = tup[1][0]
default = attr.Factory(lambda: {"cls": nested_cl()})
combined_attrs = list(tup[0])
combined_attrs.append((attr.ib(default=default),
st.just({'cls': nested_cl()})))
return _create_hyp_class(combined_attrs)
def dict_attrs(draw, defaults=None):
"""
Generate a tuple of an attribute and a strategy that yields dictionaries
for that attribute. The dictionaries map strings to integers.
"""
default = NOTHING
val_strat = st.dictionaries(keys=st.text(), values=st.integers())
if defaults is True or (defaults is None and draw(st.booleans())):
default_val = draw(val_strat)
default = attr.Factory(lambda: default_val)
return ((attr.ib(default=default), val_strat))
def Field(*args, default=attr.NOTHING, **kwargs):
if callable(default):
default = attr.Factory(default)
return attr.ib(*args, default=default, **kwargs)
def attr_init(factory_or_default=attr.NOTHING, **attr_kws):
if callable(factory_or_default): factory_or_default = attr.Factory(factory_or_default)
return attr.ib(default=factory_or_default, **attr_kws)
def TypedList(type_):
"""A helper to generate an attribute which would be with list factory
but also defining a type in its metadata
"""
return attr.ib(default=Factory(list), metadata={'type': type_})
#
# Models
#