Exemple #1
0
def test_freeze():
    collection = {
        '1': 1,
        'list': [2, 3, 4],
        'tuple': (5, 6),
        'set': {7, 8},
        'dict': {
            '7': 9,
            '8': (10, 11),
        },
        (1, 2): 'an iterable key',
        frozendict(some='value'): 'a structured key',
    }
    assert freeze(collection) == frozendict({
        '1':
        1,
        'list': (2, 3, 4),
        'tuple': (5, 6),
        'set':
        frozenset({8, 7}),
        'dict':
        frozendict({
            '7': 9,
            '8': (10, 11)
        }),
        (1, 2):
        'an iterable key',
        frozendict({'some': 'value'}):
        'a structured key'
    })
    def any(self, cond):
        # type: (Union[Predicate, Iterable]) -> Predicate
        """
        Checks if a condition is met by any element in a list,
        where a condition can also be a sequence (e.g. list).
        >>> var('f1').any(var('f2').exists())
        Matches::
            {'f1': [{'f2': 1}, {'f2': 0}]}
        >>> var('f1').any([1, 2, 3])
        # Match f1 that contains any element from [1, 2, 3]
        Matches::
            {'f1': [1, 2]}
            {'f1': [3, 4, 5]}

        :param cond: Either a Predicate that at least one element has to match
         or a list of which at least one element has to be contained
         in the tested element.
-        """
        if callable(cond):

            def _cmp(value):
                return is_iterable(value) and any(cond(e) for e in value)

        else:

            def _cmp(value):
                return is_iterable(value) and any(e in cond for e in value)

        return self._build_predicate(lambda lhs, value: _cmp(lhs),
                                     Operation.ANY, (self._path, freeze(cond)))
Exemple #3
0
    def all(self, cond: t.Union[Predicate, t.Iterable]) -> Predicate:
        """
        Checks if a condition is met by any element in a list,
        where a condition can also be a sequence (e.g. list).
        >>> var('f1').all(var('f2').exists())
        Matches::
            {'f1': [{'f2': 1}, {'f2': 1}]}
        >>> var('f1').all([1, 2, 3])
        # Match f1 that contains any element from [1, 2, 3]
        Matches::
            {'f1': [1, 2, 3, 4, 5]}

        :param cond: Either a Predicate that all elements have to match or
         a list which has to be contained in the tested element.
        """
        if callable(cond):
            def _cmp(value):
                return is_iterable(value) and all(cond(e) for e in value)

        else:
            def _cmp(value):
                return is_iterable(value) and all(e in value for e in cond)

        return self._build_predicate(
            lambda lhs, value: _cmp(lhs),
            Operation.ALL,
            (self._path, freeze(cond))
        )
Exemple #4
0
def test_freeze():
    collection = {
        "1": 1,
        "list": [2, 3, 4],
        "tuple": (5, 6),
        "set": {7, 8},
        "dict": {
            "7": 9,
            "8": (10, 11),
        },
        (1, 2): "an iterable key",
        frozendict(some="value"): "a structured key",
    }
    assert freeze(collection) == frozendict({
        "1":
        1,
        "list": (2, 3, 4),
        "tuple": (5, 6),
        "set":
        frozenset({8, 7}),
        "dict":
        frozendict({
            "7": 9,
            "8": (10, 11)
        }),
        (1, 2):
        "an iterable key",
        frozendict({"some": "value"}):
        "a structured key",
    })
Exemple #5
0
    def all(self, cond: t.Union[Predicate, t.Iterable]) -> Predicate:
        """
        Checks if a condition is met by any element in a list,
        where a condition can also be a sequence (e.g. list).
        >>> var('f1').all(var('f2').exists())
        Matches::
            {'f1': [{'f2': 1}, {'f2': 1}]}
        >>> var('f1').all([1, 2, 3])
        # Match f1 that contains any element from [1, 2, 3]
        Matches::
            {'f1': [1, 2, 3, 4, 5]}

        :param cond: Either a Predicate that all elements have to match or
         a list which has to be contained in the tested element.
        """
        if callable(cond):

            def _cmp(value):
                return is_iterable(value) and all(cond(e) for e in value)

        else:

            def _cmp(value):
                return is_iterable(value) and all(e in value for e in cond)

        return self._build_predicate(lambda lhs, value: _cmp(lhs),
                                     Operation.ALL, (self._path, freeze(cond)))
Exemple #6
0
 def __set__(self, instance: Owner, value: Value) -> None:
     try:
         old_value = instance.__dict__[self._value_key]
     except KeyError:
         instance.__dict__[self._value_key] = freeze(value)
     else:
         if value != old_value:
             __not_supported__(self.name, instance)
Exemple #7
0
    def __eq__(self, rhs: t.Any) -> Predicate:
        """
        Test the value for equality.
        >>> var('f1') == 42

        :param rhs: The value to compare against. It can either be a plain
         value or a Var instance which points to another field on the value
         that will be used during evaluation.
        :returns: A predicate of this comparison.
        """
        rhs_curried = _curry_rhs(rhs)
        return self._build_predicate(
            lambda lhs, value: lhs == rhs_curried(value), Operation.EQ,
            (self._path, freeze(rhs)))
Exemple #8
0
    def __eq__(self, rhs: t.Any) -> Predicate:
        """
        Test the value for equality.
        >>> var('f1') == 42

        :param rhs: The value to compare against. It can either be a plain
         value or a Var instance which points to another field on the value
         that will be used during evaluation.
        :returns: A predicate of this comparison.
        """
        rhs_curried = _curry_rhs(rhs)
        return self._build_predicate(
            lambda lhs, value: lhs == rhs_curried(value),
            Operation.EQ,
            (self._path, freeze(rhs))
        )
Exemple #9
0
    def test(self, func: t.Callable[..., bool], *args, **kwargs) -> Predicate:
        """
        Run a user-defined test function against the value.
        >>> def test_func(val):
        ...     return val == 42
        ...
        >>> var('f1').test(test_func)

        :param func: The function to call, passing the dict as the first
            argument
        :param args:
        :param kwargs:
            Additional arguments to pass to the test function
        """
        return self._build_predicate(
            lambda lhs, value: func(lhs, *args, **kwargs), Operation.TEST,
            (self._path, func, args, freeze(kwargs)))
Exemple #10
0
class ValueClass:
    set = set()
    list = []
    dict = {}
    inner = freeze(Bunch(key=Bunch(inner_key="value")))

    not_set: set

    @property
    def property_simple_value(self):
        return []

    @property
    def property_inner_value(self):
        return Bunch(key=Bunch(inner_key="value"))

    def method(self, arg):
        return arg
Exemple #11
0
    def test(self, func: t.Callable[..., bool], *args, **kwargs) -> Predicate:
        """
        Run a user-defined test function against the value.
        >>> def test_func(val):
        ...     return val == 42
        ...
        >>> var('f1').test(test_func)

        :param func: The function to call, passing the dict as the first
            argument
        :param args:
        :param kwargs:
            Additional arguments to pass to the test function
        """
        return self._build_predicate(
            lambda lhs, value: func(lhs, *args, **kwargs),
            Operation.TEST,
            (self._path, func, args, freeze(kwargs))
        )
Exemple #12
0
def test_frozen_proxy_types():

    frozen = freeze(ValueClass())

    assert type(frozen) is FrozenProxy
    assert type(frozen.set) is frozenset
    assert type(frozen.list) is tuple
    assert type(frozen.dict) is frozendict
    assert type(frozen.property_simple_value) is tuple
    assert type(frozen.method) is FrozenProxy
    assert type(frozen.inner) is FrozenProxy
    assert type(frozen.inner["key"]) is FrozenProxy
    assert type(frozen.inner.key.inner_key) is str
    assert type(frozen.property_inner_value) is FrozenProxy

    method_result = frozen.method([1, set()])
    assert method_result == (1, frozenset())
    assert type(method_result) is tuple
    assert type(method_result[1]) is frozenset
Exemple #13
0
def test_frozen_proxy_setting_the_same_value(setter):
    frozen = freeze(ValueClass())
    with pytest.raises(TypeError):
        setter(frozen)
Exemple #14
0
def test_freeze_set_like(value, expected):
    assert freeze(value) == expected
Exemple #15
0
def test_freeze_sequence(value, expected):
    assert freeze(value) == expected
Exemple #16
0
def test_freeze_immutable(value):
    assert freeze(value) is value
Exemple #17
0
def test_frozen_proxy_setters_raises(setter):
    frozen = freeze(ValueClass())
    with pytest.raises(TypeError):
        setter(frozen)