Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_styleguide_init_report(self):
style = pycodestyle.StyleGuide(paths=[E11])
standard_report = pycodestyle.StandardReport
self.assertEqual(style.options.reporter, standard_report)
self.assertEqual(type(style.options.report), standard_report)
class MinorityReport(pycodestyle.BaseReport):
pass
report = style.init_report(MinorityReport)
self.assertEqual(style.options.report, report)
self.assertEqual(type(report), MinorityReport)
style = pycodestyle.StyleGuide(paths=[E11], reporter=MinorityReport)
self.assertEqual(type(style.options.report), MinorityReport)
self.assertEqual(style.options.reporter, MinorityReport)
def test_styleguide_init_report(self):
style = pycodestyle.StyleGuide(paths=[E11])
standard_report = pycodestyle.StandardReport
self.assertEqual(style.options.reporter, standard_report)
self.assertEqual(type(style.options.report), standard_report)
class MinorityReport(pycodestyle.BaseReport):
pass
report = style.init_report(MinorityReport)
self.assertEqual(style.options.report, report)
self.assertEqual(type(report), MinorityReport)
style = pycodestyle.StyleGuide(paths=[E11], reporter=MinorityReport)
self.assertEqual(type(style.options.report), MinorityReport)
self.assertEqual(style.options.reporter, MinorityReport)
SELFTEST_REGEX = re.compile(r'\b(Okay|[EW]\d{3}):\s(.*)')
ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
class PseudoFile(list):
"""Simplified file interface."""
write = list.append
def getvalue(self):
return ''.join(self)
def flush(self):
pass
class TestReport(StandardReport):
"""Collect the results for the tests."""
def __init__(self, options):
options.benchmark_keys += ['test cases', 'failed tests']
super(TestReport, self).__init__(options)
self._verbose = options.verbose
def error(self, line_number, offset, text, check):
"""Report an error, according to options."""
code = text[:4]
if code in self.counters:
self.counters[code] += 1
else:
self.counters[code] = 1
detailed_code = '%s:%s:%s' % (code, line_number, offset + 1)
# Don't care about expected errors or warnings
def test_own_dog_food(self):
files = [pycodestyle.__file__.rstrip('oc'), __file__.rstrip('oc'),
os.path.join(ROOT_DIR, 'setup.py')]
report = self._style.init_report(pycodestyle.StandardReport)
report = self._style.check_files(files)
self.assertFalse(report.total_errors,
msg='Failures: %s' % report.messages)
parser = kwargs.pop('parser', None)
# build options from dict
options_dict = dict(*args, **kwargs)
arglist = None if parse_argv else options_dict.get('paths', None)
options, self.paths = process_options(
arglist, parse_argv, config_file, parser)
if options_dict:
options.__dict__.update(options_dict)
if 'paths' in options_dict:
self.paths = options_dict['paths']
self.runner = self.input_file
self.options = options
if not options.reporter:
options.reporter = BaseReport if options.quiet else StandardReport
options.select = tuple(options.select or ())
if not (options.select or options.ignore or
options.testsuite or options.doctest) and DEFAULT_IGNORE:
# The default choice: ignore controversial checks
options.ignore = tuple(DEFAULT_IGNORE.split(','))
else:
# Ignore all checks which are not explicitly selected
options.ignore = ('',) if options.select else tuple(options.ignore)
options.benchmark_keys = BENCHMARK_KEYS[:]
options.ignore_code = self.ignore_code
options.physical_checks = self.get_checks('physical_line')
options.logical_checks = self.get_checks('logical_line')
options.ast_checks = self.get_checks('tree')
self.init_report()
def __init__(self, options):
super(StandardReport, self).__init__(options)
self._fmt = REPORT_FORMAT.get(options.format.lower(),
options.format)
self._repeat = options.repeat
self._show_source = options.show_source
self._show_pep8 = options.show_pep8
def _retry_serial(self, func, *args, **kwargs):
"""This will retry the passed function in serial if necessary.
In the event that we encounter an OSError with an errno in
:attr:`serial_retry_errors`, this function will retry this function
using pep8's default Report class which operates in serial.
"""
try:
return func(*args, **kwargs)
except OSError as oserr:
if oserr.errno in self.serial_retry_errors:
self.init_report(pep8.StandardReport)
else:
raise
return func(*args, **kwargs)
def check_pycodestyle(file_path, config_path=None):
import pycodestyle
if not file_path.endswith(".py"):
return True, None
# A custom reporter class for pycodestyle that checks for disabled errors
# and formats the style report output.
class CustomReporter(pycodestyle.StandardReport):
def get_file_results(self):
# Iterates through the lines of code that generated lint errors and
# checks if the given error has been disabled for that line via an
# inline comment (e.g., # pycodestyle: disable=E201,E226). Those
# that have been disabled are not treated as errors.
self._deferred_print.sort()
results = []
prev_line_num = -1
prev_line_errs = []
for line_number, _, code, text, _ in self._deferred_print:
if prev_line_num == line_number:
err_codes = prev_line_errs
else:
line = self.lines[line_number - 1]
m = PYCODESTYLE_COMMENT_PATTERN.search(line)
if m and m.group(0):
print(line.rstrip())
print(re.sub(r'\S', ' ', line[:offset]) + '^')
if self._show_pep8 and doc:
print(' ' + doc.strip())
# stdout is block buffered when not stdout.isatty().
# line can be broken where buffer boundary since other processes
# write to same file.
# flush() after print() to avoid buffer boundary.
# Typical buffer size is 8192. line written safely when
# len(line) < 8192.
sys.stdout.flush()
return self.file_errors
class DiffReport(StandardReport):
"""Collect and print the results for the changed lines only."""
def __init__(self, options):
super(DiffReport, self).__init__(options)
self._selected = options.selected_lines
def error(self, line_number, offset, text, check):
if line_number not in self._selected[self.filename]:
return
return super(DiffReport, self).error(line_number, offset, text, check)
class StyleGuide(object):
"""Initialize a PEP-8 instance with few options."""
def __init__(self, *args, **kwargs):
name = 'pep8_errors'
msgs = {'E9989': ('Found PEP8 style error at %s', 'pep8-errors', '')}
options = ()
# this is important so that your checker is executed before others
priority = -1
def process_module(self, node):
style_guide = pycodestyle.StyleGuide(paths=[node.stream().name], reporter=JSONReport, ignore=IGNORED_CHECKS)
report = style_guide.check_files()
for line_num, msg in report.get_file_results():
self.add_message('pep8-errors', line=line_num, args=msg)
class JSONReport(pycodestyle.StandardReport):
def get_file_results(self):
self._deferred_print.sort()
return [
(line_number, f'line {line_number}, column {offset}: {text}')
for line_number, offset, _, text, _ in self._deferred_print
]
def register(linter):
"""required method to auto register this checker"""
linter.register_checker(PycodestyleChecker(linter))