-
Notifications
You must be signed in to change notification settings - Fork 10
/
test_acid.py
executable file
·186 lines (141 loc) · 5.24 KB
/
test_acid.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
#!/usr/bin/env python3
"""Test that pyformat runs without crashing on various Python files."""
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import subprocess
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
PYFORMAT_BIN = os.path.join(ROOT_PATH, 'pyformat.py')
import autopep8
if sys.stdout.isatty():
YELLOW = '\x1b[33m'
END = '\x1b[0m'
else:
YELLOW = ''
END = ''
def colored(text, color):
"""Return color coded text."""
return color + text + END
def readlines(filename):
"""Return contents of file as a list of lines."""
with autopep8.open_with_encoding(
filename,
encoding=autopep8.detect_encoding(filename)) as f:
return f.readlines()
def diff(before, after):
"""Return diff of two files."""
import difflib
return ''.join(difflib.unified_diff(
readlines(before),
readlines(after),
before,
after))
def run(filename, verbose=False, options=None):
"""Run pyformat on file at filename.
Return True on success.
"""
if not options:
options = []
import test_pyformat
with test_pyformat.temporary_directory() as temp_directory:
temp_filename = os.path.join(temp_directory,
os.path.basename(filename))
import shutil
shutil.copyfile(filename, temp_filename)
if 0 != subprocess.call([PYFORMAT_BIN, '--in-place', temp_filename] +
options):
sys.stderr.write('pyformat crashed on ' + filename + '\n')
return False
try:
file_diff = diff(filename, temp_filename)
if verbose:
sys.stderr.write(file_diff)
if check_syntax(filename):
try:
check_syntax(temp_filename, raise_error=True)
except (SyntaxError, TypeError,
UnicodeDecodeError) as exception:
sys.stderr.write('pyformat broke ' + filename + '\n' +
str(exception) + '\n')
return False
except IOError as exception:
sys.stderr.write(str(exception) + '\n')
return True
def check_syntax(filename, raise_error=False):
"""Return True if syntax is okay."""
with autopep8.open_with_encoding(
filename,
encoding=autopep8.detect_encoding(filename)) as input_file:
try:
compile(input_file.read(), '<string>', 'exec', dont_inherit=True)
return True
except (SyntaxError, TypeError, UnicodeDecodeError):
if raise_error:
raise
else:
return False
def process_args():
"""Return processed arguments (options and positional arguments)."""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--aggressive', action='store_true',
help='pass to the pyformat "--aggressive" option')
parser.add_argument('-v', '--verbose', action='store_true',
help='print verbose messages')
parser.add_argument('files', nargs='*', help='files to format')
return parser.parse_args()
def check(args):
"""Run recursively run pyformat on directory of files.
Return False if the fix results in broken syntax.
"""
if args.files:
dir_paths = args.files
else:
dir_paths = [path for path in sys.path
if os.path.isdir(path)]
options = []
if args.aggressive:
options.append('--aggressive')
filenames = dir_paths
completed_filenames = set()
while filenames:
try:
name = os.path.realpath(filenames.pop(0))
if not os.path.exists(name):
# Invalid symlink.
continue
if name in completed_filenames:
sys.stderr.write(
colored(
'---> Skipping previously tested ' + name + '\n',
YELLOW))
continue
else:
completed_filenames.update(name)
if os.path.isdir(name):
for root, directories, children in os.walk('{}'.format(name)):
filenames += [os.path.join(root, f) for f in children
if f.endswith('.py') and
not f.startswith('.')]
directories[:] = [d for d in directories
if not d.startswith('.')]
else:
verbose_message = '---> Testing with ' + name
sys.stderr.write(colored(verbose_message + '\n', YELLOW))
if not run(os.path.join(name), verbose=args.verbose,
options=options):
return False
except (UnicodeDecodeError, UnicodeEncodeError) as exception:
# Ignore annoying codec problems on Python 2.
print(exception, file=sys.stderr)
continue
return True
def main():
"""Run main."""
return 0 if check(process_args()) else 1
if __name__ == '__main__':
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(1)