Example #1
0
def test_indexing(smap):
    """Test using indexing for get and set operations."""
    assert smap["a"] == 1
    smap["a"] = 2
    assert smap["a"] == 2

    with pytest.raises(KeyError):
        smap[1]
    with pytest.raises(KeyError):
        sortedmap()[1]
Example #2
0
def test_indexing(smap):
    """Test using indexing for get and set operations.

    """
    assert smap['a'] == 1
    smap['a'] = 2
    assert smap['a'] == 2

    with pytest.raises(KeyError):
        smap[1]
    with pytest.raises(KeyError):
        sortedmap()[1]
Example #3
0
def test_dynamic_scope_creation():
    """Test handling bad arguments when creating dnamic scope.

    """
    owner = object()
    locs = sortedmap()
    globs = {}
    builtins = {}
    change = {}
    tracer = object()

    dynamicscope = DynamicScope(owner, locs, globs, builtins, change, tracer)
    for referrent, obj in zip(gc.get_referents(dynamicscope),
                              [owner, change, tracer, locs, globs, builtins,
                               None, None]):
        assert referrent is obj

    with pytest.raises(TypeError) as excinfo:
        DynamicScope(owner, None, globs, builtins)
    assert 'mapping' in excinfo.exconly()

    with pytest.raises(TypeError) as excinfo:
        DynamicScope(owner, locs, None, builtins)
    assert 'dict' in excinfo.exconly()

    with pytest.raises(TypeError) as excinfo:
        DynamicScope(owner, locs, globs, None)
    assert 'dict' in excinfo.exconly()

    del dynamicscope
    gc.collect()
def new_scope(key, seed=None):
    """ Create a new scope mapping and push it onto the stack.

    The currently active scope can be retrieved with 'peek_scope' and
    a specific scope can be retrieved with 'fetch_scope'.

    Parameters
    ----------
    key : object
        The scope key to associate with this local scope.

    seed : sortedmap, optional
        The seed map values for creating the scope.

    Returns
    -------
    result : contextmanager
        A contextmanager which will pop the scope after the context
        exits. It yields the new scope as the context variable.

    """
    if seed is not None:
        scope = seed.copy()
    else:
        scope = sortedmap()
    __map[key] = scope
    __stack.append(scope)
    yield scope
    __stack.pop()
    del __map[key]
Example #5
0
def new_scope(key, seed=None):
    """ Create a new scope mapping and push it onto the stack.

    The currently active scope can be retrieved with 'peek_scope' and
    a specific scope can be retrieved with 'fetch_scope'.

    Parameters
    ----------
    key : object
        The scope key to associate with this local scope.

    seed : sortedmap, optional
        The seed map values for creating the scope.

    Returns
    -------
    result : contextmanager
        A contextmanager which will pop the scope after the context
        exits. It yields the new scope as the context variable.

    """
    if seed is not None:
        scope = seed.copy()
    else:
        scope = sortedmap()
    __map[key] = scope
    __stack.append(scope)
    yield scope
    __stack.pop()
    del __map[key]
Example #6
0
def test_dynamic_scope_creation():
    """Test handling bad arguments when creating dnamic scope.

    """
    owner = object()
    locs = sortedmap()
    globs = {}
    builtins = {}
    change = {}
    tracer = object()

    dynamicscope = DynamicScope(owner, locs, globs, builtins, change, tracer)
    for referrent, obj in zip(
            gc.get_referents(dynamicscope),
        [owner, change, tracer, locs, globs, builtins, None, None]):
        assert referrent is obj

    with pytest.raises(TypeError) as excinfo:
        DynamicScope(owner, None, globs, builtins)
    assert 'mapping' in excinfo.exconly()

    with pytest.raises(TypeError) as excinfo:
        DynamicScope(owner, locs, None, builtins)
    assert 'dict' in excinfo.exconly()

    with pytest.raises(TypeError) as excinfo:
        DynamicScope(owner, locs, globs, None)
    assert 'dict' in excinfo.exconly()

    del dynamicscope
    gc.collect()
Example #7
0
def smap():
    """Sortedmap used for testing."""
    smap = sortedmap()
    smap["a"] = 1
    smap["b"] = 2
    smap["c"] = 3
    return smap
    def update_id_nodes(self):
        """ Update the id nodes for this node.

        """
        mapping = sortedmap()
        if self.identifier:
            mapping[self.identifier] = self
        super(DeclarativeNode, self).update_id_nodes(mapping)
Example #9
0
    def update_id_nodes(self):
        """ Update the id nodes for this node.

        """
        mapping = sortedmap()
        if self.identifier:
            mapping[self.identifier] = self
        super(DeclarativeNode, self).update_id_nodes(mapping)
Example #10
0
def smap():
    """Sortedmap used for testing.

    """
    smap = sortedmap()
    smap['a'] = 1
    smap['b'] = 2
    smap['c'] = 3
    return smap
def smap():
    """Sortedmap used for testing.

    """
    smap = sortedmap()
    smap['a'] = 1
    smap['b'] = 2
    smap['c'] = 3
    return smap
Example #12
0
def test_deleting_keys(smap):
    """Test deleting items."""
    del smap["c"]
    assert smap.keys() == ["a", "b"]

    with pytest.raises(KeyError):
        del smap[1]
    with pytest.raises(KeyError):
        del sortedmap()[1]
Example #13
0
    def __call__(cls, parent=None, **kwargs):
        """ A custom instance creation routine for EnamlDef classes.

        """
        self = cls.__new__(cls)
        for node in cls.__constructs__:
            node.populate(self, node, sortedmap())
        self.__init__(parent, **kwargs)
        return self
def test_ordering_with_inhomogeneous(smap):
    """Test the ordering of the map.

    """
    smap['d'] = 4
    assert [k for k in smap.keys()] == ['a', 'b', 'c', 'd']

    smap['0'] = 4
    assert [k for k in smap.keys()] == ['0', 'a', 'b', 'c', 'd']

    smap[1] = 4
    assert [k for k in smap.keys()] == [1, '0', 'a', 'b', 'c', 'd']

    # Test ordering None, which is smaller than anything
    s = sortedmap()
    s[1] = 1
    s[None] = 1
    assert [k for k in s.keys()] == [None, 1]

    s = sortedmap()
    s[None] = 1
    s[1] = 1
    assert [k for k in s.keys()] == [None, 1]

    # Test ordering class that cannot be ordered through the usual mean
    class T:
        pass

    t1 = T()
    t2 = T()
    oT = T

    class T:
        pass

    u = T()
    s = sortedmap()
    s[t1] = 1
    s[t2] = 1
    assert [k for k in s.keys()] == [t1, t2] if id(t1) < id(t2) else [t2, t1]
    s[u] = 1
    assert [k for k in s.keys()
            ][0] is u if id(T) < id(oT) else [k for k in s.keys()][-1] is u
Example #15
0
def test_sortedmap():
    """Test sortedmap methods and protocols.

    """
    smap = sortedmap()
    smap['a'] = 1
    smap['b'] = 2
    smap['c'] = 3
    assert 'a' in smap

    # Test get method
    assert smap.get('a') == 1
    assert smap.get('d') is None
    assert smap.get('e', 4) == 4

    # Test that we get the keys and values in the proper order
    assert smap.keys() == ['a', 'b', 'c']
    assert smap.values() == [1, 2, 3]
    assert smap.items() == [('a', 1), ('b', 2), ('c', 3)]

    # Test popping a key and check the order
    assert smap.pop('b') == 2
    assert smap.pop('b', 1) == 1
    assert smap.keys() == ['a', 'c']

    # Test iterating and checking the order
    # XXX should sortedmap support iteration
    smap['d'] = 4
    assert [k for k in smap.keys()] == ['a', 'c', 'd']

    # Test the repr
    assert "sortedmap" in repr(smap)
    # XXX fails because we need the repr of strings
    #    assert eval(repr(smap)) == smap

    # Test deleting a key
    del smap['c']
    assert smap.keys() == ['a', 'd']

    # Test copying
    csmap = smap.copy()
    assert csmap is not smap
    assert csmap.keys() == smap.keys()
    assert csmap.values() == smap.values()
    assert csmap.items() == smap.items()
    # XXX fail because sortedmap does not implement richcompare
    #    assert csmap == smap

    # Test sizeof
    smap.__sizeof__()

    # Test clear
    smap.clear()
    assert not smap
def test_deleting_keys(smap):
    """Test deleting items.

    """
    del smap['c']
    assert smap.keys() == ['a', 'b']

    with pytest.raises(KeyError):
        del smap[1]
    with pytest.raises(KeyError):
        del sortedmap()[1]
Example #17
0
def test_deleting_keys(smap):
    """Test deleting items.

    """
    del smap['c']
    assert smap.keys() == ['a', 'b']

    with pytest.raises(KeyError):
        del smap[1]
    with pytest.raises(KeyError):
        del sortedmap()[1]
Example #18
0
File: looper.py Project: ylwb/enaml
    def refresh_items(self):
        """ Refresh the items of the pattern.

        This method destroys the old items and creates and initializes
        the new items.

        """
        old_items = self.items[:]
        old_iter_data = self._iter_data
        iterable = self.iterable
        pattern_nodes = self.pattern_nodes
        new_iter_data = sortedmap()
        new_items = []

        if iterable is not None and len(pattern_nodes) > 0:
            for loop_index, loop_item in enumerate(iterable):
                iter_data = old_iter_data.get(loop_item)
                if iter_data is not None:
                    new_iter_data[loop_item] = iter_data
                    iteration = iter_data.nodes
                    new_items.append(iteration)
                    old_items.remove(iteration)
                    iter_data.index = loop_index
                    continue
                iter_data = Iteration(index=loop_index, item=loop_item)
                iteration = iter_data.nodes
                new_iter_data[loop_item] = iter_data
                new_items.append(iteration)
                for nodes, key, f_locals in pattern_nodes:
                    with new_scope(key, f_locals) as f_locals:
                        # Retain for compatibility reasons
                        f_locals['loop_index'] = loop_index
                        f_locals['loop_item'] = loop_item
                        f_locals['loop'] = iter_data
                        for node in nodes:
                            child = node(None)
                            if isinstance(child, list):
                                iteration.extend(child)
                            else:
                                iteration.append(child)

        for iteration in old_items:
            for old in iteration:
                if not old.is_destroyed:
                    old.destroy()

        if len(new_items) > 0:
            expanded = []
            recursive_expand(sum(new_items, []), expanded)
            self.parent.insert_children(self, expanded)

        self.items = new_items
        self._iter_data = new_iter_data
Example #19
0
    def resolve(self, headers):
        """ Resolve the item map for the given headers.

        """
        items = {}
        for item in self.items():
            items[item.name] = item
        item_map = self.item_map = sortedmap()
        for header in headers:
            item = items.get(header.name)
            if item is not None:
                item_map[header] = item
Example #20
0
    def copy(self):
        """ Create a copy of the expression engine.

        Returns
        -------
        result : ExpressionEngine
            A copy of the engine with independent handler sets.

        """
        new = ExpressionEngine()
        handlers = sortedmap()
        for key, value in self._handlers.items():
            handlers[key] = value.copy()
        new._handlers = handlers
        return new
Example #21
0
    def copy(self):
        """ Create a copy of the expression engine.

        Returns
        -------
        result : ExpressionEngine
            A copy of the engine with independent handler sets.

        """
        new = ExpressionEngine()
        handlers = sortedmap()
        for key, value in list(self._handlers.items()):
            handlers[key] = value.copy()
        new._handlers = handlers
        return new
Example #22
0
    def refresh_items(self):
        """ Refresh the items of the pattern.

        This method destroys the old items and creates and initializes
        the new items.

        """
        old_items = self.items[:]
        old_iter_data = self._iter_data
        iterable = self.iterable
        pattern_nodes = self.pattern_nodes
        new_iter_data = sortedmap()
        new_items = []

        if iterable and len(pattern_nodes) > 0:
            for loop_index, loop_item in enumerate(iterable):
                iteration = old_iter_data.get(loop_item)
                if iteration is not None:
                    new_iter_data[loop_item] = iteration
                    new_items.append(iteration)
                    old_items.remove(iteration)
                    continue
                iteration = []
                new_iter_data[loop_item] = iteration
                new_items.append(iteration)
                for nodes, f_locals in pattern_nodes:
                    with new_scope(f_locals) as f_locals:
                        f_locals['loop_index'] = loop_index
                        f_locals['loop_item'] = loop_item
                        for node in nodes:
                            child = node(None)
                            if isinstance(child, list):
                                iteration.extend(child)
                            else:
                                iteration.append(child)

        for iteration in old_items:
            for old in iteration:
                if not old.is_destroyed:
                    old.destroy()

        if len(new_items) > 0:
            expanded = []
            recursive_expand(sum(new_items, []), expanded)
            self.parent.insert_children(self, expanded)

        self.items = new_items
        self._iter_data = new_iter_data
Example #23
0
def test_handling_bad_arguments():
    """Test handling bad arguments to sortedmap methods.

    """
    smap = sortedmap()
    # Test bad parameters for get
    with pytest.raises(TypeError):
        smap.get()
    with pytest.raises(TypeError):
        smap.get('r', None, None)

    # Test bad parameters for pop
    with pytest.raises(TypeError):
        smap.pop()
    with pytest.raises(TypeError):
        smap.pop(None, None, None)
Example #24
0
def test_sortedmap_init():
    """Test initializing a sortedmap."""
    smap = sortedmap({})
    assert smap.items() == []
    smap = sortedmap([(1, 2)])
    assert smap.items() == [(1, 2)]
    smap = sortedmap({1: 2})
    assert smap.items() == [(1, 2)]

    with pytest.raises(TypeError):
        sortedmap(1)
    with pytest.raises(TypeError) as excinfo:
        sortedmap([1])
    assert "pairs" in excinfo.exconly()
Example #25
0
def test_sortedmap_init():
    """Test initializing a sortedmap.

    """
    smap = sortedmap({})
    assert smap.items() == []
    smap = sortedmap([(1, 2)])
    assert smap.items() == [(1, 2)]
    smap = sortedmap({1: 2})
    assert smap.items() == [(1, 2)]

    with pytest.raises(TypeError):
        sortedmap(1)
    with pytest.raises(TypeError) as excinfo:
        sortedmap([1])
    assert 'pairs' in excinfo.exconly()
Example #26
0
    def _refresh_items(self):
        """ A private method which refreshes the loop items.

        This method destroys the old items and creates and initializes
        the new items.

        """
        old_items = self.items[:]
        old_idata = self._idata
        iterable = self.iterable
        cdata = self._cdata
        new_idata = sortedmap()
        new_items = []

        if iterable and len(cdata) > 0:
            for loop_index, loop_item in enumerate(iterable):
                iteration = old_idata.get(loop_item)
                if iteration is not None:
                    new_idata[loop_item] = iteration
                    new_items.append(iteration)
                    old_items.remove(iteration)
                    continue
                iteration = []
                new_idata[loop_item] = iteration
                new_items.append(iteration)
                for node, f_locals in cdata:
                    new_locals = f_locals.copy()
                    new_locals['loop_index'] = loop_index
                    new_locals['loop_item'] = loop_item
                    for child_node in node.child_defs:
                        child = child_node.typeclass()
                        child_node.populate(child, child_node, new_locals)
                        iteration.append(child)

        for iteration in old_items:
            for old in iteration:
                if not old.is_destroyed:
                    old.destroy()
        if len(new_items) > 0:
            expanded = []
            _recursive_expand(sum(new_items, []), expanded)
            self.parent.insert_children(self, expanded)
        self.items = new_items
        self._idata = new_idata
def make_template_scope(node, scope_tuple):
    """ Create and add the template scope to a template node.

    Parameters
    ----------
    node : TemplateNode
        The template node for which to create the scope.

    scope_tuple : tuple
        A tuple of alternating key, value pairs representing the
        scope of a template instantiation.

    """
    scope = sortedmap()
    t_iter = iter(scope_tuple)
    for key, value in zip(t_iter, t_iter):
        scope[key] = value
    node.template_scope = scope
    return node
Example #28
0
def test_traverse():
    """Test traversing on deletion."""
    class Holder(Atom):

        smap = Value()

    h = Holder()
    smap = sortedmap()

    # Create a reference cycle
    h.smap = smap
    smap[1] = h

    # Create a weakref to check that the objects involved in teh cycle are
    # collected
    ref = atomref(h)

    del smap, h
    gc.collect()

    assert not ref()
Example #29
0
def add_template_scope(node, names, values):
    """ Create and add the template scope to a template node.

    Parameters
    ----------
    node : TemplateNode
        The template node for which to create the scope.

    scope_tuple : tuple
        A tuple of alternating key, value pairs representing the
        scope of a template instantiation.

    Returns
    -------
    result : sortedmap
        The scope mapping for the given scope tuple.

    """
    scope = sortedmap()
    for name, value in zip(names, values):
        scope[name] = value
    node.scope = scope
Example #30
0
def test_traverse():
    """Test traversing on deletion.

    """

    class Holder(Atom):

        smap = Value()

    h = Holder()
    smap = sortedmap()

    # Create a reference cycle
    h.smap = smap
    smap[1] = h

    # Create a weakref to check that the objects involved in teh cycle are
    # collected
    ref = atomref(h)

    del smap, h
    gc.collect()

    assert not ref()
def new_scope(seed=None):
    """ Create a new scope mapping and push it onto the stack.

    The currently active scope can be retrieved with 'peek_locals'.

    Parameters
    ----------
    seed : sortedmap, optional
        The seed map values for creating the scope.

    Returns
    -------
    result : contextmanager
        A contextmanager which will pop the scope after the context
        exits. It yields the new scope as the context variable.

    """
    if seed is not None:
        scope = seed.copy()
    else:
        scope = sortedmap()
    __stack.append(scope)
    yield scope
    __stack.pop()
Example #32
0
    def update_id_nodes(self):
        """ Update the id nodes for this node.

        """
        super(TemplateNode, self).update_id_nodes(sortedmap())
Example #33
0
def dynamicscope():
    """Dynamic used for testing.

    """

    class NonDataDescriptor(object):

        def __init__(self, should_raise=False):
            self.should_raise = should_raise

        def __get__(self, instance, objtype=None):
            if not self.should_raise:
                return instance
            else:
                raise KeyError()

    class ReadOnlyDescriptor(object):

        def __get__(self, instance, objtype=None):
            return 1

        def __set__(self, instance, objtype=None):
            raise AttributeError

    class WriteOnlyDescriptor(object):

        def __set__(self, instance, value, objtype=None):
            instance.value = 1

    class Owner(object):
        def __init__(self):
            self._parent = None
            self.attribute1 = 1
            self._prop2 = 0

        owner = NonDataDescriptor()

        prop1 = ReadOnlyDescriptor()

        @property
        def prop2(self):
            return self._prop2

        @prop2.setter
        def prop2(self, value):
            self._prop2 = value

        @property
        def key_raise(self):
            raise KeyError()

        non_data_key_raise = NonDataDescriptor(True)

        write_only = WriteOnlyDescriptor()

    class TopOwner(Owner):

        @property
        def top(self):
            return self._top

        @top.setter
        def top(self, value):
            self._top = 1

    class Tracer(object):
        """Tracer for testing.

        """
        def __init__(self):
            self.traced = []

        def dynamic_load(self, owner, name, value):
            self.traced.append((owner, name, value))

    owner = Owner()
    owner.attribute1 = 2
    owner._parent = TopOwner()
    owner._parent.attribute2 = 1
    locs = sortedmap()
    locs['a'] = 1
    globs = {'b': 2}
    builtins = {'c': 3}
    change = {'d': 4}
    tracer = Tracer()
    dynamicscope = DynamicScope(owner, locs, globs, builtins, change, tracer)
    dynamicscope['e'] = 5  # Add an entry in the f_writes

    return dynamicscope, (owner, locs, globs, builtins, change, tracer)
Example #34
0
def dynamicscope():
    """Dynamic used for testing.

    """
    class NonDataDescriptor(object):
        def __init__(self, should_raise=False):
            self.should_raise = should_raise

        def __get__(self, instance, objtype=None):
            if not self.should_raise:
                return instance
            else:
                raise KeyError()

    class ReadOnlyDescriptor(object):
        def __get__(self, instance, objtype=None):
            return 1

        def __set__(self, instance, objtype=None):
            raise AttributeError

    class WriteOnlyDescriptor(object):
        def __set__(self, instance, value, objtype=None):
            instance.value = 1

    class Owner(object):
        def __init__(self):
            self._parent = None
            self.attribute1 = 1
            self._prop2 = 0

        owner = NonDataDescriptor()

        prop1 = ReadOnlyDescriptor()

        @property
        def prop2(self):
            return self._prop2

        @prop2.setter
        def prop2(self, value):
            self._prop2 = value

        @property
        def key_raise(self):
            raise KeyError()

        non_data_key_raise = NonDataDescriptor(True)

        write_only = WriteOnlyDescriptor()

    class TopOwner(Owner):
        @property
        def top(self):
            return self._top

        @top.setter
        def top(self, value):
            self._top = 1

    class Tracer(object):
        """Tracer for testing.

        """
        def __init__(self):
            self.traced = []

        def dynamic_load(self, owner, name, value):
            self.traced.append((owner, name, value))

    owner = Owner()
    owner.attribute1 = 2
    owner._parent = TopOwner()
    owner._parent.attribute2 = 1
    locs = sortedmap()
    locs['a'] = 1
    globs = {'b': 2}
    builtins = {'c': 3}
    change = {'d': 4}
    tracer = Tracer()
    dynamicscope = DynamicScope(owner, locs, globs, builtins, change, tracer)
    dynamicscope['e'] = 5  # Add an entry in the f_writes

    return dynamicscope, (owner, locs, globs, builtins, change, tracer)
Example #35
0
    def update_id_nodes(self):
        """ Update the id nodes for this node.

        """
        super(TemplateNode, self).update_id_nodes(sortedmap())
Example #36
0
    def __init__(self, binding):
        """ Initialize a subscription operator.

        """
        super(OpSubscribe, self).__init__(binding)
        self.observers = sortedmap()
Example #37
0
 def __init__(self, binding):
     super(OpSubscribe, self).__init__(binding)
     self.observers = sortedmap()