summaryrefslogtreecommitdiff
path: root/tests/functional/m/mapping_context.py
blob: 8dc6b3b72d827ae367c61443641f06f15a1258f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"""
Checks that only valid values are used in a mapping context.
"""
# pylint: disable=missing-docstring,invalid-name,too-few-public-methods,import-error,wrong-import-position,use-dict-literal


def test(**kwargs):
    print(kwargs)


# dictionary value/comprehension
dict_value = dict(a=1, b=2, c=3)
dict_comp = {chr(x): x for x in range(256)}
test(**dict_value)
test(**dict_comp)


# in order to be used in kwargs custom mapping class should define
# __iter__(), __getitem__(key) and keys().
class CustomMapping:
    def __init__(self):
        self.data = dict(a=1, b=2, c=3, d=4, e=5)

    def __getitem__(self, key):
        return self.data[key]

    def keys(self):
        return self.data.keys()

test(**CustomMapping())
test(**CustomMapping)  # [not-a-mapping]

class NotMapping:
    pass

test(**NotMapping())  # [not-a-mapping]

# skip checks if statement is inside mixin/base/abstract class
class SomeMixin:
    kwargs = None

    def get_kwargs(self):
        return self.kwargs

    def run(self, **kwargs):
        print(kwargs)

    def dispatch(self):
        kws = self.get_kwargs()
        self.run(**kws)

class AbstractThing:
    kwargs = None

    def get_kwargs(self):
        return self.kwargs

    def run(self, **kwargs):
        print(kwargs)

    def dispatch(self):
        kws = self.get_kwargs()
        self.run(**kws)

class BaseThing:
    kwargs = None

    def get_kwargs(self):
        return self.kwargs

    def run(self, **kwargs):
        print(kwargs)

    def dispatch(self):
        kws = self.get_kwargs()
        self.run(**kws)

# abstract class
class Thing:
    def get_kwargs(self):
        raise NotImplementedError

    def run(self, **kwargs):
        print(kwargs)

    def dispatch(self):
        kwargs = self.get_kwargs()
        self.run(**kwargs)

# skip uninferable instances
from some_missing_module import Mapping

class MyClass(Mapping):
    pass

test(**MyClass())


class HasDynamicGetattr:

    def __init__(self):
        self._obj = {}

    def __getattr__(self, attr):
        return getattr(self._obj, attr)


test(**HasDynamicGetattr())