File: test_validation.py

package info (click to toggle)
python-gql 4.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,900 kB
  • sloc: python: 21,677; makefile: 54
file content (262 lines) | stat: -rw-r--r-- 5,646 bytes parent folder | download
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
import copy

import pytest

from gql import Client, gql

from .schema import StarWarsIntrospection, StarWarsSchema


@pytest.fixture
def local_schema():
    return Client(schema=StarWarsSchema)


@pytest.fixture
def typedef_schema():
    return Client(
        schema="""
schema {
  query: Query
}

interface Character {
  appearsIn: [Episode]
  friends: [Character]
  id: String!
  name: String
}

type Droid implements Character {
  appearsIn: [Episode]
  friends: [Character]
  id: String!
  name: String
  primaryFunction: String
}

enum Episode {
  EMPIRE
  JEDI
  NEWHOPE
}

type Human implements Character {
  appearsIn: [Episode]
  friends: [Character]
  homePlanet: String
  id: String!
  name: String
}

type Query {
  droid(id: String!): Droid
  hero(episode: Episode): Character
  human(id: String!): Human
}"""
    )


@pytest.fixture
def introspection_schema():
    return Client(introspection=StarWarsIntrospection)


@pytest.fixture
def introspection_schema_empty_directives():
    # Create a deep copy to avoid modifying the original
    introspection = copy.deepcopy(StarWarsIntrospection)

    # Simulate an empty dictionary for directives
    introspection["__schema"]["directives"] = []

    return Client(introspection=introspection)


@pytest.fixture
def introspection_schema_no_directives():
    # Create a deep copy to avoid modifying the original
    introspection = copy.deepcopy(StarWarsIntrospection)

    # Simulate no directives key
    del introspection["__schema"]["directives"]  # type: ignore

    return Client(introspection=introspection)


@pytest.fixture(
    params=[
        "local_schema",
        "typedef_schema",
        "introspection_schema",
        "introspection_schema_empty_directives",
        "introspection_schema_no_directives",
    ]
)
def client(request):
    return request.getfixturevalue(request.param)


def validation_errors(client, query):
    query = gql(query)
    try:
        client.validate(query)
        return False
    except Exception:
        return True


def test_incompatible_request_gql(client):
    with pytest.raises(TypeError):
        gql(123)  # type: ignore

    """
    The error generated depends on graphql-core version
    < 3.1.5: "body must be a string"
    >= 3.1.5: some variation of "object of type 'int' has no len()"
              depending on the python environment

    So we are not going to check the exact error message here anymore.
    """

    """
    assert ("body must be a string" in str(exc_info.value)) or (
        "object of type 'int' has no len()" in str(exc_info.value)
    )
    """


def test_nested_query_with_fragment(client):
    query = """
        query NestedQueryWithFragment {
          hero {
            ...NameAndAppearances
            friends {
              ...NameAndAppearances
              friends {
                ...NameAndAppearances
              }
            }
          }
        }
        fragment NameAndAppearances on Character {
          name
          appearsIn
        }
    """
    assert not validation_errors(client, query)


def test_non_existent_fields(client):
    query = """
        query HeroSpaceshipQuery {
          hero {
            favoriteSpaceship
          }
        }
    """
    assert validation_errors(client, query)


def test_require_fields_on_object(client):
    query = """
        query HeroNoFieldsQuery {
          hero
        }
    """
    assert validation_errors(client, query)


def test_disallows_fields_on_scalars(client):
    query = """
        query HeroFieldsOnScalarQuery {
          hero {
            name {
              firstCharacterOfName
            }
          }
        }
    """
    assert validation_errors(client, query)


def test_disallows_object_fields_on_interfaces(client):
    query = """
        query DroidFieldOnCharacter {
          hero {
            name
            primaryFunction
          }
        }
    """
    assert validation_errors(client, query)


def test_allows_object_fields_in_fragments(client):
    query = """
        query DroidFieldInFragment {
          hero {
            name
            ...DroidFields
          }
        }
        fragment DroidFields on Droid {
          primaryFunction
        }
    """
    assert not validation_errors(client, query)


def test_allows_object_fields_in_inline_fragments(client):
    query = """
        query DroidFieldInFragment {
          hero {
            name
            ... on Droid {
              primaryFunction
            }
          }
        }
    """
    assert not validation_errors(client, query)


def test_include_directive(client):
    query = """
        query fetchHero($with_friends: Boolean!) {
          hero {
            name
            friends @include(if: $with_friends) {
                name
            }
          }
        }
    """
    assert not validation_errors(client, query)


def test_skip_directive(client):
    query = """
        query fetchHero($without_friends: Boolean!) {
          hero {
            name
            friends @skip(if: $without_friends) {
                name
            }
          }
        }
    """
    assert not validation_errors(client, query)


def test_build_client_schema_invalid_introspection():
    from gql.utilities import build_client_schema

    with pytest.raises(TypeError) as exc_info:
        build_client_schema("blah")  # type: ignore

    assert (
        "Invalid or incomplete introspection result. Ensure that you are passing the "
        "'data' attribute of an introspection response and no 'errors' were returned "
        "alongside: 'blah'."
    ) in str(exc_info.value)