-
Notifications
You must be signed in to change notification settings - Fork 269
/
test_code_quality.py
234 lines (214 loc) · 8.71 KB
/
test_code_quality.py
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
import os, re, sys, pydatastructs, inspect
from typing import Type
def _list_files(checker):
root_path = os.path.abspath(
os.path.join(
os.path.split(__file__)[0],
os.pardir, os.pardir))
code_files = []
for (dirpath, _, filenames) in os.walk(root_path):
for _file in filenames:
if checker(_file):
code_files.append(os.path.join(dirpath, _file))
return code_files
checker = lambda _file: (re.match(r".*\.py$", _file) or
re.match(r".*\.cpp$", _file) or
re.match(r".*\.hpp$", _file))
code_files = _list_files(checker)
def test_trailing_white_spaces():
messages = [("The following places in your code "
"end with white spaces.")]
msg = "{}:{}"
for file_path in code_files:
file = open(file_path, "r")
line = file.readline()
line_number = 1
while line != "":
if line.endswith(" \n") or line.endswith("\t\n") \
or line.endswith(" ") or line.endswith("\t"):
messages.append(msg.format(file_path, line_number))
line = file.readline()
line_number += 1
file.close()
if len(messages) > 1:
assert False, '\n'.join(messages)
def test_final_new_lines():
messages = [("The following files in your code "
"do not end with a single new line.")]
msg1 = "No new line in {}:{}"
msg2 = "More than one new line in {}:{}"
for file_path in code_files:
file = open(file_path, "r")
lines = []
line = file.readline()
while line != "":
lines.append(line)
line = file.readline()
if lines:
if lines[-1][-1] != "\n":
messages.append(msg1.format(file_path, len(lines)))
if lines[-1] == "\n" and lines[-2][-1] == "\n":
messages.append(msg2.format(file_path, len(lines)))
file.close()
if len(messages) > 1:
assert False, '\n'.join(messages)
def test_comparison_True_False_None():
messages = [("The following places in your code "
"use `!=` or `==` for comparing True/False/None."
"Please use `is` instead.")]
msg = "{}:{}"
checker = lambda _file: re.match(r".*\.py$", _file)
py_files = _list_files(checker)
for file_path in py_files:
if file_path.find("test_code_quality.py") == -1:
file = open(file_path, "r")
line = file.readline()
line_number = 1
while line != "":
if ((line.find("== True") != -1) or
(line.find("== False") != -1) or
(line.find("== None") != -1) or
(line.find("!= True") != -1) or
(line.find("!= False") != -1) or
(line.find("!= None") != -1)):
messages.append(msg.format(file_path, line_number))
line = file.readline()
line_number += 1
file.close()
if len(messages) > 1:
assert False, '\n'.join(messages)
def test_reinterpret_cast():
def is_variable(str):
for ch in str:
if not (ch == '_' or ch.isalnum()):
return False
return True
checker = lambda _file: (re.match(r".*\.cpp$", _file) or
re.match(r".*\.hpp$", _file))
cpp_files = _list_files(checker)
messages = [("The following lines should use reinterpret_cast"
" to cast pointers from one type to another")]
msg = "Casting to {} at {}:{}"
for file_path in cpp_files:
file = open(file_path, "r")
line = file.readline()
line_number = 1
while line != "":
found_open = False
between_open_close = ""
for char in line:
if char == '(':
found_open = True
elif char == ')':
if (between_open_close and
between_open_close[-1] == '*' and
is_variable(between_open_close[:-1])):
messages.append(msg.format(between_open_close[:-1],
file_path, line_number))
between_open_close = ""
found_open = False
elif char != ' ' and found_open:
between_open_close += char
line = file.readline()
line_number += 1
file.close()
if len(messages) > 1:
assert False, '\n'.join(messages)
def test_presence_of_tabs():
messages = [("The following places in your code "
"use tabs instead of spaces.")]
msg = "{}:{}"
for file_path in code_files:
file = open(file_path, "r")
line_number = 1
line = file.readline()
while line != "":
if (line.find('\t') != -1):
messages.append(msg.format(file_path, line_number))
line = file.readline()
line_number += 1
file.close()
if len(messages) > 1:
assert False, '\n'.join(messages)
def _apis():
import pydatastructs as pyds
return [
pyds.graphs.adjacency_list.AdjacencyList,
pyds.graphs.adjacency_matrix.AdjacencyMatrix,
pyds.DoublyLinkedList, pyds.SinglyLinkedList,
pyds.SinglyCircularLinkedList,
pyds.DoublyCircularLinkedList,
pyds.OneDimensionalArray, pyds.MultiDimensionalArray,
pyds.DynamicOneDimensionalArray,
pyds.trees.BinaryTree, pyds.BinarySearchTree,
pyds.AVLTree, pyds.SplayTree, pyds.BinaryTreeTraversal,
pyds.DHeap, pyds.BinaryHeap, pyds.TernaryHeap, pyds.BinomialHeap,
pyds.MAryTree, pyds.OneDimensionalSegmentTree,
pyds.Queue, pyds.miscellaneous_data_structures.queue.ArrayQueue,
pyds.miscellaneous_data_structures.queue.LinkedListQueue,
pyds.PriorityQueue,
pyds.miscellaneous_data_structures.queue.LinkedListPriorityQueue,
pyds.miscellaneous_data_structures.queue.BinaryHeapPriorityQueue,
pyds.miscellaneous_data_structures.queue.BinomialHeapPriorityQueue,
pyds.Stack, pyds.miscellaneous_data_structures.stack.ArrayStack,
pyds.miscellaneous_data_structures.stack.LinkedListStack,
pyds.DisjointSetForest, pyds.BinomialTree, pyds.TreeNode, pyds.MAryTreeNode,
pyds.LinkedListNode, pyds.BinomialTreeNode, pyds.AdjacencyListGraphNode,
pyds.AdjacencyMatrixGraphNode, pyds.GraphEdge, pyds.Set, pyds.BinaryIndexedTree,
pyds.CartesianTree, pyds.CartesianTreeNode, pyds.Treap, pyds.RedBlackTreeNode, pyds.RedBlackTree,
pyds.Trie, pyds.TrieNode, pyds.SkipList, pyds.RangeQueryStatic, pyds.RangeQueryDynamic, pyds.SparseTable,
pyds.miscellaneous_data_structures.segment_tree.OneDimensionalArraySegmentTree,
pyds.bubble_sort, pyds.linear_search, pyds.binary_search, pyds.jump_search,
pyds.selection_sort, pyds.insertion_sort, pyds.quick_sort]
def test_public_api():
pyds = pydatastructs
apis = _apis()
print("\n\nAPI Report")
print("==========")
for name in apis:
if inspect.isclass(name):
_class = name
mro = _class.__mro__
must_methods = _class.methods()
print("\n" + str(name))
print("Methods Implemented")
print(must_methods)
print("Parent Classes")
print(mro[1:])
for supercls in mro:
if supercls != _class:
for method in must_methods:
if hasattr(supercls, method) and \
getattr(supercls, method) == \
getattr(_class, method):
assert False, ("%s class doesn't "
"have %s method implemented."%(
_class, method
))
def test_backend_argument_message():
import pydatastructs as pyds
backend_implemented = [
pyds.OneDimensionalArray,
pyds.DynamicOneDimensionalArray,
pyds.quick_sort
]
def call_and_raise(api, pos_args_count=0):
try:
if pos_args_count == 0:
api(backend=None)
elif pos_args_count == 1:
api(None, backend=None)
elif pos_args_count == 2:
api(None, None, backend=None)
except ValueError as value_error:
assert str(api) in value_error.args[0]
except TypeError as type_error:
max_pos_args_count = 2
if pos_args_count <= max_pos_args_count:
call_and_raise(api, pos_args_count + 1)
else:
raise type_error
apis = _apis()
for api in apis:
if api not in backend_implemented:
call_and_raise(api, 0)