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_register_invalid_check(self):
class InvalidChecker(DummyChecker):
def __init__(self, filename):
pass
def check_dummy(logical, tokens):
if False:
yield
pycodestyle.register_check(InvalidChecker, ['Z741'])
pycodestyle.register_check(check_dummy, ['Z441'])
for checkers in pycodestyle._checks.values():
self.assertTrue(DummyChecker not in checkers)
self.assertTrue(check_dummy not in checkers)
self.assertRaises(TypeError, pycodestyle.register_check)
def test_register_invalid_check(self):
class InvalidChecker(DummyChecker):
def __init__(self, filename):
pass
def check_dummy(logical, tokens):
if False:
yield
pycodestyle.register_check(InvalidChecker, ['Z741'])
pycodestyle.register_check(check_dummy, ['Z441'])
for checkers in pycodestyle._checks.values():
self.assertTrue(DummyChecker not in checkers)
self.assertTrue(check_dummy not in checkers)
self.assertRaises(TypeError, pycodestyle.register_check)
def test_check_nullbytes(self):
pycodestyle.register_check(DummyChecker, ['Z701'])
pep8style = pycodestyle.StyleGuide()
count_errors = pep8style.input_file('stdin', lines=['\x00\n'])
stdout = sys.stdout.getvalue()
if 'SyntaxError' in stdout:
# PyPy 2.2 returns a SyntaxError
expected = "stdin:1:2: E901 SyntaxError"
elif 'ValueError' in stdout:
# Python 3.5.
expected = "stdin:1:1: E901 ValueError"
else:
expected = "stdin:1:1: E901 TypeError"
self.assertTrue(stdout.startswith(expected),
msg='Output %r does not start with %r' %
(stdout, expected))
def test_check_unicode(self):
# Do not crash if lines are Unicode (Python 2.x)
pycodestyle.register_check(DummyChecker, ['Z701'])
source = '#\n'
if hasattr(source, 'decode'):
source = source.decode('ascii')
pep8style = pycodestyle.StyleGuide()
count_errors = pep8style.input_file('stdin', lines=[source])
self.assertFalse(sys.stdout)
self.assertFalse(sys.stderr)
self.assertEqual(count_errors, 0)
def test_register_ast_check(self):
pycodestyle.register_check(DummyChecker, ['Z701'])
self.assertTrue(DummyChecker in pycodestyle._checks['tree'])
codes, args = pycodestyle._checks['tree'][DummyChecker]
self.assertTrue('Z701' in codes)
self.assertTrue(args is None)
options = pycodestyle.StyleGuide().options
self.assertTrue(any(cls == DummyChecker
for name, cls, args in options.ast_checks))
# Copyright 2017 Palantir Technologies, Inc.
import logging
import pycodestyle
from autopep8 import continued_indentation as autopep8_c_i
from pyls import hookimpl, lsp
# Check if autopep8's continued_indentation implementation
# is overriding pycodestyle's and if so, re-register
# the check using pycodestyle's implementation as expected
if autopep8_c_i in pycodestyle._checks['logical_line']:
del pycodestyle._checks['logical_line'][autopep8_c_i]
pycodestyle.register_check(pycodestyle.continued_indentation)
log = logging.getLogger(__name__)
@hookimpl
def pyls_lint(config, document):
settings = config.plugin_settings('pycodestyle')
log.debug("Got pycodestyle settings: %s", settings)
opts = {
'exclude': settings.get('exclude'),
'filename': settings.get('filename'),
'hang_closing': settings.get('hangClosing'),
'ignore': settings.get('ignore'),
'max_line_length': settings.get('maxLineLength'),
'select': settings.get('select'),
def _register_extensions():
"""Register all the extensions."""
extensions = util.OrderedSet()
extensions.add(('pycodestyle', pep8.__version__))
parser_hooks = []
options_hooks = []
ignored_hooks = []
try:
from pkg_resources import iter_entry_points
except ImportError:
pass
else:
for entry in iter_entry_points('flake8.extension'):
# Do not verify that the requirements versions are valid
checker = _load_entry_point(entry, verify_requirements=False)
pep8.register_check(checker, codes=[entry.name])
extensions.add((checker.name, checker.version))
if hasattr(checker, 'add_options'):
parser_hooks.append(checker.add_options)
if hasattr(checker, 'parse_options'):
options_hooks.append(checker.parse_options)
if getattr(checker, 'off_by_default', False) is True:
ignored_hooks.append(entry.name)
return extensions, parser_hooks, options_hooks, ignored_hooks
if (
indent_next and
not last_line_begins_with_multiline and
pycodestyle.expand_indent(line) == indent_level + DEFAULT_INDENT_SIZE
):
pos = (start[0], indent[0] + 4)
desired_indent = indent_level + 2 * DEFAULT_INDENT_SIZE
if visual_indent:
yield (pos, 'E129 {0}'.format(desired_indent))
else:
yield (pos, 'E125 {0}'.format(desired_indent))
del pycodestyle._checks['logical_line'][pycodestyle.continued_indentation]
pycodestyle.register_check(continued_indentation)
class FixPEP8(object):
"""Fix invalid code.
Fixer methods are prefixed "fix_". The _fix_source() method looks for these
automatically.
The fixer method can take either one or two arguments (in addition to
self). The first argument is "result", which is the error information from
pycodestyle. The second argument, "logical", is required only for
logical-line fixes.
The fixer method can return the list of modified lines or None. An empty
list would mean that no changes were made. None would mean that only the
if previous_logical.startswith('def '):
if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line):
yield (0, 'E303 too many blank lines ({0})'.format(blank_lines))
elif pycodestyle.DOCSTRING_REGEX.match(previous_logical):
# Missing blank line between class docstring and method declaration.
if (
indent_level and
not blank_lines and
not blank_before and
logical_line.startswith(('def ')) and
'(self' in logical_line
):
yield (0, 'E301 expected 1 blank line, found 0')
pycodestyle.register_check(extended_blank_lines)
def continued_indentation(logical_line, tokens, indent_level, indent_char,
noqa):
"""Override pycodestyle's function to provide indentation information."""
first_row = tokens[0][2][0]
nrows = 1 + tokens[-1][2][0] - first_row
if noqa or nrows == 1:
return
# indent_next tells us whether the next block is indented. Assuming
# that it is indented by 4 spaces, then we should not allow 4-space
# indents on the final continuation line. In turn, some other
# indents are allowed to have an extra 4 spaces.
indent_next = logical_line.endswith(':')
if previous_logical.startswith('def '):
if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line):
yield (0, 'E303 too many blank lines ({0})'.format(blank_lines))
elif pycodestyle.DOCSTRING_REGEX.match(previous_logical):
# Missing blank line between class docstring and method declaration.
if (
indent_level and
not blank_lines and
not blank_before and
logical_line.startswith(('def ')) and
'(self' in logical_line
):
yield (0, 'E301 expected 1 blank line, found 0')
pycodestyle.register_check(extended_blank_lines)
def continued_indentation(logical_line, tokens, indent_level, indent_char,
noqa):
"""Override pycodestyle's function to provide indentation information."""
first_row = tokens[0][2][0]
nrows = 1 + tokens[-1][2][0] - first_row
if noqa or nrows == 1:
return
# indent_next tells us whether the next block is indented. Assuming
# that it is indented by 4 spaces, then we should not allow 4-space
# indents on the final continuation line. In turn, some other
# indents are allowed to have an extra 4 spaces.
indent_next = logical_line.endswith(':')