Example #1
0
    def test_config(self):
        from pylama.config import get_parser, get_config

        parser = get_parser()
        self.assertTrue(parser)

        config = get_config()
        self.assertTrue(config)

        options = parse_options()
        self.assertTrue(options)
        self.assertTrue(options.skip)
        self.assertEqual(options.path, 'pylama')

        options = parse_options(['-l', 'pep257,pep8', '-i', 'E'])
        self.assertEqual(set(options.linters), set(['pep257', 'pep8']))
        self.assertEqual(options.ignore, ['E'])

        options = parse_options(['-l', 'gjslint,pep8', '-i', 'E:0010'])
        self.assertEqual(set(options.linters), set(['gjslint', 'pep8']))
        self.assertEqual(options.ignore, ['E:0010'])

        options = parse_options('-o dummy dummy.py'.split())
        self.assertEqual(
            set(options.linters), set(['pep8', 'mccabe', 'pyflakes']))
        self.assertEqual(options.skip, [])
Example #2
0
def test_prepare_params():
    p1 = dict(ignore='W', select='R01', skip='0')
    p2 = dict(ignore='E34,R45', select='E')
    options = parse_options(ignore=['D'], config=False)
    params = prepare_params(p1, p2, options)
    assert params == {
        'ignore': set(['R45', 'E34', 'W', 'D']), 'select': set(['R01', 'E']), 'skip': False}
Example #3
0
def shell(args: List[str] = None, error: bool = True):
    """Endpoint for console.

    Parse a command arguments, configuration files and run a checkers.
    """
    if args is None:
        args = sys.argv[1:]

    options = parse_options(args)
    setup_logger(options)
    LOGGER.info(options)

    # Install VSC hook
    if options.hook:
        from .hook import install_hook  # noqa

        for path in options.paths:
            return install_hook(path)

    if options.from_stdin and not options.paths:
        LOGGER.error("--from-stdin requires a filename")
        return sys.exit(1)

    errors = check_paths(
        options.paths,
        code=read_stdin() if options.from_stdin else None,
        options=options,
        rootdir=CURDIR,
    )
    display_errors(errors, options)

    if error:
        sys.exit(int(bool(errors)))

    return errors
Example #4
0
def test_pyflakes():
    options = parse_options(linters=['pyflakes'], config=False)
    assert options.linters
    errors = run('dummy.py',
                 code="\n".join(
                     ["import sys", "def test():", "    unused = 1"]),
                 options=options)
    assert len(errors) == 2
Example #5
0
def test_pep8():
    options = parse_options(linters=['pep8'], config=False)
    errors = run('dummy.py', options=options)
    assert len(errors) == 3

    options.linters_params['pep8'] = dict(max_line_length=60)
    errors = run('dummy.py', options=options)
    assert len(errors) == 11
Example #6
0
def test_pep8():
    options = parse_options(linters=['pep8'], config=False)
    errors = run('dummy.py', options=options)
    assert len(errors) == 2

    options.linters_params['pep8'] = dict(max_line_length=60)
    errors = run('dummy.py', options=options)
    assert len(errors) == 11
Example #7
0
def test_linters_params():
    options = parse_options(linters='mccabe', config=False)
    options.linters_params['mccabe'] = dict(complexity=2)
    errors = run('dummy.py', options=options)
    assert len(errors) == 13

    options.linters_params['mccabe'] = dict(complexity=20)
    errors = run('dummy.py', options=options)
    assert not errors
Example #8
0
def test_prepare_params():
    p1 = dict(ignore='W', select='R01', skip='0')
    p2 = dict(ignore='E34,R45', select='E')
    options = parse_options(ignore=['D'], config=False)
    params = prepare_params(p1, p2, options)
    assert params == {
        'ignore': set(['R45', 'E34', 'W', 'D']),
        'select': set(['R01', 'E']),
        'skip': False, 'linters': []}
Example #9
0
def test_linters_params():
    options = parse_options(linters='mccabe', config=False)
    options.linters_params['mccabe'] = dict(complexity=1)
    errors = run('dummy.py', options=options)
    assert len(errors) == 1

    options.linters_params['mccabe'] = dict(complexity=20)
    errors = run('dummy.py', options=options)
    assert not errors
Example #10
0
def test_pycodestyle():
    options = parse_options(linters=['pycodestyle'], config=False)
    assert len(options.linters) == 1
    errors = run('dummy.py', options=options)
    assert len(errors) == 2

    options.linters_params['pycodestyle'] = dict(max_line_length=60)
    errors = run('dummy.py', options=options)
    assert len(errors) == 11
Example #11
0
def test_pyflakes():
    options = parse_options(linters=['pyflakes'], config=False)
    assert options.linters
    errors = run('dummy.py', code="\n".join([
        "import sys",
        "def test():",
        "    unused = 1"
    ]), options=options)
    assert len(errors) == 2
Example #12
0
def test_shell():
    errors = shell('-o dummy dummy.py'.split(), error=False)
    assert errors

    options = parse_options()
    errors = check_files(['dummy.py'], options=options, error=False)
    assert errors

    errors = shell(['unknown.py'], error=False)
    assert not errors
Example #13
0
def test_pyflakes():
    options = parse_options(linters=['pyflakes'], config=False)
    assert options.linters
    errors = run('dummy.py', code="""
import sys

def test():
    unused = 1
""", options=options)
    assert len(errors) == 2
Example #14
0
def test_config():
    config = get_config()
    assert config

    options = parse_options()
    assert options
    assert options.skip
    assert not options.verbose
    assert options.paths == ['pylama']

    options = parse_options(['-l', 'pydocstyle,pycodestyle', '-i', 'E'])
    linters, _ = zip(*options.linters)
    assert set(linters) == set(['pydocstyle', 'pycodestyle'])
    assert options.ignore == ['E']

    options = parse_options('-o dummy dummy.py'.split())
    linters, _ = zip(*options.linters)
    assert set(linters) == set(['pycodestyle', 'mccabe', 'pyflakes'])
    assert options.skip == []
Example #15
0
def git_hook(error=True):
    """Run pylama after git commit."""
    _, files_modified, _ = run("git diff-index --cached --name-only HEAD")

    options = parse_options()
    setup_logger(options)
    candidates = [f.decode("utf-8") for f in files_modified]
    if candidates:
        errors = check_paths(candidates, options, rootdir=getcwd())
        display_errors(errors, options)
        sys.exit(int(error and bool(errors)))
Example #16
0
    def test_shell(self):
        from pylama.main import shell, check_files

        errors = shell('-o dummy dummy.py'.split(), error=False)
        self.assertTrue(errors)

        options = parse_options()
        errors = check_files(['dummy.py'], options=options, error=False)
        self.assertTrue(errors)

        errors = shell(['unknown.py'], error=False)
        self.assertFalse(errors)
Example #17
0
    def test_shell(self):
        from pylama.main import shell, check_files

        errors = shell('-o dummy dummy.py'.split(), error=False)
        self.assertTrue(errors)

        options = parse_options()
        errors = check_files(['dummy.py'], options=options, error=False)
        self.assertTrue(errors)

        errors = shell(['unknown.py'], error=False)
        self.assertTrue(errors)
Example #18
0
def test_pycodestyle():
    options = parse_options(linters=['pycodestyle'], config=False)
    assert len(options.linters) == 1
    errors = run('dummy.py', options=options)
    numbers = [error.number for error in errors]
    assert len(errors) == 4
    assert 'E265' in numbers
    assert 'E301' in numbers
    assert 'E501' in numbers

    options.linters_params['pycodestyle'] = dict(max_line_length=60)
    errors = run('dummy.py', options=options)
    assert len(errors) == 13
Example #19
0
def test_pycodestyle():
    options = parse_options(linters=['pycodestyle'], config=False)
    assert len(options.linters) == 1
    errors = run('dummy.py', options=options)
    numbers = [error.number for error in errors]
    assert len(errors) == 4
    assert 'E265' in numbers
    assert 'E301' in numbers
    assert 'E501' in numbers

    options.linters_params['pycodestyle'] = dict(max_line_length=60)
    errors = run('dummy.py', options=options)
    assert len(errors) == 13
Example #20
0
    def test_config(self):
        from pylama.config import get_parser, get_config

        parser = get_parser()
        self.assertTrue(parser)

        config = get_config()
        self.assertTrue(config)

        options = parse_options()
        self.assertTrue(options)
        self.assertTrue(options.skip)
        self.assertEqual(options.path, 'pylama')

        options = parse_options(['-l', 'pep257,pep8', '-i', 'E'])
        linters, _ = zip(*options.linters)
        self.assertEqual(set(linters), set(['pep257', 'pep8']))
        self.assertEqual(options.ignore, ['E'])

        options = parse_options('-o dummy dummy.py'.split())
        linters, _ = zip(*options.linters)
        self.assertEqual(set(linters), set(['pep8', 'mccabe', 'pyflakes']))
        self.assertEqual(options.skip, [])
Example #21
0
def test_ignore_select():
    options = parse_options()
    options.ignore = ['E301', 'D102']
    options.linters = ['pep8', 'pep257', 'pyflakes', 'mccabe']
    errors = run('dummy.py', options=options)
    assert len(errors) == 15

    options.ignore = ['E3', 'D']
    errors = run('dummy.py', options=options)
    assert len(errors) == 0

    options.select = ['E301']
    errors = run('dummy.py', options=options)
    assert len(errors) == 1
    assert errors[0]['col']
Example #22
0
def test_ignore_select():
    options = parse_options()
    options.ignore = ['E301', 'D102']
    options.linters = ['pycodestyle', 'pydocstyle', 'pyflakes', 'mccabe']
    errors = run('dummy.py', options=options)
    assert len(errors) == 17

    options.ignore = ['E3', 'D']
    errors = run('dummy.py', options=options)
    assert len(errors) == 0

    options.select = ['E301']
    errors = run('dummy.py', options=options)
    assert len(errors) == 1
    assert errors[0]['col']
Example #23
0
def test_ignore_select():
    options = parse_options()
    options.ignore = ['E301', 'D102']
    options.linters = ['pep8', 'pep257', 'pyflakes', 'mccabe']
    errors = run('dummy.py', options=options)
    assert len(errors) == 16

    options.ignore = ['E3', 'D']
    errors = run('dummy.py', options=options)
    assert len(errors) == 1

    options.select = ['E301']
    errors = run('dummy.py', options=options)
    assert len(errors) == 2
    assert errors[0]['col']
Example #24
0
def test_pylint():
    from pylama.core import run
    from pylama.config import parse_options

    options = parse_options(linters=['pylint'], config=False)
    options.ignore = set(['R0912', 'C0111', 'I0011', 'F0401'])
    errors = run('dummy.py', options=options)
    assert len(errors) == 3
    assert errors[0].number == 'W0611'

    options.linters_params['pylint'] = dict(disable="W")
    errors = run('dummy.py', options=options)
    assert len(errors) == 1
    assert errors[0].number == 'E0602'

    options.linters_params['pylint']['max-line_length'] = 200
    errors = run('dummy.py', options=options)
    assert len(errors) == 1
Example #25
0
def test_pylint():
    from pylama.core import run
    from pylama.config import parse_options

    options = parse_options(linters=['pylint'], config=False)
    options.ignore = set(['R0912', 'C0111', 'I0011', 'F0401'])
    errors = run('dummy.py', options=options)
    assert len(errors) == 4
    assert errors[0].number == 'W0611'

    options.linters_params['pylint'] = dict(disable="W")
    errors = run('dummy.py', options=options)
    assert len(errors) == 1
    assert errors[0].number == 'E0602'

    options.linters_params['pylint']['max-line_length'] = 200
    errors = run('dummy.py', options=options)
    assert len(errors) == 1
Example #26
0
def test_pylint():
    from pylama.core import run
    from pylama.config import parse_options

    options = parse_options(linters=['pylint'], config=False)
    options.ignore = set(['R0912', 'C0111'])
    errors = run('pylama_pylint/pylint/utils.py', options=options)
    assert len(errors) == 29
    assert errors[0].number == 'W0622'

    options.linters_params['pylint'] = dict(disable="W")
    errors = run('pylama_pylint/pylint/utils.py', options=options)
    assert len(errors) == 21
    assert errors[0].number == 'C0301'

    options.linters_params['pylint']['max-line_length'] = 200
    errors = run('pylama_pylint/pylint/utils.py', options=options)
    assert len(errors) == 3
Example #27
0
def test_pylint():
    from pylama.core import run
    from pylama.config import parse_options

    options = parse_options(linters=["pylint"], config=False)
    options.ignore = set(["R0912", "C0111", "I0011", "F0401"])
    errors = run("dummy.py", options=options)
    assert len(errors) == 3
    assert errors[0].number == "W0611"

    options.linters_params["pylint"] = dict(disable="W")
    errors = run("dummy.py", options=options)
    assert len(errors) == 1
    assert errors[0].number == "E0602"

    options.linters_params["pylint"]["max-line_length"] = 200
    errors = run("dummy.py", options=options)
    assert len(errors) == 1
Example #28
0
def hg_hook(_, repo, node=None, **kwargs):  # noqa
    """Run pylama after mercurial commit."""
    seen = set()
    candidates = []
    if len(repo):
        for rev in range(repo[node], len(repo)):
            for file_ in repo[rev].files():
                file_ = op.join(repo.root, file_)
                if file_ in seen or not op.exists(file_):
                    continue
                seen.add(file_)
                candidates.append(file_)

    options = parse_options()
    setup_logger(options)
    if candidates:
        errors = check_paths(candidates, options)
        display_errors(errors, options)
        sys.exit(int(bool(errors)))
Example #29
0
def test_ignore_select():
    options = parse_options()
    options.ignore = ['E301', 'D102']
    options.linters = ['pycodestyle', 'pydocstyle', 'pyflakes', 'mccabe']
    errors = run('dummy.py', options=options)
    assert len(errors) == 32

    numbers = [error.number for error in errors]
    assert 'D100' in numbers
    assert 'E301' not in numbers
    assert 'D102' not in numbers

    options.ignore = ['E3', 'D', 'E2', 'E8']
    errors = run('dummy.py', options=options)
    assert not errors

    options.select = ['E301']
    errors = run('dummy.py', options=options)
    assert len(errors) == 1
    assert errors[0]['col']
Example #30
0
def test_mypy():
    if sys.version_info.major >= 3 and sys.version_info.minor >= 5:
        options = parse_options(linters=['mypy'])
        assert len(options.linters) == 1
        errors = run('dummy.py', options=options)
        assert len(errors) == 1
Example #31
0
def test_pydocstyle():
    options = parse_options(linters=['pydocstyle'])
    assert len(options.linters) == 1
    errors = run('dummy.py', options=options)
    assert errors
Example #32
0
def test_mypy():
    if sys.version_info.major >= 3 and sys.version_info.minor >= 5:
        options = parse_options(linters=['mypy'])
        assert len(options.linters) == 1
        errors = run('dummy.py', options=options)
        assert len(errors) == 1
Example #33
0
def test_checkpath():
    path = op.abspath('dummy.py')
    options = parse_options([path])
    result = check_path(options)
    assert result
    assert result[0].filename == 'dummy.py'
Example #34
0
    def test_async(self):
        options = parse_options(async=True, linters=['pep8'])
        errors = async_check_files(['dummy.py'], options)

        self.assertTrue(errors)
Example #35
0
    def test_checkpath(self):
        options = parse_options(linters=['pep8'])
        errors = check_path('dummy.py', options)

        self.assertTrue(errors)
        self.assertEqual(errors[0]['rel'], 'dummy.py')
Example #36
0
def test_checkpath():
    options = parse_options(linters=['pep8'])
    errors = check_path('dummy.py', options)
    assert errors
    assert errors[0]['rel'] == 'dummy.py'
Example #37
0
def test_sort():
    options = parse_options()
    options.sort = ['C', 'D']
    errors = run('dummy.py', options=options)
    assert errors[0].type == 'C'
Example #38
0
def test_checkpath():
    path = op.abspath('dummy.py')
    options = parse_options([path])
    result = check_path(options)
    assert result
    assert result[0].filename == 'dummy.py'
Example #39
0
def test_pep257():
    options = parse_options(linters=['pep257'])
    errors = run('dummy.py', options=options)
    assert errors
Example #40
0
def test_sort():
    options = parse_options()
    options.sort = ['C', 'D']
    errors = run('dummy.py', options=options)
    assert errors[0].type == 'C'
Example #41
0
def code_check():
    """Run pylama and check current file.

    :return bool:

    """
    with silence_stderr():

        from pylama.core import run
        from pylama.config import parse_options

        if not env.curbuf.name:
            return env.stop()

        linters = env.var('g:pymode_lint_checkers')
        env.debug(linters)

        # Fixed in v0.9.3: these two parameters may be passed as strings.
        # DEPRECATE: v:0.10.0: need to be set as lists.
        if isinstance(env.var('g:pymode_lint_ignore'), str):
            raise ValueError ('g:pymode_lint_ignore should have a list type')
        else:
            ignore = env.var('g:pymode_lint_ignore')
        if isinstance(env.var('g:pymode_lint_select'), str):
            raise ValueError ('g:pymode_lint_select should have a list type')
        else:
            select = env.var('g:pymode_lint_select')
        options = parse_options(
            linters=linters, force=1,
            ignore=ignore,
            select=select,
        )
        env.debug(options)

        for linter in linters:
            opts = env.var('g:pymode_lint_options_%s' % linter, silence=True)
            if opts:
                options.linters_params[linter] = options.linters_params.get(
                    linter, {})
                options.linters_params[linter].update(opts)

        path = os.path.relpath(env.curbuf.name, env.curdir)
        env.debug("Start code check: ", path)

        if getattr(options, 'skip', None) and any(p.match(path) for p in options.skip):  # noqa
            env.message('Skip code checking.')
            env.debug("Skipped")
            return env.stop()

        if env.options.get('debug'):
            from pylama.core import LOGGER, logging
            LOGGER.setLevel(logging.DEBUG)

        errors = run(path, code='\n'.join(env.curbuf) + '\n', options=options)

    env.debug("Find errors: ", len(errors))
    sort_rules = env.var('g:pymode_lint_sort')

    def __sort(e):
        try:
            return sort_rules.index(e.get('type'))
        except ValueError:
            return 999

    if sort_rules:
        env.debug("Find sorting: ", sort_rules)
        errors = sorted(errors, key=__sort)

    for e in errors:
        e._info['bufnr'] = env.curbuf.number
        if e._info['col'] is None:
            e._info['col'] = 1

    env.run('g:PymodeLocList.current().extend', [e._info for e in errors])
Example #42
0
def code_check():
    """Run pylama and check current file.

    :return bool:

    """
    with silence_stderr():

        from pylama.core import run
        from pylama.config import parse_options

        if not env.curbuf.name:
            return env.stop()

        linters = env.var('g:pymode_lint_checkers')
        env.debug(linters)

        # Fixed in v0.9.3: these two parameters may be passed as strings.
        # DEPRECATE: v:0.10.0: need to be set as lists.
        if isinstance(env.var('g:pymode_lint_ignore'), str):
            raise ValueError ('g:pymode_lint_ignore should have a list type')
        else:
            ignore = env.var('g:pymode_lint_ignore')
        if isinstance(env.var('g:pymode_lint_select'), str):
            raise ValueError ('g:pymode_lint_select should have a list type')
        else:
            select = env.var('g:pymode_lint_select')
        options = parse_options(
            linters=linters, force=1,
            ignore=ignore,
            select=select,
        )
        env.debug(options)

        for linter in linters:
            opts = env.var('g:pymode_lint_options_%s' % linter, silence=True)
            if opts:
                options.linters_params[linter] = options.linters_params.get(
                    linter, {})
                options.linters_params[linter].update(opts)

        path = os.path.relpath(env.curbuf.name, env.curdir)
        env.debug("Start code check: ", path)

        if getattr(options, 'skip', None) and any(p.match(path) for p in options.skip):  # noqa
            env.message('Skip code checking.')
            env.debug("Skipped")
            return env.stop()

        if env.options.get('debug'):
            from pylama.core import LOGGER, logging
            LOGGER.setLevel(logging.DEBUG)

        errors = run(path, code='\n'.join(env.curbuf) + '\n', options=options)

    env.debug("Find errors: ", len(errors))
    sort_rules = env.var('g:pymode_lint_sort')

    def __sort(e):
        try:
            return sort_rules.index(e.get('type'))
        except ValueError:
            return 999

    if sort_rules:
        env.debug("Find sorting: ", sort_rules)
        errors = sorted(errors, key=__sort)

    for e in errors:
        e._info['bufnr'] = env.curbuf.number
        if e._info['col'] is None:
            e._info['col'] = 1

    env.run('g:PymodeLocList.current().extend', [e._info for e in errors])
Example #43
0
def test_async():
    options = parse_options(config=False)
    errors = check_async(['dummy.py'], options=options, rootdir='.')
    assert errors
Example #44
0
    def test_checkpath(self):
        options = parse_options(linters=['pep8'])
        errors = check_path('dummy.py', options)

        self.assertTrue(errors)
        self.assertEqual(errors[0]['rel'], 'dummy.py')
Example #45
0
def test_pep257():
    options = parse_options(linters=['pep257'])
    errors = run('dummy.py', options=options)
    assert errors
Example #46
0
def test_pydocstyle():
    options = parse_options(linters=['pydocstyle'])
    assert len(options.linters) == 1
    errors = run('dummy.py', options=options)
    assert errors
Example #47
0
def test_async():
    options = parse_options(config=False)
    errors = check_async(['dummy.py'], options=options, rootdir='.')
    assert errors