ca13e678ae
* Fix unit test parametrize order on Python 3.5. (cherry picked from commit53b230ca74
) * Fix ansible-test unit test execution. (#45772) * Fix ansible-test units requirements install. * Run unit tests as unprivileged user under Docker. (cherry picked from commit379a7f4f5a
) * Run unit tests in parallel. (#45812) (cherry picked from commitabe8e4c9e8
) * Minor fixes for unit test delegation. (cherry picked from commitbe199cfe90
) * add support for opening shell on remote Windows host (#43919) * add support for opening shell on remote Windows host * added arg completion and fix sanity check * remove uneeded arg (cherry picked from commit6ca4ea0c1f
) * Block network access for unit tests in docker. (cherry picked from commit99cac99cbc
) * Make ansible-test available in the bin directory. (#45876) (cherry picked from commitf3d1f9544b
) * Support comments in ansible-test flat files. (cherry picked from commit5a3000af19
) * Fix incorrect use of subprocess.CalledProcessError (#45890) (cherry picked from commit24dd87bd0a
) * Improve ansible-test match error handling. (cherry picked from commit2056c981ae
) * Improve error handling for docs-build test. (cherry picked from commit2148999048
) * Bug fixes and cleanup for ansible-test. (#45991) * Remove unused imports. * Clean up ConfigParser usage in ansible-test. * Fix bare except statements in ansible-test. * Miscellaneous cleanup from PyCharm inspections. * Enable pylint no-self-use for ansible-test. * Remove obsolete pylint ignores for Python 3.7. * Fix shellcheck issuers under newer shellcheck. * Use newer path for ansible-test. * Fix issues in code-smell tests. (cherry picked from commitac492476e5
) * Fix integration test library search path. This prevents tests from loading modules outside the source tree, which could result in testing the wrong module if a system-wide install is present, or custom modules exist. (cherry picked from commitd603cd41fe
) * Update default container to version 1.2.0. (cherry picked from commitd478a4c3f6
) (cherry picked from commit21c4eb8db5
) * Fix ansible-test docker python version handling. This removes the old name based version detection behavior and uses versions defined in the docker completion file instead, as the new containers do not follow the old naming scheme. (cherry picked from commit54937ba784
) * Reduce noise in docs-build test failures. (cherry picked from commit4085d01617
) * Fix ansible-test encoding issues for exceptions. (cherry picked from commit0d7a156319
) * Fix ansible-test multi-group smoke test handling. (#46363) * Fix ansible-test smoke tests across groups. * Fix ansible-test list arg defaults. * Fix ansible-test require and exclude delegation. * Fix detection of Windows specific changes. * Add minimal Windows testing for Python 3.7. (cherry picked from commite53390b3b1
) * Use default-test-container version 1.3.0. (cherry picked from commit6d9be66418
) * Add file exists check in integration-aliases test. (cherry picked from commit33a8be9109
) * Improve ansible-test environment checking between tests. (#46459) * Add unified diff output to environment validation. This makes it easier to see where the environment changed. * Compare Python interpreters by version to pip shebangs. This helps expose cases where pip executables use a different Python interpreter than is expected. * Query `pip.__version__` instead of using `pip --version`. This is a much faster way to query the pip version. It also more closely matches how we invoke pip within ansible-test. * Remove redundant environment scan between tests. This reuses the environment scan from the end of the previous test as the basis for comparison during the next test. (cherry picked from commit0dc7f38787
) * Add symlinks sanity test. (#46467) * Add symlinks sanity test. * Replace legacy test symlinks with actual content. * Remove dir symlink from template_jinja2_latest. * Update import test to use generated library dir. * Fix copy test symlink setup. (cherry picked from commite2b6047514
) * Fix parametrize warning in unit tests. (cherry picked from commit1a28898a00
) * Update MANIFEST.in (#46502) * Update MANIFEST.in: - Remove unnecessary prune. - Include files needed by tests. - Exclude botmeta sanity test. These changes permit sanity tests to pass on sdist output. (cherry picked from commitcbb49f66ec
) * Fix unit tests which modify the source tree. (#45763) * Fix CNOS unit test log usage. * Use temp dir for Galaxy unit tests. * Write to temp files in interfaces_file unit test. * Fix log placement in netapp_e_ldap unit test. (cherry picked from commit0686450cae
) * Fix ansible-test custom docker image traceback. (cherry picked from commit712ad9ed64
) * ansible-test: Create public key creating Windows targets (#43760) * ansible-test: Create public key creating Windows targets * Changed to always set SSH Key for Windows hosts (cherry picked from commitadc0efe10c
) * Fix and re-enable sts_assume_role integration tests (#46026) * Fix the STS assume role error message assertion when the role to assume does not exist. (cherry picked from commit18dc928e28
) * Fix ACI unit test on Python 3.7.0. The previous logic was only needed for pre-release versions of 3.7. (cherry picked from commitc0bf9815c9
) * Remove placeboify from unit tests that are not calling AWS (i.e. creating a recording) (#45754) (cherry picked from commit2167ce6cb6
) * Update sanity test ignore entries.
287 lines
9 KiB
Python
287 lines
9 KiB
Python
"""Sanity test using pylint."""
|
|
from __future__ import absolute_import, print_function
|
|
|
|
import collections
|
|
import json
|
|
import os
|
|
import datetime
|
|
|
|
from lib.sanity import (
|
|
SanitySingleVersion,
|
|
SanityMessage,
|
|
SanityFailure,
|
|
SanitySuccess,
|
|
SanitySkipped,
|
|
)
|
|
|
|
from lib.util import (
|
|
SubprocessError,
|
|
run_command,
|
|
display,
|
|
read_lines_without_comments,
|
|
ConfigParser,
|
|
)
|
|
|
|
from lib.executor import (
|
|
SUPPORTED_PYTHON_VERSIONS,
|
|
)
|
|
|
|
from lib.ansible_util import (
|
|
ansible_environment,
|
|
)
|
|
|
|
from lib.config import (
|
|
SanityConfig,
|
|
)
|
|
|
|
from lib.test import (
|
|
calculate_confidence,
|
|
calculate_best_confidence,
|
|
)
|
|
|
|
PYLINT_SKIP_PATH = 'test/sanity/pylint/skip.txt'
|
|
PYLINT_IGNORE_PATH = 'test/sanity/pylint/ignore.txt'
|
|
|
|
UNSUPPORTED_PYTHON_VERSIONS = (
|
|
'2.6',
|
|
)
|
|
|
|
|
|
class PylintTest(SanitySingleVersion):
|
|
"""Sanity test using pylint."""
|
|
def __init__(self):
|
|
super(PylintTest, self).__init__()
|
|
|
|
self.plugin_dir = 'test/sanity/pylint/plugins'
|
|
self.plugin_names = sorted(p[0] for p in [os.path.splitext(p) for p in os.listdir(self.plugin_dir)] if p[1] == '.py' and p[0] != '__init__')
|
|
|
|
def test(self, args, targets):
|
|
"""
|
|
:type args: SanityConfig
|
|
:type targets: SanityTargets
|
|
:rtype: TestResult
|
|
"""
|
|
if args.python_version in UNSUPPORTED_PYTHON_VERSIONS:
|
|
display.warning('Skipping pylint on unsupported Python version %s.' % args.python_version)
|
|
return SanitySkipped(self.name)
|
|
|
|
skip_paths = read_lines_without_comments(PYLINT_SKIP_PATH)
|
|
|
|
invalid_ignores = []
|
|
|
|
supported_versions = set(SUPPORTED_PYTHON_VERSIONS) - set(UNSUPPORTED_PYTHON_VERSIONS)
|
|
supported_versions = set([v.split('.')[0] for v in supported_versions]) | supported_versions
|
|
|
|
ignore_entries = read_lines_without_comments(PYLINT_IGNORE_PATH)
|
|
ignore = collections.defaultdict(dict)
|
|
line = 0
|
|
|
|
for ignore_entry in ignore_entries:
|
|
line += 1
|
|
|
|
if not ignore_entry:
|
|
continue
|
|
|
|
if ' ' not in ignore_entry:
|
|
invalid_ignores.append((line, 'Invalid syntax'))
|
|
continue
|
|
|
|
path, code = ignore_entry.split(' ', 1)
|
|
|
|
if not os.path.exists(path):
|
|
invalid_ignores.append((line, 'Remove "%s" since it does not exist' % path))
|
|
continue
|
|
|
|
if ' ' in code:
|
|
code, version = code.split(' ', 1)
|
|
|
|
if version not in supported_versions:
|
|
invalid_ignores.append((line, 'Invalid version: %s' % version))
|
|
continue
|
|
|
|
if version != args.python_version and version != args.python_version.split('.')[0]:
|
|
continue # ignore version specific entries for other versions
|
|
|
|
ignore[path][code] = line
|
|
|
|
skip_paths_set = set(skip_paths)
|
|
|
|
paths = sorted(i.path for i in targets.include if (os.path.splitext(i.path)[1] == '.py' or i.path.startswith('bin/')) and i.path not in skip_paths_set)
|
|
|
|
contexts = {}
|
|
remaining_paths = set(paths)
|
|
|
|
def add_context(available_paths, context_name, context_filter):
|
|
"""
|
|
:type available_paths: set[str]
|
|
:type context_name: str
|
|
:type context_filter: (str) -> bool
|
|
"""
|
|
filtered_paths = set(p for p in available_paths if context_filter(p))
|
|
contexts[context_name] = sorted(filtered_paths)
|
|
available_paths -= filtered_paths
|
|
|
|
add_context(remaining_paths, 'ansible-test', lambda p: p.startswith('test/runner/'))
|
|
add_context(remaining_paths, 'units', lambda p: p.startswith('test/units/'))
|
|
add_context(remaining_paths, 'test', lambda p: p.startswith('test/'))
|
|
add_context(remaining_paths, 'hacking', lambda p: p.startswith('hacking/'))
|
|
add_context(remaining_paths, 'modules', lambda p: p.startswith('lib/ansible/modules/'))
|
|
add_context(remaining_paths, 'module_utils', lambda p: p.startswith('lib/ansible/module_utils/'))
|
|
add_context(remaining_paths, 'ansible', lambda p: True)
|
|
|
|
messages = []
|
|
context_times = []
|
|
|
|
test_start = datetime.datetime.utcnow()
|
|
|
|
for context in sorted(contexts):
|
|
context_paths = contexts[context]
|
|
|
|
if not context_paths:
|
|
continue
|
|
|
|
context_start = datetime.datetime.utcnow()
|
|
messages += self.pylint(args, context, context_paths)
|
|
context_end = datetime.datetime.utcnow()
|
|
|
|
context_times.append('%s: %d (%s)' % (context, len(context_paths), context_end - context_start))
|
|
|
|
test_end = datetime.datetime.utcnow()
|
|
|
|
for context_time in context_times:
|
|
display.info(context_time, verbosity=4)
|
|
|
|
display.info('total: %d (%s)' % (len(paths), test_end - test_start), verbosity=4)
|
|
|
|
errors = [SanityMessage(
|
|
message=m['message'].replace('\n', ' '),
|
|
path=m['path'],
|
|
line=int(m['line']),
|
|
column=int(m['column']),
|
|
level=m['type'],
|
|
code=m['symbol'],
|
|
) for m in messages]
|
|
|
|
if args.explain:
|
|
return SanitySuccess(self.name)
|
|
|
|
line = 0
|
|
|
|
filtered = []
|
|
|
|
for error in errors:
|
|
if error.code in ignore[error.path]:
|
|
ignore[error.path][error.code] = None # error ignored, clear line number of ignore entry to track usage
|
|
else:
|
|
filtered.append(error) # error not ignored
|
|
|
|
errors = filtered
|
|
|
|
for invalid_ignore in invalid_ignores:
|
|
errors.append(SanityMessage(
|
|
code='A201',
|
|
message=invalid_ignore[1],
|
|
path=PYLINT_IGNORE_PATH,
|
|
line=invalid_ignore[0],
|
|
column=1,
|
|
confidence=calculate_confidence(PYLINT_IGNORE_PATH, line, args.metadata) if args.metadata.changes else None,
|
|
))
|
|
|
|
for path in skip_paths:
|
|
line += 1
|
|
|
|
if not path:
|
|
continue
|
|
|
|
if not os.path.exists(path):
|
|
# Keep files out of the list which no longer exist in the repo.
|
|
errors.append(SanityMessage(
|
|
code='A101',
|
|
message='Remove "%s" since it does not exist' % path,
|
|
path=PYLINT_SKIP_PATH,
|
|
line=line,
|
|
column=1,
|
|
confidence=calculate_best_confidence(((PYLINT_SKIP_PATH, line), (path, 0)), args.metadata) if args.metadata.changes else None,
|
|
))
|
|
|
|
for path in paths:
|
|
if path not in ignore:
|
|
continue
|
|
|
|
for code in ignore[path]:
|
|
line = ignore[path][code]
|
|
|
|
if not line:
|
|
continue
|
|
|
|
errors.append(SanityMessage(
|
|
code='A102',
|
|
message='Remove since "%s" passes "%s" pylint test' % (path, code),
|
|
path=PYLINT_IGNORE_PATH,
|
|
line=line,
|
|
column=1,
|
|
confidence=calculate_best_confidence(((PYLINT_IGNORE_PATH, line), (path, 0)), args.metadata) if args.metadata.changes else None,
|
|
))
|
|
|
|
if errors:
|
|
return SanityFailure(self.name, messages=errors)
|
|
|
|
return SanitySuccess(self.name)
|
|
|
|
def pylint(self, args, context, paths):
|
|
"""
|
|
:type args: SanityConfig
|
|
:type context: str
|
|
:type paths: list[str]
|
|
:rtype: list[dict[str, str]]
|
|
"""
|
|
rcfile = 'test/sanity/pylint/config/%s' % context
|
|
|
|
if not os.path.exists(rcfile):
|
|
rcfile = 'test/sanity/pylint/config/default'
|
|
|
|
parser = ConfigParser()
|
|
parser.read(rcfile)
|
|
|
|
if parser.has_section('ansible-test'):
|
|
config = dict(parser.items('ansible-test'))
|
|
else:
|
|
config = dict()
|
|
|
|
disable_plugins = set(i.strip() for i in config.get('disable-plugins', '').split(',') if i)
|
|
load_plugins = set(self.plugin_names) - disable_plugins
|
|
|
|
cmd = [
|
|
args.python_executable,
|
|
'-m', 'pylint',
|
|
'--jobs', '0',
|
|
'--reports', 'n',
|
|
'--max-line-length', '160',
|
|
'--rcfile', rcfile,
|
|
'--output-format', 'json',
|
|
'--load-plugins', ','.join(load_plugins),
|
|
] + paths
|
|
|
|
env = ansible_environment(args)
|
|
env['PYTHONPATH'] += '%s%s' % (os.path.pathsep, self.plugin_dir)
|
|
|
|
if paths:
|
|
try:
|
|
stdout, stderr = run_command(args, cmd, env=env, capture=True)
|
|
status = 0
|
|
except SubprocessError as ex:
|
|
stdout = ex.stdout
|
|
stderr = ex.stderr
|
|
status = ex.status
|
|
|
|
if stderr or status >= 32:
|
|
raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
|
|
else:
|
|
stdout = None
|
|
|
|
if not args.explain and stdout:
|
|
messages = json.loads(stdout)
|
|
else:
|
|
messages = []
|
|
|
|
return messages
|