File: test_datetime.py

package info (click to toggle)
python-gql 4.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,900 kB
  • sloc: python: 21,677; makefile: 54
file content (219 lines) | stat: -rw-r--r-- 5,730 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
from datetime import datetime, timedelta
from typing import Any, Dict, Optional

from graphql.error import GraphQLError
from graphql.language import ValueNode
from graphql.pyutils import inspect
from graphql.type import (
    GraphQLArgument,
    GraphQLField,
    GraphQLInputField,
    GraphQLInputObjectType,
    GraphQLInt,
    GraphQLList,
    GraphQLObjectType,
    GraphQLScalarType,
    GraphQLSchema,
)
from graphql.utilities import value_from_ast_untyped

from gql import Client, gql


def serialize_datetime(value: Any) -> str:
    if not isinstance(value, datetime):
        raise GraphQLError("Cannot serialize datetime value: " + inspect(value))
    return value.isoformat()


def parse_datetime_value(value: Any) -> datetime:

    if isinstance(value, str):
        try:
            # Note: a more solid custom scalar should use dateutil.parser.isoparse
            #       Not using it here in the test to avoid adding another dependency
            return datetime.fromisoformat(value)
        except Exception:
            raise GraphQLError("Cannot parse datetime value : " + inspect(value))

    else:
        raise GraphQLError("Cannot parse datetime value: " + inspect(value))


def parse_datetime_literal(
    value_node: ValueNode, variables: Optional[Dict[str, Any]] = None
) -> datetime:
    ast_value = value_from_ast_untyped(value_node, variables)
    if not isinstance(ast_value, str):
        raise GraphQLError("Cannot parse literal datetime value: " + inspect(ast_value))

    return parse_datetime_value(ast_value)


DatetimeScalar = GraphQLScalarType(
    name="Datetime",
    serialize=serialize_datetime,
    parse_value=parse_datetime_value,
    parse_literal=parse_datetime_literal,
)


def resolve_shift_days(root, _info, time, days):
    return time + timedelta(days=days)


def resolve_latest(root, _info, times):
    return max(times)


def resolve_seconds(root, _info, interval):
    print(f"interval={interval!r}")
    return (interval["end"] - interval["start"]).total_seconds()


IntervalInputType = GraphQLInputObjectType(
    "IntervalInput",
    fields={
        "start": GraphQLInputField(
            DatetimeScalar,
            default_value=datetime(2021, 11, 12, 11, 58, 13, 461161),
        ),
        "end": GraphQLInputField(DatetimeScalar),
    },
)

queryType = GraphQLObjectType(
    name="RootQueryType",
    fields={
        "shiftDays": GraphQLField(
            DatetimeScalar,
            args={
                "time": GraphQLArgument(DatetimeScalar),
                "days": GraphQLArgument(GraphQLInt),
            },
            resolve=resolve_shift_days,
        ),
        "latest": GraphQLField(
            DatetimeScalar,
            args={"times": GraphQLArgument(GraphQLList(DatetimeScalar))},
            resolve=resolve_latest,
        ),
        "seconds": GraphQLField(
            GraphQLInt,
            args={"interval": GraphQLArgument(IntervalInputType)},
            resolve=resolve_seconds,
        ),
    },
)

schema = GraphQLSchema(query=queryType)


def test_shift_days():

    client = Client(schema=schema, parse_results=True, serialize_variables=True)

    now = datetime.fromisoformat("2021-11-12T11:58:13.461161")

    query = gql("query shift5days($time: Datetime) {shiftDays(time: $time, days: 5)}")

    query.variable_values = {
        "time": now,
    }

    result = client.execute(query)

    print(result)

    assert result["shiftDays"] == datetime.fromisoformat("2021-11-17T11:58:13.461161")


def test_shift_days_serialized_manually_in_query():

    client = Client(schema=schema)

    query = gql(
        """{
        shiftDays(time: "2021-11-12T11:58:13.461161", days: 5)
    }"""
    )

    result = client.execute(query, parse_result=True)

    print(result)

    assert result["shiftDays"] == datetime.fromisoformat("2021-11-17T11:58:13.461161")


def test_shift_days_serialized_manually_in_variables():

    client = Client(schema=schema, parse_results=True)

    query = gql("query shift5days($time: Datetime) {shiftDays(time: $time, days: 5)}")

    query.variable_values = {
        "time": "2021-11-12T11:58:13.461161",
    }

    result = client.execute(query)

    print(result)

    assert result["shiftDays"] == datetime.fromisoformat("2021-11-17T11:58:13.461161")


def test_latest():

    client = Client(schema=schema, parse_results=True)

    now = datetime.fromisoformat("2021-11-12T11:58:13.461161")
    in_five_days = datetime.fromisoformat("2021-11-17T11:58:13.461161")

    query = gql("query latest($times: [Datetime!]!) {latest(times: $times)}")

    query.variable_values = {
        "times": [now, in_five_days],
    }

    result = client.execute(query, serialize_variables=True)

    print(result)

    assert result["latest"] == in_five_days


def test_seconds():
    client = Client(schema=schema)

    now = datetime.fromisoformat("2021-11-12T11:58:13.461161")
    in_five_days = datetime.fromisoformat("2021-11-17T11:58:13.461161")

    query = gql(
        "query seconds($interval: IntervalInput) {seconds(interval: $interval)}"
    )

    query.variable_values = {"interval": {"start": now, "end": in_five_days}}

    result = client.execute(query, serialize_variables=True)

    print(result)

    assert result["seconds"] == 432000


def test_seconds_omit_optional_start_argument():
    client = Client(schema=schema)

    in_five_days = datetime.fromisoformat("2021-11-17T11:58:13.461161")

    query = gql(
        "query seconds($interval: IntervalInput) {seconds(interval: $interval)}"
    )

    query.variable_values = {"interval": {"end": in_five_days}}

    result = client.execute(query, serialize_variables=True)

    print(result)

    assert result["seconds"] == 432000