Пример #1
0
    def __init__(self, func, **kwargs):
        from xoutil.objects import smart_copy

        hash(func)  # Fail if func is not hashable
        self.func = func
        smart_copy(
            kwargs, self.__dict__, defaults={"require_registry": True, "sender": None}
        )
Пример #2
0
def test_smart_copy_with_defaults():
    defaults = {'host': 'localhost', 'port': 5432, 'user': '******',
                'password': (KeyError, '{key}')}
    kwargs = {'password': '******'}
    args = smart_copy(kwargs, {}, defaults=defaults)
    assert args == dict(host='localhost', port=5432, user='******',
                        password='******')

    # if missing a required key
    with pytest.raises(KeyError):
        args = smart_copy({}, {}, defaults=defaults)
Пример #3
0
def test_smart_copy_with_callable_default():
    def default(attr, source=None):
        return attr in ('a', 'b')

    c = dict(a=1, b='2', c='3x')
    d = {}
    smart_copy(c, d, defaults=default)
    assert d == dict(a=1, b='2')

    class inset(object):
        def __init__(self, items):
            self.items = items

        def __call__(self, attr, source=None):
            return attr in self.items

    c = dict(a=1, b='2', c='3x')
    d = {}
    smart_copy(c, d, defaults=inset('ab'))
    assert d == dict(a=1, b='2')
Пример #4
0
def test_smart_copy():
    class new(object):
        def __init__(self, **kw):
            for k, v in kw.items():
                setattr(self, k, v)

    source = new(a=1, b=2, c=4, _d=5)
    target = {}
    smart_copy(source, target, defaults=False)
    assert target == dict(a=1, b=2, c=4)

    source = new(a=1, b=2, c=4, _d=5)
    target = {}
    smart_copy(source, target, defaults=None)
    assert target == dict(a=1, b=2, c=4)

    target = {}
    smart_copy(source, target, defaults=True)
    assert target['_d'] == 5
Пример #5
0
def test_smart_copy_with_plain_defaults():
    c = dict(a=1, b=2, c=3)
    d = {}
    smart_copy(c, d, defaults=('a', 'x'))
    assert d == dict(a=1, x=None)
Пример #6
0
def test_smart_copy_from_dict_to_dict():
    c = dict(c=1, d=23)
    d = dict(d=1)
    smart_copy(c, d)
    assert d == dict(c=1, d=23)
Пример #7
0
def test_smart_copy_signature():
    with pytest.raises(TypeError):
        smart_copy({}, defaults=False)