def test_init_default_factory(self): """ Instantiating with default_factory creates a proper descriptor for _default. """ a = Attribute("foo", default_factory=list) assert NOTHING is a.default_value assert list() == a.default_factory()
def test_store_attributes_stores_Attributes(self): """ The attributes passed to store_attributes are always instances of Attribute, even if they were simple strings when provided. """ @attributes(["a", "b"]) class C(object): pass assert C.characteristic_attributes == [Attribute("a"), Attribute("b")]
def test_store_attributes(self): """ store_attributes is called on the class to store the attributes that were passed in. """ attrs = [Attribute("a"), Attribute("b")] @attributes(attrs, store_attributes=lambda cls, a: setattr(cls, "foo", a)) class C(object): pass assert C.foo == attrs
def test_linecache_different_attrs(self): """ Different Attributes have different generated filenames. """ @with_init([Attribute("a")]) class C1(object): pass @with_init([Attribute("b")]) class C2(object): pass assert (C1.__init__.__code__.co_filename != C2.__init__.__code__.co_filename)
def test_eq_equal(self): """ Equal Attributes are detected equal. """ kw = { "name": "name", "exclude_from_cmp": True, "exclude_from_init": False, "exclude_from_repr": True, "exclude_from_immutable": False, "default_value": 42, "instance_of": int, } assert Attribute(**kw) == Attribute(**kw)
def test_alias(self): """ If an attribute with a leading _ is defined, the initializer keyword is stripped of it. """ a = Attribute("_private") assert "private" == a._kw_name
def test_init_simple(self): """ Instantiating with just the name initializes properly. """ a = Attribute("foo") assert "foo" == a.name assert NOTHING is a._default
def test_ambiguous_defaults(self): """ Instantiating with both default_value and default_factory raises ValueError. """ with pytest.raises(ValueError): Attribute("foo", default_value="bar", default_factory=lambda: 42)
def test_missing_attr(self): """ Accessing inexistent attributes still raises an AttributeError. """ a = Attribute("foo") with pytest.raises(AttributeError): a.bar
def test_optimizes_simple(self): """ If no defaults and extra checks are passed, an optimized version is used on Python 2.7+. """ attrs = [Attribute("a")] script = _attrs_to_script(attrs) assert "except KeyError as e:" in script
def test_eq_unequal(self): """ Equal Attributes are detected equal. """ kw = { "name": "name", "exclude_from_cmp": True, "exclude_from_init": False, "exclude_from_repr": True, "exclude_from_immutable": False, "default_value": 42, "instance_of": int, } for arg in kw.keys(): kw_mutated = dict(**kw) kw_mutated[arg] = "mutated" assert Attribute(**kw) != Attribute(**kw_mutated)
def test_Attribute_exclude_from_init(self): """ Ignores attribute if exclude_from_init=True. """ @with_init([Attribute("a", exclude_from_init=True), "b"]) class C(object): pass C(b=1)
def test_underscores(self): """ with_init takes keyword aliasing into account. """ @with_init([Attribute("_a")]) class C(object): pass c = C(a=1) assert 1 == c._a
def test_attribute_names(self): """ :func:`helper.attribute_names` returns the string if an attribute is a string, and the name if the attribute is a :class:`characteristic.Attribute` """ self.assertEqual(['ima_string', 'ima_name'], helper.attribute_names( ['ima_string', Attribute('ima_name')]))
def test_private_no_alias(self): """ Integration test for name mangling/aliasing. """ @attributes([Attribute("_a", init_aliaser=None)]) class C(object): pass c = C(_a=42) assert 42 == c._a
def test_private(self): """ Integration test for name mangling/aliasing. """ @attributes([Attribute("_a")]) class C(object): pass c = C(a=42) assert 42 == c._a
def test_Attribute_exclude_from_cmp(self): """ Ignores attribute if exclude_from_cmp=True. """ @with_cmp([Attribute("a", exclude_from_cmp=True), "b"]) class C(object): def __init__(self, a, b): self.a = a self.b = b assert C(42, 1) == C(23, 1)
def test_Attribute_exclude_from_repr(self): """ Ignores attribute if exclude_from_repr=True. """ @with_repr([Attribute("a", exclude_from_repr=True), "b"]) class C(object): def __init__(self, a, b): self.a = a self.b = b assert "<C(b=2)>" == repr(C(1, 2))
def test_instance_of_success(self): """ Setting an attribute to a value that doesn't conflict with an `instance_of` declaration works. """ @with_init([Attribute("a", instance_of=int)]) class C(object): pass c = C(a=42) assert 42 == c.a
def test_default_factory(self): """ The default factory is used for each instance of missing keyword argument. """ @with_init([Attribute("a", default_factory=list)]) class C(object): pass o1 = C() o2 = C() assert o1.a is not o2.a
def test_Attribute(self): """ Mutation is caught if user passes an Attribute instance. """ @immutable([Attribute("foo")]) class ImmuClass(object): def __init__(self): self.foo = "bar" i = ImmuClass() with pytest.raises(AttributeError): i.foo = "not bar"
def test_store_attributes_defaults_to_characteristic_attributes(self): """ By default, store_attributes stores the attributes in `characteristic_attributes` on the class. """ attrs = [Attribute("a")] @attributes(attrs) class C(object): pass assert C.characteristic_attributes == attrs
def test_linecache(self): """ The created init method is added to the linecache so PDB shows it properly. """ attrs = [Attribute("a")] @with_init(attrs) class C(object): pass assert tuple == type(linecache.cache[C.__init__.__code__.co_filename])
def test_instance_of_fail(self): """ Raise `TypeError` if an Attribute with an `instance_of` is is attempted to be set to a mismatched type. """ @with_init([Attribute("a", instance_of=int)]) class C(object): pass with pytest.raises(TypeError) as e: C(a="not an int!") assert ( "Attribute 'a' must be an instance of 'int'." == e.value.args[0])
def test_Attribute_exclude_from_immutable(self): """ Ignores attribute if exclude_from_immutable=True. """ @immutable([Attribute("a", exclude_from_immutable=True), "b"]) class C(object): def __init__(self, a, b): self.a = a self.b = b c = C(1, 2) c.a = 3 with pytest.raises(AttributeError): c.b = 4
def test_defaults_conflict(self): """ Raises `ValueError` if both defaults and an Attribute are passed. """ with pytest.raises(ValueError) as e: @with_init([Attribute("a")], defaults={"a": 42}) class C(object): pass assert ( "Mixing of the 'defaults' keyword argument and passing instances " "of Attribute for 'attrs' is prohibited. Please don't use " "'defaults' anymore, it has been deprecated in 14.0." == e.value.args[0])
def test_linecache_attrs_unique(self): """ If the attributes are the same, only one linecache entry is created. Since the key within the cache is the filename, this effectively means that the filenames must be equal if the attributes are equal. """ attrs = [Attribute("a")] @with_init(attrs[:]) class C1(object): pass @with_init(attrs[:]) class C2(object): pass assert (C1.__init__.__code__.co_filename == C2.__init__.__code__.co_filename)
def test_repr(self): """ repr returns the correct string. """ a = Attribute(name="name", exclude_from_cmp=True, exclude_from_init=True, exclude_from_repr=True, exclude_from_immutable=True, default_value=42, instance_of=str, init_aliaser=None) assert ( "<Attribute(name='name', exclude_from_cmp=True, " "exclude_from_init=True, exclude_from_repr=True, " "exclude_from_immutable=True, " "default_value=42, default_factory=None, instance_of=<{0} 'str'>," " init_aliaser=None)>" ).format("type" if PY2 else "class") == repr(a)
import random import string from uuid import uuid4 from characteristic import attributes, Attribute from six import text_type from mimic.util.helper import random_hex_generator, random_string METRIC_TYPE_INTEGER = 'i' METRIC_TYPE_NUMBER = 'n' METRIC_TYPE_STRING = 's' @attributes([ Attribute('agent_id', default_value=None), Attribute('created_at', instance_of=int), Attribute('id', default_factory=(lambda: u'en' + random_hex_generator(4)), instance_of=text_type), Attribute('ip_addresses', default_factory=dict, instance_of=dict), Attribute('label', default_value=u'', instance_of=text_type), Attribute('managed', default_value=False, instance_of=bool), Attribute('metadata', default_factory=dict, instance_of=dict), Attribute('updated_at', instance_of=int), Attribute('uri', default_value=None) ]) class Entity(object): """ Models a MaaS Entity. """
""" Serialize a :obj:`Keypair` into JSON """ return { "keypair": { "name": self.name, "public_key": self.public_key, "fingerprint": self.fingerprint, "user_id": self.user_id } } @attributes([ "tenant_id", "region_name", "clock", Attribute("keypairs", default_factory=list) ]) class RegionalKeyPairCollection(object): """ A :obj:`ReionalKeyPairCollection` is a collection of :obj:`KeyPair` objects owned by a given tenant for a region. """ def create_keypair(self, keypair): """ Add a :obj:`KeyPair` to the list of keypairs """ self.keypairs.append(keypair) return self.keypair_by_name(keypair.name).key_json() def keypair_by_name(self, name): """