File: test_custom_global_id.py

package info (click to toggle)
python-graphene 3.4.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,124 kB
  • sloc: python: 8,935; makefile: 212; sh: 18
file content (325 lines) | stat: -rw-r--r-- 10,349 bytes parent folder | download | duplicates (2)
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import re
from uuid import uuid4

from graphql import graphql_sync

from ..id_type import BaseGlobalIDType, SimpleGlobalIDType, UUIDGlobalIDType
from ..node import Node
from ...types import Int, ObjectType, Schema, String


class TestUUIDGlobalID:
    def setup_method(self):
        self.user_list = [
            {"id": uuid4(), "name": "First"},
            {"id": uuid4(), "name": "Second"},
            {"id": uuid4(), "name": "Third"},
            {"id": uuid4(), "name": "Fourth"},
        ]
        self.users = {user["id"]: user for user in self.user_list}

        class CustomNode(Node):
            class Meta:
                global_id_type = UUIDGlobalIDType

        class User(ObjectType):
            class Meta:
                interfaces = [CustomNode]

            name = String()

            @classmethod
            def get_node(cls, _type, _id):
                return self.users[_id]

        class RootQuery(ObjectType):
            user = CustomNode.Field(User)

        self.schema = Schema(query=RootQuery, types=[User])
        self.graphql_schema = self.schema.graphql_schema

    def test_str_schema_correct(self):
        """
        Check that the schema has the expected and custom node interface and user type and that they both use UUIDs
        """
        parsed = re.findall(r"(.+) \{\n\s*([\w\W]*?)\n\}", str(self.schema))
        types = [t for t, f in parsed]
        fields = [f for t, f in parsed]
        custom_node_interface = "interface CustomNode"
        assert custom_node_interface in types
        assert (
            '"""The ID of the object"""\n  id: UUID!'
            == fields[types.index(custom_node_interface)]
        )
        user_type = "type User implements CustomNode"
        assert user_type in types
        assert (
            '"""The ID of the object"""\n  id: UUID!\n  name: String'
            == fields[types.index(user_type)]
        )

    def test_get_by_id(self):
        query = """query userById($id: UUID!) {
            user(id: $id) {
                id
                name
            }
        }"""
        # UUID need to be converted to string for serialization
        result = graphql_sync(
            self.graphql_schema,
            query,
            variable_values={"id": str(self.user_list[0]["id"])},
        )
        assert not result.errors
        assert result.data["user"]["id"] == str(self.user_list[0]["id"])
        assert result.data["user"]["name"] == self.user_list[0]["name"]


class TestSimpleGlobalID:
    def setup_method(self):
        self.user_list = [
            {"id": "my global primary key in clear 1", "name": "First"},
            {"id": "my global primary key in clear 2", "name": "Second"},
            {"id": "my global primary key in clear 3", "name": "Third"},
            {"id": "my global primary key in clear 4", "name": "Fourth"},
        ]
        self.users = {user["id"]: user for user in self.user_list}

        class CustomNode(Node):
            class Meta:
                global_id_type = SimpleGlobalIDType

        class User(ObjectType):
            class Meta:
                interfaces = [CustomNode]

            name = String()

            @classmethod
            def get_node(cls, _type, _id):
                return self.users[_id]

        class RootQuery(ObjectType):
            user = CustomNode.Field(User)

        self.schema = Schema(query=RootQuery, types=[User])
        self.graphql_schema = self.schema.graphql_schema

    def test_str_schema_correct(self):
        """
        Check that the schema has the expected and custom node interface and user type and that they both use UUIDs
        """
        parsed = re.findall(r"(.+) \{\n\s*([\w\W]*?)\n\}", str(self.schema))
        types = [t for t, f in parsed]
        fields = [f for t, f in parsed]
        custom_node_interface = "interface CustomNode"
        assert custom_node_interface in types
        assert (
            '"""The ID of the object"""\n  id: ID!'
            == fields[types.index(custom_node_interface)]
        )
        user_type = "type User implements CustomNode"
        assert user_type in types
        assert (
            '"""The ID of the object"""\n  id: ID!\n  name: String'
            == fields[types.index(user_type)]
        )

    def test_get_by_id(self):
        query = """query {
            user(id: "my global primary key in clear 3") {
                id
                name
            }
        }"""
        result = graphql_sync(self.graphql_schema, query)
        assert not result.errors
        assert result.data["user"]["id"] == self.user_list[2]["id"]
        assert result.data["user"]["name"] == self.user_list[2]["name"]


class TestCustomGlobalID:
    def setup_method(self):
        self.user_list = [
            {"id": 1, "name": "First"},
            {"id": 2, "name": "Second"},
            {"id": 3, "name": "Third"},
            {"id": 4, "name": "Fourth"},
        ]
        self.users = {user["id"]: user for user in self.user_list}

        class CustomGlobalIDType(BaseGlobalIDType):
            """
            Global id that is simply and integer in clear.
            """

            graphene_type = Int

            @classmethod
            def resolve_global_id(cls, info, global_id):
                _type = info.return_type.graphene_type._meta.name
                return _type, global_id

            @classmethod
            def to_global_id(cls, _type, _id):
                return _id

        class CustomNode(Node):
            class Meta:
                global_id_type = CustomGlobalIDType

        class User(ObjectType):
            class Meta:
                interfaces = [CustomNode]

            name = String()

            @classmethod
            def get_node(cls, _type, _id):
                return self.users[_id]

        class RootQuery(ObjectType):
            user = CustomNode.Field(User)

        self.schema = Schema(query=RootQuery, types=[User])
        self.graphql_schema = self.schema.graphql_schema

    def test_str_schema_correct(self):
        """
        Check that the schema has the expected and custom node interface and user type and that they both use UUIDs
        """
        parsed = re.findall(r"(.+) \{\n\s*([\w\W]*?)\n\}", str(self.schema))
        types = [t for t, f in parsed]
        fields = [f for t, f in parsed]
        custom_node_interface = "interface CustomNode"
        assert custom_node_interface in types
        assert (
            '"""The ID of the object"""\n  id: Int!'
            == fields[types.index(custom_node_interface)]
        )
        user_type = "type User implements CustomNode"
        assert user_type in types
        assert (
            '"""The ID of the object"""\n  id: Int!\n  name: String'
            == fields[types.index(user_type)]
        )

    def test_get_by_id(self):
        query = """query {
            user(id: 2) {
                id
                name
            }
        }"""
        result = graphql_sync(self.graphql_schema, query)
        assert not result.errors
        assert result.data["user"]["id"] == self.user_list[1]["id"]
        assert result.data["user"]["name"] == self.user_list[1]["name"]


class TestIncompleteCustomGlobalID:
    def setup_method(self):
        self.user_list = [
            {"id": 1, "name": "First"},
            {"id": 2, "name": "Second"},
            {"id": 3, "name": "Third"},
            {"id": 4, "name": "Fourth"},
        ]
        self.users = {user["id"]: user for user in self.user_list}

    def test_must_define_to_global_id(self):
        """
        Test that if the `to_global_id` method is not defined, we can query the object, but we can't request its ID.
        """

        class CustomGlobalIDType(BaseGlobalIDType):
            graphene_type = Int

            @classmethod
            def resolve_global_id(cls, info, global_id):
                _type = info.return_type.graphene_type._meta.name
                return _type, global_id

        class CustomNode(Node):
            class Meta:
                global_id_type = CustomGlobalIDType

        class User(ObjectType):
            class Meta:
                interfaces = [CustomNode]

            name = String()

            @classmethod
            def get_node(cls, _type, _id):
                return self.users[_id]

        class RootQuery(ObjectType):
            user = CustomNode.Field(User)

        self.schema = Schema(query=RootQuery, types=[User])
        self.graphql_schema = self.schema.graphql_schema

        query = """query {
            user(id: 2) {
                name
            }
        }"""
        result = graphql_sync(self.graphql_schema, query)
        assert not result.errors
        assert result.data["user"]["name"] == self.user_list[1]["name"]

        query = """query {
            user(id: 2) {
                id
                name
            }
        }"""
        result = graphql_sync(self.graphql_schema, query)
        assert result.errors is not None
        assert len(result.errors) == 1
        assert result.errors[0].path == ["user", "id"]

    def test_must_define_resolve_global_id(self):
        """
        Test that if the `resolve_global_id` method is not defined, we can't query the object by ID.
        """

        class CustomGlobalIDType(BaseGlobalIDType):
            graphene_type = Int

            @classmethod
            def to_global_id(cls, _type, _id):
                return _id

        class CustomNode(Node):
            class Meta:
                global_id_type = CustomGlobalIDType

        class User(ObjectType):
            class Meta:
                interfaces = [CustomNode]

            name = String()

            @classmethod
            def get_node(cls, _type, _id):
                return self.users[_id]

        class RootQuery(ObjectType):
            user = CustomNode.Field(User)

        self.schema = Schema(query=RootQuery, types=[User])
        self.graphql_schema = self.schema.graphql_schema

        query = """query {
            user(id: 2) {
                id
                name
            }
        }"""
        result = graphql_sync(self.graphql_schema, query)
        assert result.errors is not None
        assert len(result.errors) == 1
        assert result.errors[0].path == ["user"]