PyCG 0.0.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
PyCG/tests/base.py ADDED
@@ -0,0 +1,25 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ from unittest import TestCase
22
+
23
+
24
+ class TestBase(TestCase):
25
+ pass
@@ -0,0 +1,87 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ from base import TestBase
22
+
23
+ from pycg.machinery.callgraph import CallGraph, CallGraphError
24
+
25
+
26
+ class CallGraphTest(TestBase):
27
+ def setUp(self):
28
+ self.cg = CallGraph()
29
+
30
+ def tearDown(self):
31
+ del self.cg
32
+
33
+ def test_setup(self):
34
+ self.assertEqual(self.cg.get(), {})
35
+
36
+ def test_add_node(self):
37
+ clone = {}
38
+
39
+ self.cg.add_node("node1")
40
+ clone["node1"] = set()
41
+ self.assertEqual(self.cg.get().items(), clone.items())
42
+
43
+ # no duplicate nodes
44
+ self.cg.add_node("node1")
45
+ self.assertEqual(self.cg.get().items(), clone.items())
46
+
47
+ # only str types can be mapped
48
+ with self.assertRaises(CallGraphError):
49
+ self.cg.add_node(1)
50
+
51
+ # no empty names allowed
52
+ with self.assertRaises(CallGraphError):
53
+ self.cg.add_node("")
54
+
55
+ self.cg.add_node("node2")
56
+ clone["node2"] = set()
57
+ self.assertEqual(self.cg.get().items(), clone.items())
58
+
59
+ def test_add_edge(self):
60
+ clone = {}
61
+ clone["node1"] = set(["node2"])
62
+ clone["node2"] = set()
63
+
64
+ # should create a node for node1 and node2
65
+ # and add an edge from node1 to node2
66
+ self.cg.add_edge("node1", "node2")
67
+ self.assertEqual(self.cg.get().items(), clone.items())
68
+
69
+ # no duplicate items
70
+ self.cg.add_edge("node1", "node2")
71
+ self.assertEqual(self.cg.get().items(), clone.items())
72
+
73
+ clone["node2"].add("node1")
74
+ self.cg.add_edge("node2", "node1")
75
+ self.assertEqual(self.cg.get().items(), clone.items())
76
+
77
+ # no integer nodes allowed
78
+ with self.assertRaises(CallGraphError):
79
+ self.cg.add_edge("node1", 1)
80
+ with self.assertRaises(CallGraphError):
81
+ self.cg.add_edge(1, "node1")
82
+
83
+ # no empty strings allowed
84
+ with self.assertRaises(CallGraphError):
85
+ self.cg.add_edge("node1", "")
86
+ with self.assertRaises(CallGraphError):
87
+ self.cg.add_edge("", "node1")
@@ -0,0 +1,90 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ from base import TestBase
22
+
23
+ from pycg import utils
24
+ from pycg.machinery.definitions import DefinitionError, DefinitionManager
25
+
26
+
27
+ class DefinitionManagerTest(TestBase):
28
+ def test_create(self):
29
+ dm = DefinitionManager()
30
+
31
+ dm.create("adefi", utils.constants.NAME_DEF)
32
+
33
+ defi = dm.get("adefi")
34
+ self.assertEqual(defi.get_type(), utils.constants.NAME_DEF)
35
+ self.assertEqual(defi.get_ns(), "adefi")
36
+
37
+ # only non empty strings allowed
38
+ with self.assertRaises(DefinitionError):
39
+ dm.create("", utils.constants.NAME_DEF)
40
+
41
+ with self.assertRaises(DefinitionError):
42
+ dm.create(1, utils.constants.NAME_DEF)
43
+
44
+ # no duplicate defs
45
+ with self.assertRaises(DefinitionError):
46
+ dm.create("adefi", utils.constants.NAME_DEF)
47
+
48
+ # we should provide a valid type
49
+ with self.assertRaises(DefinitionError):
50
+ dm.create("adefi2", "notavalidtype")
51
+
52
+ def test_assign(self):
53
+ dm = DefinitionManager()
54
+ defi1 = dm.create("defi1", utils.constants.NAME_DEF)
55
+ defi1.get_name_pointer().add("item1")
56
+ defi1.get_name_pointer().add("item2")
57
+ defi1.get_name_pointer().add_arg(0, "arg")
58
+
59
+ defi2 = dm.assign("defi2", defi1)
60
+ # should have the correct ns
61
+ self.assertEqual(defi2.get_ns(), "defi2")
62
+ # values should be merged
63
+ self.assertEqual(defi2.get_type(), utils.constants.NAME_DEF)
64
+ self.assertEqual(defi2.get_name_pointer().get(), set(["item1", "item2"]))
65
+ self.assertEqual(defi2.get_name_pointer().get_arg(0), set(["arg"]))
66
+
67
+ # for function defs a return def should be created too
68
+ fndefi = dm.create("fndefi", utils.constants.FUN_DEF)
69
+ dm.assign("fndefi2", fndefi)
70
+ return_def = dm.get("{}.{}".format("fndefi2", utils.constants.RETURN_NAME))
71
+ self.assertIsNotNone(return_def)
72
+ self.assertEqual(
73
+ return_def.get_name_pointer().get(),
74
+ set(["{}.{}".format("fndefi", utils.constants.RETURN_NAME)]),
75
+ )
76
+
77
+ def test_handle_function_def(self):
78
+ # handle parent definition
79
+ parent_ns = "root"
80
+ fn_name = "function"
81
+ fn_ns = "{}.{}".format(parent_ns, fn_name)
82
+
83
+ dm = DefinitionManager()
84
+ dm.create("root", utils.constants.NAME_DEF)
85
+
86
+ dm.handle_function_def(parent_ns, fn_name)
87
+
88
+ # a definition for the function should be created
89
+ fn_def = dm.get(fn_ns)
90
+ self.assertIsNotNone(fn_def)
@@ -0,0 +1,319 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ from base import TestBase
22
+
23
+ from pycg import utils
24
+ from pycg.formats.fasten import Fasten
25
+
26
+
27
+ class FastenFormatTest(TestBase):
28
+ FORGE = "pypi"
29
+ PRODUCT = "myproduct"
30
+ PACKAGE = "mock_pkg"
31
+ VERSION = "0.2.1"
32
+ TIMESTAMP = 128
33
+
34
+ def setUp(self):
35
+ class CGGenerator:
36
+ internal_mods = {}
37
+ external_mods = {}
38
+ classes = {}
39
+ edges = []
40
+ functions = []
41
+
42
+ def output_internal_mods(self):
43
+ return self.internal_mods
44
+
45
+ def output_external_mods(self):
46
+ return self.external_mods
47
+
48
+ def output_classes(self):
49
+ return self.classes
50
+
51
+ def output_edges(self):
52
+ return self.edges
53
+
54
+ def output_functions(self):
55
+ return self.functions
56
+
57
+ self.cg_generator = CGGenerator()
58
+ self.forge = self.FORGE
59
+ self.product = self.PRODUCT
60
+ self.package = self.PACKAGE
61
+ self.version = self.VERSION
62
+ self.timestamp = self.TIMESTAMP
63
+
64
+ def get_formatter(self):
65
+ return Fasten(
66
+ self.cg_generator,
67
+ self.package,
68
+ self.product,
69
+ self.forge,
70
+ self.version,
71
+ self.timestamp,
72
+ )
73
+
74
+ def test_cli_args(self):
75
+ formatter = self.get_formatter()
76
+ output = formatter.generate()
77
+
78
+ self.assertEqual(output["product"], self.product)
79
+ self.assertEqual(output["forge"], self.forge)
80
+ self.assertEqual(output["depset"], [])
81
+ self.assertEqual(output["version"], self.version)
82
+ self.assertEqual(output["timestamp"], self.timestamp)
83
+ self.assertEqual(output["modules"], {"internal": {}, "external": {}})
84
+ self.assertEqual(
85
+ output["graph"],
86
+ {"internalCalls": [], "externalCalls": [], "resolvedCalls": []},
87
+ )
88
+
89
+ def test_uri(self):
90
+ self.cg_generator.functions = ["mod1.mod2.myfunc"]
91
+ formatter = self.get_formatter()
92
+
93
+ # Internal uri check
94
+ # test modname without method
95
+ self.assertEqual(formatter.to_uri("mymod"), "/mymod/")
96
+ self.assertEqual(formatter.to_uri("mymod.mod1"), "/mymod.mod1/")
97
+ # test method starting with modname
98
+ self.assertEqual(
99
+ formatter.to_uri("mymod.mod1", "mymod.mod1.fn"), "/mymod.mod1/fn"
100
+ )
101
+ self.assertEqual(
102
+ formatter.to_uri("mymod.mod1", "mymod.mod1.cls.fn"), "/mymod.mod1/cls.fn"
103
+ )
104
+ # test method starting with modname but without . inbetween
105
+ with self.assertRaises(Exception):
106
+ formatter.to_uri("mymod.mod1", "mymod.mod1cls.fn")
107
+ # test method being in functions
108
+ self.assertEqual(
109
+ formatter.to_uri("mod1.mod2", "mod1.mod2.myfunc"), "/mod1.mod2/myfunc()"
110
+ )
111
+
112
+ # External uri check
113
+ # test modname builtin
114
+ self.assertEqual(
115
+ formatter.to_external_uri(
116
+ utils.constants.BUILTIN_NAME,
117
+ utils.join_ns(utils.constants.BUILTIN_NAME, "cls1.fn1"),
118
+ ),
119
+ "//.builtin//cls1.fn1",
120
+ )
121
+ # test modname not builtin
122
+ self.assertEqual(
123
+ formatter.to_external_uri("requests", "requests.Request.get"),
124
+ "//requests//requests.Request.get",
125
+ )
126
+
127
+ def _get_internal_mods(self):
128
+ return {
129
+ "mod1": {
130
+ "filename": "mod1.py",
131
+ "methods": {
132
+ "mod1.method": {"name": "mod1.method", "first": 2, "last": 5},
133
+ "mod1.Cls.method": {
134
+ "name": "mod1.Cls.method",
135
+ "first": 6,
136
+ "last": 9,
137
+ },
138
+ "mod1": {"name": "mod1", "first": 1, "last": 9},
139
+ "mod1.Cls": {"name": "mod1.Cls", "first": 5, "last": 9},
140
+ },
141
+ },
142
+ "mod.mod2": {
143
+ "filename": "mod/mod2.py",
144
+ "methods": {
145
+ "mod.mod2.method": {
146
+ "name": "mod.mod2.method",
147
+ "first": 1,
148
+ "last": 3,
149
+ },
150
+ "mod.mod2": {"name": "mod.mod2", "first": 1, "last": 9},
151
+ "mod.mod2.Cls.Nested.method": {
152
+ "name": "mod.mod2.Cls.Nested.method",
153
+ "first": 6,
154
+ "last": 9,
155
+ },
156
+ "mod.mod2.Cls": {"name": "mod.mod2.Cls", "first": 4, "last": 9},
157
+ "mod.mod2.Cls.Nested": {
158
+ "name": "mod.mod2.Cls.Nested",
159
+ "first": 5,
160
+ "last": 9,
161
+ },
162
+ },
163
+ },
164
+ }
165
+
166
+ def _get_external_mods(self):
167
+ return {
168
+ "external": {
169
+ "filename": None,
170
+ "methods": {
171
+ "external": {"name": "external", "first": None, "last": None},
172
+ "external.Cls": {
173
+ "name": "external.Cls",
174
+ "first": None,
175
+ "last": None,
176
+ },
177
+ "external.method": {
178
+ "name": "external.method",
179
+ "first": None,
180
+ "last": None,
181
+ },
182
+ },
183
+ },
184
+ "external2": {
185
+ "filename": None,
186
+ "methods": {
187
+ "external2": {"name": "external2", "first": None, "last": None},
188
+ "external2.method": {
189
+ "name": "external2.method",
190
+ "first": None,
191
+ "last": None,
192
+ },
193
+ },
194
+ },
195
+ }
196
+
197
+ def _get_classes(self):
198
+ return {
199
+ "mod1.Cls": {"module": "mod1", "mro": ["mod1.Cls"]},
200
+ "mod.mod2.Cls": {"module": "mod.mod2", "mro": ["mod.mod2.Cls", "mod1.Cls"]},
201
+ "mod.mod2.Cls.Nested": {
202
+ "module": "mod.mod2",
203
+ "mro": ["mod.mod2.Cls.Nested", "external.Cls"],
204
+ },
205
+ }
206
+
207
+ def test_internal_modules(self):
208
+ internal_mods = self._get_internal_mods()
209
+ self.cg_generator.internal_mods = internal_mods
210
+
211
+ formatter = self.get_formatter()
212
+ internal_modules = formatter.generate()["modules"]["internal"]
213
+
214
+ # test that keys are URI formatted names
215
+ key_uris = [formatter.to_uri(key) for key in internal_mods]
216
+ self.assertEqual(set(key_uris), set(internal_modules.keys()))
217
+ self.assertEqual(len(key_uris), len(internal_modules.keys()))
218
+
219
+ # test that SourceFileName are correct
220
+ for name, mod in internal_mods.items():
221
+ self.assertEqual(
222
+ mod["filename"], internal_modules[formatter.to_uri(name)]["sourceFile"]
223
+ )
224
+
225
+ # test that namespaces contains all methods
226
+ for name, mod in internal_mods.items():
227
+ name_uri = formatter.to_uri(name)
228
+
229
+ # collect expected namespaces for module
230
+ expected_namespaces = []
231
+ for method, info in mod["methods"].items():
232
+ method_uri = formatter.to_uri(name, method)
233
+ first = info["first"]
234
+ last = info["last"]
235
+ expected_namespaces.append(
236
+ dict(namespace=method_uri, metadata=dict(first=first, last=last))
237
+ )
238
+
239
+ # namespaces defined for module
240
+ result_namespaces = internal_modules[name_uri]["namespaces"].values()
241
+ # unique identifiers defined for module
242
+ result_ids = internal_modules[name_uri]["namespaces"].keys()
243
+
244
+ # no duplicate ids and same namespaces
245
+ self.assertEqual(
246
+ sorted(expected_namespaces, key=lambda x: x["namespace"]),
247
+ sorted(result_namespaces, key=lambda x: x["namespace"]),
248
+ )
249
+ self.assertEqual(len(result_ids), len(set(result_ids)))
250
+
251
+ def test_external_modules(self):
252
+ external_mods = self._get_external_mods()
253
+ self.cg_generator.external_mods = external_mods
254
+
255
+ formatter = self.get_formatter()
256
+ external_modules = formatter.generate()["modules"]["external"]
257
+
258
+ # test that external modules keys are identical with the ones generated
259
+ self.assertEqual(set(external_mods.keys()), set(external_modules.keys()))
260
+ self.assertEqual(len(external_mods.keys()), len(external_modules.keys()))
261
+
262
+ # test that namespaces contains all the expected methods
263
+ for name, mod in external_mods.items():
264
+ # collect expected namespaces for module
265
+ expected_namespaces = []
266
+ for method, info in mod["methods"].items():
267
+ if method != name:
268
+ method_uri = formatter.to_external_uri(name, method)
269
+ expected_namespaces.append(dict(namespace=method_uri, metadata={}))
270
+
271
+ # namespaces defined for external modules
272
+ result_namespaces = external_modules[name]["namespaces"].values()
273
+
274
+ # unique identifiers defined for external modules
275
+ result_ids = external_modules[name]["namespaces"].keys()
276
+
277
+ # no duplicate ids and same namespaces
278
+ self.assertEqual(
279
+ sorted(expected_namespaces, key=lambda x: x["namespace"]),
280
+ sorted(result_namespaces, key=lambda x: x["namespace"]),
281
+ )
282
+ self.assertEqual(len(result_ids), len(set(result_ids)))
283
+
284
+ def test_hiearchy(self):
285
+ classes = self._get_classes()
286
+ internal_mods = self._get_internal_mods()
287
+ self.cg_generator.internal_mods = internal_mods
288
+ self.cg_generator.classes = classes
289
+
290
+ formatter = self.get_formatter()
291
+ fasten_format = formatter.generate()
292
+ modules = fasten_format["modules"]["internal"]
293
+ id_mapping = {}
294
+ total_classes = 0
295
+ for _, mod in modules.items():
296
+ for unique, ns in mod["namespaces"].items():
297
+ id_mapping[ns["namespace"]] = unique
298
+ if "superClasses" in ns["metadata"]:
299
+ total_classes += 1
300
+ self.assertEqual(total_classes, len(classes.keys()))
301
+ for cls_name, cls in classes.items():
302
+ cls_name_uri = id_mapping[formatter.to_uri(cls["module"], cls_name)]
303
+ cls_mro = []
304
+ for item in cls["mro"]:
305
+ # result mro should not contain the class name
306
+ if item == cls_name:
307
+ continue
308
+
309
+ if classes.get(item, None): # it is an internal module
310
+ cls_mro.append(formatter.to_uri(classes[item]["module"], item))
311
+ else:
312
+ cls_mro.append(formatter.to_external_uri(item.split(".")[0], item))
313
+
314
+ self.assertEqual(
315
+ cls_mro,
316
+ modules[formatter.to_uri(cls["module"])]["namespaces"][cls_name_uri][
317
+ "metadata"
318
+ ]["superClasses"],
319
+ )