python-botocore/tests/functional/test_six_imports.py

59 lines
1.8 KiB
Python
Raw Permalink Normal View History

2017-06-27 11:52:19 +02:00
import ast
2022-05-26 00:10:07 +02:00
import os
2017-06-27 11:52:19 +02:00
2021-10-04 18:33:37 +02:00
import pytest
2022-05-26 00:10:07 +02:00
import botocore
2017-06-27 11:52:19 +02:00
ROOTDIR = os.path.dirname(botocore.__file__)
2021-10-04 18:33:37 +02:00
def _all_files():
2017-06-27 11:52:19 +02:00
for rootdir, dirnames, filenames in os.walk(ROOTDIR):
if 'vendored' in dirnames:
# We don't need to lint our vendored packages.
dirnames.remove('vendored')
for filename in filenames:
if not filename.endswith('.py'):
continue
2021-10-04 18:33:37 +02:00
yield os.path.join(rootdir, filename)
2017-06-27 11:52:19 +02:00
2021-10-04 18:33:37 +02:00
@pytest.mark.parametrize("filename", _all_files())
def test_no_bare_six_imports(filename):
2017-06-27 11:52:19 +02:00
with open(filename) as f:
contents = f.read()
parsed = ast.parse(contents, filename)
2021-11-03 18:14:15 +01:00
SixImportChecker(filename).visit(parsed)
2017-06-27 11:52:19 +02:00
class SixImportChecker(ast.NodeVisitor):
def __init__(self, filename):
self.filename = filename
def visit_Import(self, node):
for alias in node.names:
if getattr(alias, 'name', '') == 'six':
line = self._get_line_content(self.filename, node.lineno)
raise AssertionError(
"A bare 'import six' was found in %s:\n"
"\n%s: %s\n"
2022-05-26 00:10:07 +02:00
"Please use 'from botocore.compat import six' instead"
% (self.filename, node.lineno, line)
)
2017-06-27 11:52:19 +02:00
def visit_ImportFrom(self, node):
if node.module == 'six':
line = self._get_line_content(self.filename, node.lineno)
raise AssertionError(
"A bare 'from six import ...' was found in %s:\n"
"\n%s:%s\n"
2022-05-26 00:10:07 +02:00
"Please use 'from botocore.compat import six' instead"
% (self.filename, node.lineno, line)
)
2017-06-27 11:52:19 +02:00
def _get_line_content(self, filename, lineno):
with open(filename) as f:
contents = f.readlines()
return contents[lineno - 1]