Beispiel #1
0
def update_atom_members(old: Atom, new: Atom):
    """Update an atom member"""
    old_keys = old.members().keys()
    new_keys = new.members().keys()
    for key in old_keys:
        old_obj = getattr(old, key)
        try:
            new_obj = getattr(new, key)
            if old_obj == new_obj:
                continue
        except AttributeError:
            # Remove any obsolete members
            try:
                delattr(old, key)
            except (AttributeError, TypeError):
                pass
            continue

        try:
            #: Update any changed members
            #: TODO: We have to somehow know if this was changed by the user or the code!
            #: and ONLY update if it's due to the code changing! Without this, the entire concept
            #: is broken and useless...
            setattr(old, key, getattr(new, key))
        except (AttributeError, TypeError):
            pass  # skip non-writable attributes

    #: Add any new members
    for key in set(new_keys) - set(old_keys):
        try:
            setattr(old, key, getattr(new, key))
        except (AttributeError, TypeError):
            pass  # skip non-writable attributes
Beispiel #2
0
def test_no_op_validation():
    """Test the no-op handler."""
    a = Atom()
    m = Value()
    m.set_validate_mode(Validate.NoOp, None)

    for value in (1, 1.0, "", [], {}):
        assert m.do_validate(a, None, value) == value
Beispiel #3
0
def test_dead_atomref():
    """Test a dead atomref."""
    atom = Atom()
    ref = atomref(atom)
    del atom
    gc.collect()

    assert not ref and ref() is None
    assert "AtomRef" in repr(ref)

    ref.__sizeof__()
Beispiel #4
0
def test_live_atomref():
    """Test a live atomref."""
    atom = Atom()
    ref = atomref(atom)

    assert ref is atomref(atom)
    assert ref and ref() is atom
    assert "AtomRef" in repr(ref)

    ref.__sizeof__()

    with pytest.raises(TypeError):
        atomref(object())
Beispiel #5
0
def test_wrong_reset_arguments():
    """Test the handling of wrong arguments in reset."""
    prop = Property()

    with pytest.raises(TypeError) as excinfo:
        reset_property()
    assert "2 arguments" in excinfo.exconly()

    with pytest.raises(TypeError) as excinfo:
        reset_property(None, None)
    assert "Member" in excinfo.exconly()

    with pytest.raises(TypeError) as excinfo:
        prop.reset(None)
    assert "CAtom" in excinfo.exconly()

    with pytest.raises(SystemError) as excinfo:
        prop.reset(Atom())
    assert "invalid member index" in excinfo.exconly()
Beispiel #6
0
def tagged_members(
    obj: Atom, meta: Optional[str] = None, meta_value: Any = None
) -> Dict[str, Member]:
    """Utility function to retrieve tagged members from an object

    Parameters
    ----------
    obj : Atom
        Object from which the tagged members should be retrieved.

    meta : str, optional
        The tag to look for, only member which has this tag will be returned

    meta_value : optional
        The value of the metadata used for filtering the members returned

    Returns
    -------
    tagged_members : dict(str, Member)
        Dictionary of the members whose metadatas corresponds to the predicate

    """
    members = obj.members()
    if meta is None and meta_value is None:
        return members
    elif meta_value is None:
        return {
            key: member
            for key, member in members.items()
            if member.metadata is not None and meta in member.metadata
        }
    else:
        return {
            key: member
            for key, member in members.items()
            if member.metadata is not None
            and meta in member.metadata
            and member.metadata[meta] == meta_value
        }
Beispiel #7
0
 def __init__(self, root, attr, **kwargs):
     kwargs['__id__'] = root.getId()
     kwargs['__prefix__'] = attr + "."
     Atom.__init__(self, **kwargs)
Beispiel #8
0
 def __init__(self, root, attr, **kwargs):
     kwargs["__id__"] = root.getId()
     kwargs["__prefix__"] = f"{attr}."
     Atom.__init__(self, **kwargs)
Beispiel #9
0
                IOLoop.current().add_future(
                    future, lambda future: callback(future.result()))
            return future

        return wrapper

    if args and kwargs:
        raise ValueError("cannot combine positional and keyword args")
    if len(args) == 1:
        return run_on_executor_decorator(args[0])
    elif len(args) != 0:
        raise ValueError("expected 1 argument, got %d", len(args))
    return run_on_executor_decorator


_NO_RESULT = Atom()


def return_future(f):
    """Decorator to make a function that returns via callback return a
    `Future`.

    The wrapped function should take a ``callback`` keyword argument
    and invoke it with one argument when it has finished.  To signal failure,
    the function can simply raise an exception (which will be
    captured by the `.StackContext` and passed along to the ``Future``).

    From the caller's perspective, the callback argument is optional.
    If one is given, it will be invoked when the function is complete
    with `Future.result()` as an argument.  If the function fails, the
    callback will not be run and an exception will be raised into the