| 1 |
|
| 2 |
"""Test that autoflake performs correctly on arbitrary Python files. |
| 3 |
|
| 4 |
This checks that autoflake never introduces incorrect syntax. This is |
| 5 |
done by doing a syntax check after the autoflake run. The number of |
| 6 |
Pyflakes warnings is also confirmed to always improve. |
| 7 |
""" |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import argparse |
| 12 |
import os |
| 13 |
import shlex |
| 14 |
import subprocess |
| 15 |
import sys |
| 16 |
from collections.abc import Sequence |
| 17 |
|
| 18 |
import autoflake |
| 19 |
|
| 20 |
ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) |
| 21 |
AUTOFLAKE_BIN = "'{}' '{}'".format( |
| 22 |
sys.executable, |
| 23 |
os.path.join(ROOT_PATH, "autoflake.py"), |
| 24 |
) |
| 25 |
|
| 26 |
if sys.stdout.isatty(): |
| 27 |
YELLOW = "\x1b[33m" |
| 28 |
END = "\x1b[0m" |
| 29 |
else: |
| 30 |
YELLOW = "" |
| 31 |
END = "" |
| 32 |
|
| 33 |
|
| 34 |
def colored(text: str, color: str) -> str: |
| 35 |
"""Return color coded text.""" |
| 36 |
return color + text + END |
| 37 |
|
| 38 |
|
| 39 |
def pyflakes_count(filename: str) -> int: |
| 40 |
"""Return pyflakes error count.""" |
| 41 |
with autoflake.open_with_encoding( |
| 42 |
filename, |
| 43 |
encoding=autoflake.detect_encoding(filename), |
| 44 |
) as f: |
| 45 |
return len(list(autoflake.check(f.read()))) |
| 46 |
|
| 47 |
|
| 48 |
def readlines(filename: str) -> Sequence[str]: |
| 49 |
"""Return contents of file as a list of lines.""" |
| 50 |
with autoflake.open_with_encoding( |
| 51 |
filename, |
| 52 |
encoding=autoflake.detect_encoding(filename), |
| 53 |
) as f: |
| 54 |
return f.readlines() |
| 55 |
|
| 56 |
|
| 57 |
def diff(before: str, after: str) -> str: |
| 58 |
"""Return diff of two files.""" |
| 59 |
import difflib |
| 60 |
|
| 61 |
return "".join( |
| 62 |
difflib.unified_diff( |
| 63 |
readlines(before), |
| 64 |
readlines(after), |
| 65 |
before, |
| 66 |
after, |
| 67 |
), |
| 68 |
) |
| 69 |
|
| 70 |
|
| 71 |
def run( |
| 72 |
filename: str, |
| 73 |
command: str, |
| 74 |
verbose: bool = False, |
| 75 |
options: list[str] | None = None, |
| 76 |
) -> bool: |
| 77 |
"""Run autoflake on file at filename. |
| 78 |
|
| 79 |
Return True on success. |
| 80 |
""" |
| 81 |
if not options: |
| 82 |
options = [] |
| 83 |
|
| 84 |
import test_autoflake |
| 85 |
|
| 86 |
with test_autoflake.temporary_directory() as temp_directory: |
| 87 |
temp_filename = os.path.join( |
| 88 |
temp_directory, |
| 89 |
os.path.basename(filename), |
| 90 |
) |
| 91 |
import shutil |
| 92 |
|
| 93 |
shutil.copyfile(filename, temp_filename) |
| 94 |
|
| 95 |
if 0 != subprocess.call( |
| 96 |
shlex.split(command) + ["--in-place", temp_filename] + options, |
| 97 |
): |
| 98 |
sys.stderr.write("autoflake crashed on " + filename + "\n") |
| 99 |
return False |
| 100 |
|
| 101 |
try: |
| 102 |
file_diff = diff(filename, temp_filename) |
| 103 |
if verbose: |
| 104 |
sys.stderr.write(file_diff) |
| 105 |
|
| 106 |
if check_syntax(filename): |
| 107 |
try: |
| 108 |
check_syntax(temp_filename, raise_error=True) |
| 109 |
except ( |
| 110 |
SyntaxError, |
| 111 |
TypeError, |
| 112 |
UnicodeDecodeError, |
| 113 |
ValueError, |
| 114 |
) as exception: |
| 115 |
sys.stderr.write( |
| 116 |
"autoflake broke " + filename + "\n" + str(exception) + "\n", |
| 117 |
) |
| 118 |
return False |
| 119 |
|
| 120 |
before_count = pyflakes_count(filename) |
| 121 |
after_count = pyflakes_count(temp_filename) |
| 122 |
|
| 123 |
if verbose: |
| 124 |
print("(before, after):", (before_count, after_count)) |
| 125 |
|
| 126 |
if file_diff and after_count > before_count: |
| 127 |
sys.stderr.write("autoflake made " + filename + " worse\n") |
| 128 |
return False |
| 129 |
except OSError as exception: |
| 130 |
sys.stderr.write(str(exception) + "\n") |
| 131 |
|
| 132 |
return True |
| 133 |
|
| 134 |
|
| 135 |
def check_syntax(filename: str, raise_error: bool = False) -> bool: |
| 136 |
"""Return True if syntax is okay.""" |
| 137 |
with autoflake.open_with_encoding( |
| 138 |
filename, |
| 139 |
encoding=autoflake.detect_encoding(filename), |
| 140 |
) as input_file: |
| 141 |
try: |
| 142 |
compile(input_file.read(), "<string>", "exec", dont_inherit=True) |
| 143 |
return True |
| 144 |
except (SyntaxError, TypeError, UnicodeDecodeError, ValueError): |
| 145 |
if raise_error: |
| 146 |
raise |
| 147 |
else: |
| 148 |
return False |
| 149 |
|
| 150 |
|
| 151 |
def process_args() -> argparse.Namespace: |
| 152 |
"""Return processed arguments (options and positional arguments).""" |
| 153 |
parser = argparse.ArgumentParser() |
| 154 |
|
| 155 |
parser.add_argument( |
| 156 |
"--command", |
| 157 |
default=AUTOFLAKE_BIN, |
| 158 |
help="autoflake command (default: %(default)s)", |
| 159 |
) |
| 160 |
|
| 161 |
parser.add_argument( |
| 162 |
"--expand-star-imports", |
| 163 |
action="store_true", |
| 164 |
help="expand wildcard star imports with undefined names", |
| 165 |
) |
| 166 |
|
| 167 |
parser.add_argument( |
| 168 |
"--imports", |
| 169 |
help='pass to the autoflake "--imports" option', |
| 170 |
) |
| 171 |
|
| 172 |
parser.add_argument( |
| 173 |
"--remove-all-unused-imports", |
| 174 |
action="store_true", |
| 175 |
help='pass "--remove-all-unused-imports" option to autoflake', |
| 176 |
) |
| 177 |
|
| 178 |
parser.add_argument( |
| 179 |
"--remove-duplicate-keys", |
| 180 |
action="store_true", |
| 181 |
help='pass "--remove-duplicate-keys" option to autoflake', |
| 182 |
) |
| 183 |
|
| 184 |
parser.add_argument( |
| 185 |
"--remove-unused-variables", |
| 186 |
action="store_true", |
| 187 |
help='pass "--remove-unused-variables" option to autoflake', |
| 188 |
) |
| 189 |
|
| 190 |
parser.add_argument( |
| 191 |
"-v", |
| 192 |
"--verbose", |
| 193 |
action="store_true", |
| 194 |
help="print verbose messages", |
| 195 |
) |
| 196 |
|
| 197 |
parser.add_argument("files", nargs="*", help="files to test against") |
| 198 |
|
| 199 |
return parser.parse_args() |
| 200 |
|
| 201 |
|
| 202 |
def check(args: argparse.Namespace) -> bool: |
| 203 |
"""Run recursively run autoflake on directory of files. |
| 204 |
|
| 205 |
Return False if the fix results in broken syntax. |
| 206 |
""" |
| 207 |
if args.files: |
| 208 |
dir_paths = args.files |
| 209 |
else: |
| 210 |
dir_paths = [path for path in sys.path if os.path.isdir(path)] |
| 211 |
|
| 212 |
options = [] |
| 213 |
if args.expand_star_imports: |
| 214 |
options.append("--expand-star-imports") |
| 215 |
|
| 216 |
if args.imports: |
| 217 |
options.append("--imports=" + args.imports) |
| 218 |
|
| 219 |
if args.remove_all_unused_imports: |
| 220 |
options.append("--remove-all-unused-imports") |
| 221 |
|
| 222 |
if args.remove_duplicate_keys: |
| 223 |
options.append("--remove-duplicate-keys") |
| 224 |
|
| 225 |
if args.remove_unused_variables: |
| 226 |
options.append("--remove-unused-variables") |
| 227 |
|
| 228 |
filenames = dir_paths |
| 229 |
completed_filenames = set() |
| 230 |
|
| 231 |
while filenames: |
| 232 |
try: |
| 233 |
name = os.path.realpath(filenames.pop(0)) |
| 234 |
if not os.path.exists(name): |
| 235 |
|
| 236 |
continue |
| 237 |
|
| 238 |
if name in completed_filenames: |
| 239 |
sys.stderr.write( |
| 240 |
colored( |
| 241 |
"---> Skipping previously tested " + name + "\n", |
| 242 |
YELLOW, |
| 243 |
), |
| 244 |
) |
| 245 |
continue |
| 246 |
else: |
| 247 |
completed_filenames.update(name) |
| 248 |
|
| 249 |
if os.path.isdir(name): |
| 250 |
for root, directories, children in os.walk(name): |
| 251 |
filenames += [ |
| 252 |
os.path.join(root, f) |
| 253 |
for f in children |
| 254 |
if f.endswith(".py") and not f.startswith(".") |
| 255 |
] |
| 256 |
|
| 257 |
directories[:] = [d for d in directories if not d.startswith(".")] |
| 258 |
else: |
| 259 |
verbose_message = "---> Testing with " + name |
| 260 |
sys.stderr.write(colored(verbose_message + "\n", YELLOW)) |
| 261 |
|
| 262 |
if not run( |
| 263 |
os.path.join(name), |
| 264 |
command=args.command, |
| 265 |
verbose=args.verbose, |
| 266 |
options=options, |
| 267 |
): |
| 268 |
return False |
| 269 |
except (UnicodeDecodeError, UnicodeEncodeError) as exception: |
| 270 |
|
| 271 |
print(exception, file=sys.stderr) |
| 272 |
continue |
| 273 |
|
| 274 |
return True |
| 275 |
|
| 276 |
|
| 277 |
def main() -> int: |
| 278 |
"""Run main.""" |
| 279 |
return 0 if check(process_args()) else 1 |
| 280 |
|
| 281 |
|
| 282 |
if __name__ == "__main__": |
| 283 |
try: |
| 284 |
sys.exit(main()) |
| 285 |
except KeyboardInterrupt: |
| 286 |
sys.exit(1) |