forked from dropbox/stone
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_python_type_stubs.py
More file actions
425 lines (334 loc) · 11.8 KB
/
test_python_type_stubs.py
File metadata and controls
425 lines (334 loc) · 11.8 KB
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
from __future__ import absolute_import, division, print_function, unicode_literals
import textwrap
MYPY = False
if MYPY:
import typing # noqa: F401 # pylint: disable=import-error,unused-import,useless-suppression
import unittest
try:
# Works for Py 3.3+
from unittest.mock import Mock
except ImportError:
# See https://github.com/python/mypy/issues/1153#issuecomment-253842414
from mock import Mock # type: ignore
from stone.ir import (
Alias,
Api,
ApiNamespace,
Boolean,
List,
Map,
Nullable,
String,
Struct,
StructField,
Timestamp,
UInt64,
Union,
UnionField,
Void,
Float64)
from stone.ir.api import ApiRoute
from stone.backends.python_type_stubs import PythonTypeStubsBackend
from test.backend_test_util import _mock_emit
ISO_8601_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
def _make_backend():
# type: () -> PythonTypeStubsBackend
return PythonTypeStubsBackend(
target_folder_path=Mock(),
args=Mock()
)
def _make_namespace_with_alias():
# type: (...) -> ApiNamespace
ns = ApiNamespace('ns_with_alias')
struct1 = Struct(name='Struct1', namespace=ns, ast_node=None)
struct1.set_attributes(None, [StructField('f1', Boolean(), None, None)])
ns.add_data_type(struct1)
alias = Alias(name='AliasToStruct1', namespace=ns, ast_node=None)
alias.set_attributes(doc=None, data_type=struct1)
ns.add_alias(alias)
str_type = String(min_length=3)
str_alias = Alias(name='NotUserDefinedAlias', namespace=ns, ast_node=None)
str_alias.set_attributes(doc=None, data_type=str_type)
ns.add_alias(str_alias)
return ns
def _make_namespace_with_many_structs():
# type: (...) -> ApiNamespace
ns = ApiNamespace('ns_with_many_structs')
struct1 = Struct(name='Struct1', namespace=ns, ast_node=None)
struct1.set_attributes(None, [StructField('f1', Boolean(), None, None)])
ns.add_data_type(struct1)
struct2 = Struct(name='Struct2', namespace=ns, ast_node=None)
struct2.set_attributes(
doc=None,
fields=[
StructField('f2', List(UInt64()), None, None),
StructField('f3', Timestamp(ISO_8601_FORMAT), None, None),
StructField('f4', Map(String(), UInt64()), None, None)
]
)
ns.add_data_type(struct2)
return ns
def _make_namespace_with_nested_types():
# type: (...) -> ApiNamespace
ns = ApiNamespace('ns_w_nested_types')
struct = Struct(name='NestedTypes', namespace=ns, ast_node=None)
struct.set_attributes(
doc=None,
fields=[
StructField(
name='NullableList',
data_type=Nullable(
List(UInt64())
),
doc=None,
ast_node=None,
),
StructField(
name='ListOfNullables',
data_type=List(
Nullable(UInt64())
),
doc=None,
ast_node=None,
)
]
)
ns.add_data_type(struct)
return ns
def _make_namespace_with_a_union():
# type: (...) -> ApiNamespace
ns = ApiNamespace('ns_with_a_union')
u1 = Union(name='Union', namespace=ns, ast_node=None, closed=True)
u1.set_attributes(
doc=None,
fields=[
UnionField(
name="first",
doc=None,
data_type=Void(),
ast_node=None
),
UnionField(
name="last",
doc=None,
data_type=Void(),
ast_node=None
),
],
)
ns.add_data_type(u1)
# A more interesting case with non-void variants.
shape_union = Union(name='Shape', namespace=ns, ast_node=None, closed=True)
shape_union.set_attributes(
doc=None,
fields=[
UnionField(
name="point",
doc=None,
data_type=Void(),
ast_node=None
),
UnionField(
name="circle",
doc=None,
data_type=Float64(),
ast_node=None
),
],
)
ns.add_data_type(shape_union)
return ns
def _make_namespace_with_empty_union():
# type: (...) -> ApiNamespace
ns = ApiNamespace('ns_with_empty_union')
union = Union(name='EmptyUnion', namespace=ns, ast_node=None, closed=True)
union.set_attributes(
doc=None,
fields=[],
)
ns.add_data_type(union)
return ns
def _make_namespace_with_route():
# type: (...) -> ApiNamespace
ns = ApiNamespace("_make_namespace_with_route()")
mock_ast_node = Mock()
route_one = ApiRoute(
name="route_one",
ast_node=mock_ast_node,
)
route_two = ApiRoute(
name="route_two",
ast_node=mock_ast_node,
)
ns.add_route(route_one)
ns.add_route(route_two)
return ns
def _api():
api = Api(version="1.0")
return api
_headers = """\
# -*- coding: utf-8 -*-
# Auto-generated by Stone, do not modify.
# @generated
# flake8: noqa
# pylint: skip-file
try:
from . import stone_validators as bv
from . import stone_base as bb
except (ImportError, SystemError, ValueError):
# Catch errors raised when importing a relative module when not in a package.
# This makes testing this file directly (outside of a package) easier.
import stone_validators as bv # type: ignore
import stone_base as bb # type: ignore"""
class TestPythonTypeStubs(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestPythonTypeStubs, self).__init__(*args, **kwargs)
self.maxDiff = 1000000 # Increase text diff size
def _evaluate_namespace(self, ns):
# type: (ApiNamespace) -> typing.Text
backend = _make_backend()
emitted = _mock_emit(backend)
backend._generate_base_namespace_module(ns)
result = "".join(emitted)
return result
def test__generate_base_namespace_module__with_many_structs(self):
# type: () -> None
ns = _make_namespace_with_many_structs()
result = self._evaluate_namespace(ns)
expected = textwrap.dedent("""\
{headers}
class Struct1(object):
def __init__(self,
f1: bool = ...) -> None: ...
@property
def f1(self) -> bool: ...
@f1.setter
def f1(self, val: bool) -> None: ...
@f1.deleter
def f1(self) -> None: ...
Struct1_validator: bv.Validator = ...
class Struct2(object):
def __init__(self,
f2: List[long] = ...,
f3: datetime.datetime = ...,
f4: Dict[Text, long] = ...) -> None: ...
@property
def f2(self) -> List[long]: ...
@f2.setter
def f2(self, val: List[long]) -> None: ...
@f2.deleter
def f2(self) -> None: ...
@property
def f3(self) -> datetime.datetime: ...
@f3.setter
def f3(self, val: datetime.datetime) -> None: ...
@f3.deleter
def f3(self) -> None: ...
@property
def f4(self) -> Dict[Text, long]: ...
@f4.setter
def f4(self, val: Dict[Text, long]) -> None: ...
@f4.deleter
def f4(self) -> None: ...
Struct2_validator: bv.Validator = ...
from typing import (
Dict,
List,
Text,
)
import datetime
""").format(headers=_headers)
self.assertEqual(result, expected)
def test__generate_base_namespace_module__with_nested_types(self):
# type: () -> None
ns = _make_namespace_with_nested_types()
result = self._evaluate_namespace(ns)
expected = textwrap.dedent("""\
{headers}
class NestedTypes(object):
def __init__(self,
list_of_nullables: List[Optional[long]] = ...,
nullable_list: Optional[List[long]] = ...) -> None: ...
@property
def list_of_nullables(self) -> List[Optional[long]]: ...
@list_of_nullables.setter
def list_of_nullables(self, val: List[Optional[long]]) -> None: ...
@list_of_nullables.deleter
def list_of_nullables(self) -> None: ...
@property
def nullable_list(self) -> Optional[List[long]]: ...
@nullable_list.setter
def nullable_list(self, val: Optional[List[long]]) -> None: ...
@nullable_list.deleter
def nullable_list(self) -> None: ...
NestedTypes_validator: bv.Validator = ...
from typing import (
List,
Optional,
)
""").format(headers=_headers)
self.assertEqual(result, expected)
def test__generate_base_namespace_module_with_union__generates_stuff(self):
# type: () -> None
ns = _make_namespace_with_a_union()
result = self._evaluate_namespace(ns)
expected = textwrap.dedent("""\
{headers}
class Union(bb.Union):
first = ... # type: Union
last = ... # type: Union
def is_first(self) -> bool: ...
def is_last(self) -> bool: ...
Union_validator: bv.Validator = ...
class Shape(bb.Union):
point = ... # type: Shape
def is_point(self) -> bool: ...
def is_circle(self) -> bool: ...
@classmethod
def circle(cls, val: float) -> Shape: ...
def get_circle(self) -> float: ...
Shape_validator: bv.Validator = ...
""").format(headers=_headers)
self.assertEqual(result, expected)
def test__generate_base_namespace_module_with_empty_union__generates_pass(self):
# type: () -> None
ns = _make_namespace_with_empty_union()
result = self._evaluate_namespace(ns)
expected = textwrap.dedent("""\
{headers}
class EmptyUnion(bb.Union):
pass
EmptyUnion_validator: bv.Validator = ...
""").format(headers=_headers)
self.assertEqual(result, expected)
def test__generate_routes(self):
# type: () -> None
ns = _make_namespace_with_route()
result = self._evaluate_namespace(ns)
expected = textwrap.dedent("""\
{headers}
route_one: bb.Route = ...
route_two: bb.Route = ...
""").format(headers=_headers)
self.assertEqual(result, expected)
def test__generate_base_namespace_module__with_alias(self):
# type: () -> None
ns = _make_namespace_with_alias()
result = self._evaluate_namespace(ns)
expected = textwrap.dedent("""\
{headers}
class Struct1(object):
def __init__(self,
f1: bool = ...) -> None: ...
@property
def f1(self) -> bool: ...
@f1.setter
def f1(self, val: bool) -> None: ...
@f1.deleter
def f1(self) -> None: ...
Struct1_validator: bv.Validator = ...
AliasToStruct1_validator: bv.Validator = ...
AliasToStruct1 = Struct1
NotUserDefinedAlias_validator: bv.Validator = ...
""").format(headers=_headers)
self.assertEqual(result, expected)