File: test_api.py

package info (click to toggle)
python-gast 0.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 312 kB
  • sloc: python: 3,057; sh: 7; makefile: 3
file content (232 lines) | stat: -rw-r--r-- 7,708 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
import unittest

import ast
import gast
import sys


def dump(node):
    return gast.dump(node, show_empty=True)


class APITestCase(unittest.TestCase):

    def test_literal_eval_string(self):
        code = "1, 3"
        self.assertEqual(ast.literal_eval(code),
                         gast.literal_eval(code))

    def test_literal_eval_code(self):
        code = "[1, 3]"
        tree = ast.parse(code, mode='eval')
        gtree = gast.parse(code, mode='eval')
        self.assertEqual(ast.literal_eval(tree),
                         gast.literal_eval(gtree))

    def test_parse(self):
        code = '''
def foo(x=1, *args, **kwargs):
    return x + y +len(args) + len(kwargs)
        '''
        gast.parse(code)

    def test_unparse(self):
        code = 'def foo(x=1): return x'
        self.assertEqual(gast.unparse(gast.parse(code)),
                         'def foo(x=1):\n    return x')

    def test_dump0(self):
        code = 'lambda x: x'
        tree = gast.parse(code, mode='eval')
        zdump = dump(tree)
        norm = ("Expression(body=Lambda(args=arguments(args=[Name("
                "id='x', ctx=Param(), "
                "annotation=None, type_comment=None)], posonlyargs=[], "
                "vararg=None, kwonlyargs=[], kw_defaults=[], kwarg=None, "
                "defaults=[]), body=Name(id='x', ctx=Load(), "
                "annotation=None, type_comment=None)"
                "))")
        self.assertEqual(zdump, norm)

    def test_dump1(self):
        code = 'def func(): return 1'
        tree = gast.parse(code)
        node = tree.body[0]
        zdump = gast.dump(node)
        norm = "FunctionDef(name='func', args=arguments(vararg=None, kwarg=None), body=[Return(value=Constant(value=1, kind=None))], returns=None, type_comment=None)"
        self.assertEqual(zdump, norm)

    def test_walk(self):
        code = 'x + 1'
        tree = gast.parse(code, mode='eval')
        zdump = dump(tree)
        norm = ("Expression(body=BinOp(left=Name(id='x', ctx=Load(), "
                "annotation=None, type_comment=None), op=Add(), "
                "right=Constant(value=1, kind=None)))")
        self.assertEqual(zdump, norm)
        self.assertEqual(len(list(gast.walk(tree))), 6)

    def test_iter_fields(self):
        tree = gast.Constant(value=1, kind=None)
        self.assertEqual({name for name, _ in gast.iter_fields(tree)},
                         {'value', 'kind'})

    def test_iter_child_nodes(self):
        tree = gast.UnaryOp(gast.USub(), gast.Constant(value=1, kind=None))
        self.assertEqual(len(list(gast.iter_fields(tree))),
                         2)

    def test_increment_lineno(self):
        tree = gast.Constant(value=1, kind=None)
        tree.lineno = 1
        gast.increment_lineno(tree)
        self.assertEqual(tree.lineno, 2)

    def test_get_source_segment(self):
        code = 'x + 1'
        tree = gast.parse(code)
        source = gast.get_source_segment(code, tree.body[0].value.left)
        if sys.version_info >= (3, 8):
            self.assertEqual(source, 'x')
        else:
            self.assertEqual(source, None)


    def test_get_source_segment_padded(self):
        code = 'if 1:\n if 2:\n  3'
        tree = gast.parse(code)
        if_tree = tree.body[0].body[0]
        source_nopadding = gast.get_source_segment(code, if_tree, padded=False)
        if sys.version_info >= (3, 8):
            self.assertEqual(source_nopadding, 'if 2:\n  3')
        else:
            self.assertEqual(source_nopadding, None)
        source_padding = gast.get_source_segment(code, if_tree, padded=True)
        if sys.version_info >= (3, 8):
            self.assertEqual(source_padding, ' if 2:\n  3')
        else:
            self.assertEqual(source_padding, None)

    def test_get_docstring_function(self):
        code = 'def foo(): "foo"'
        tree = gast.parse(code)
        func = tree.body[0]
        docs = gast.get_docstring(func)
        self.assertEqual(docs, "foo")

    if sys.version_info >= (3, 5):
        def test_get_docstring_asyncfunction(self):
            code = 'async def foo(): "foo"'
            tree = gast.parse(code)
            func = tree.body[0]
            docs = gast.get_docstring(func)
            self.assertEqual(docs, "foo")

    def test_get_docstring_module(self):
        code = '"foo"'
        tree = gast.parse(code)
        docs = gast.get_docstring(tree)
        self.assertEqual(docs, "foo")

    def test_get_docstring_class(self):
        code = 'class foo: "foo"'
        tree = gast.parse(code)
        cls = tree.body[0]
        docs = gast.get_docstring(cls)
        self.assertEqual(docs, "foo")

    def test_get_docstring_expr(self):
        code = '1'
        tree = gast.parse(code)
        func = tree
        docs = gast.get_docstring(func)
        self.assertEqual(docs, None)

    def test_copy_location(self):
        tree = gast.Constant(value=1, kind=None)
        tree.lineno = 1
        tree.col_offset = 2

        node = gast.Constant(value=2, kind=None)
        gast.copy_location(node, tree)
        self.assertEqual(node.lineno, tree.lineno)
        self.assertEqual(node.col_offset, tree.col_offset)

    def test_fix_missing_locations(self):
        node = gast.Constant(value=6, kind=None)
        tree = gast.UnaryOp(gast.USub(), node)
        tree.lineno = 1
        tree.col_offset = 2
        gast.fix_missing_locations(tree)
        self.assertEqual(node.lineno, tree.lineno)
        self.assertEqual(node.col_offset, tree.col_offset)

    def test_NodeTransformer(self):
        node = gast.Constant(value=6, kind=None)
        tree = gast.UnaryOp(gast.USub(), node)

        class Trans(gast.NodeTransformer):

            def visit_Constant(self, node):
                node.value *= 2
                return node

        tree = Trans().visit(tree)

        self.assertEqual(node.value, 12)

    def test_NodeVisitor(self):
        node = gast.Constant(value=6, kind=None)
        tree = gast.UnaryOp(gast.USub(), node)

        class Vis(gast.NodeTransformer):

            def __init__(self):
                self.state = []

            def visit_Constant(self, node):
                self.state.append(node.value)

        vis = Vis()
        vis.visit(tree)

        self.assertEqual(vis.state, [6])

    def test_NodeConstructor(self):
        node0 = gast.Name()
        load = gast.Load()
        node1 = gast.Name('id', load, None, None)
        node2 = gast.Name('id', load, None, type_comment=None)
        with self.assertRaises(TypeError):
            node1 = gast.Name('id', 'ctx', 'annotation', 'type_comment',
                              'random_field')
        for field in gast.Name._fields:
            self.assertEqual(getattr(node1, field), getattr(node2, field))

    def test_IncompleteNodeConstructor(self):
        afd = gast.FunctionDef(
                    name="f",
                    args=gast.arguments(
                        args=[],
                        posonlyargs=[],
                        vararg=None,
                        kwonlyargs=[],
                        kw_defaults=[],
                        kwarg=None,
                        defaults=[],
                        ),
                    body=[],
                    decorator_list=[],
                    returns=None,
                    type_comment=None,
                    #type_params=[],
                    )
        # Should not fail even if type_params is not set
        afd_ast = gast.gast_to_ast(afd)
        self.assertEqual(afd_ast.name, "f")
        if hasattr(afd_ast, "type_params"):
            self.assertEqual(afd_ast.type_params, [])


if __name__ == '__main__':
    unittest.main()