Skip to content

Commit

Permalink
add tests around pylint exit kwargs
Browse files Browse the repository at this point in the history
Signed-off-by: Matthew Peveler <[email protected]>
  • Loading branch information
MasterOdin committed Jun 22, 2024
1 parent 3507550 commit 39d43a7
Show file tree
Hide file tree
Showing 5 changed files with 131 additions and 78 deletions.
57 changes: 10 additions & 47 deletions pylint_runner/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
from argparse import ArgumentParser
import configparser
import os
import re
import sys

import colorama
import pylint
import pylint.lint

from pylint_runner import __version__
from . import __version__
from .utils import get_files_from_dir, get_pylint_kwargs

PYTHON_VERSION = ".".join([str(x) for x in sys.version_info[0:3]])

Expand All @@ -40,6 +40,10 @@ def __init__(self, args=None):
self._parse_args(args)
self._parse_ignores()

def is_using_default_rcfile(self):
""" Check if the rcfile is the default rcfile. """
return self.rcfile == os.getcwd() + "/" + self.DEFAULT_RCFILE

def _parse_args(self, args):
"""Parses any supplied command-line args and provides help text. """

Expand Down Expand Up @@ -95,7 +99,7 @@ def _parse_ignores(self):
)

if not os.path.isfile(self.rcfile):
if not self._is_using_default_rcfile():
if not self.is_using_default_rcfile():
print(error_message)
sys.exit(1)
else:
Expand All @@ -111,45 +115,11 @@ def _parse_ignores(self):
if config.has_section("MASTER") and config.get("MASTER", "ignore"):
self.ignore_folders += config.get("MASTER", "ignore").split(",")

def _is_using_default_rcfile(self):
return self.rcfile == os.getcwd() + "/" + self.DEFAULT_RCFILE

def _print_line(self, line):
""" Print output only with verbose flag. """
if self.verbose:
print(line)

def get_files_from_dir(self, current_dir):
"""
Recursively walk through a directory and get all python files and then
walk through any potential directories that are found off current
directory, so long as not within self.IGNORE_FOLDERS
:return: all python files that were found off current_dir
"""
if current_dir[-1] != "/" and current_dir != ".":
current_dir += "/"

files = []

for dir_file in os.listdir(current_dir):
if current_dir != ".":
file_path = current_dir + dir_file
else:
file_path = dir_file

if os.path.isfile(file_path):
file_split = os.path.splitext(dir_file)
if len(file_split) == 2 and file_split[0] != "" \
and file_split[1] == ".py":
files.append(file_path)
elif (os.path.isdir(dir_file) or os.path.isdir(file_path)) \
and dir_file not in self.ignore_folders:
path = dir_file + os.path.sep
if current_dir not in ["", "."]:
path = os.path.join(current_dir.rstrip(os.path.sep), path)
files += self.get_files_from_dir(path)
return files

def run(self, output=None, error=None):
""" Runs pylint on all python files in the current directory """

Expand All @@ -159,7 +129,7 @@ def run(self, output=None, error=None):
sys.stdout = pylint_output
sys.stderr = pylint_error

pylint_files = self.get_files_from_dir(os.curdir)
pylint_files = get_files_from_dir(os.curdir, self.ignore_folders)
print(
"Using pylint "
+ colorama.Fore.RED
Expand All @@ -183,19 +153,12 @@ def run(self, output=None, error=None):
self._print_line("- " + pylint_file)
self._print_line("----")

if not self._is_using_default_rcfile():
if not self.is_using_default_rcfile():
# insert this at the front so it's not after any potential
# positional arguments
self.args.insert(0, f"--rcfile={self.rcfile}")

pylint_version = pylint.__version__.split('.')[:3]
pylint_version[2] = re.sub(r'[a-z-].*', '', pylint_version[2])
pylint_version = [int(x) for x in pylint_version]

if pylint_version < [2, 5, 1]:
exit_kwarg = {"do_exit": False}
else:
exit_kwarg = {"exit": False}
exit_kwarg = get_pylint_kwargs(pylint.__version__)

run = pylint.lint.Run(self.args + pylint_files, **exit_kwarg)
sys.stdout = savedout
Expand Down
51 changes: 51 additions & 0 deletions pylint_runner/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
Utility functions for the pylint_runner module.
"""

import os
import re


def get_files_from_dir(current_dir, ignore_folders=None):
"""
Recursively walk through a directory and get all python files and then
walk through any potential directories that are found off current
directory, so long as not within self.IGNORE_FOLDERS
:return: all python files that were found off current_dir
"""
if ignore_folders is None:
ignore_folders = []

if current_dir[-1] != "/" and current_dir != ".":
current_dir += "/"

files = []

for dir_file in os.listdir(current_dir):
if current_dir != ".":
file_path = current_dir + dir_file
else:
file_path = dir_file

if os.path.isfile(file_path):
file_split = os.path.splitext(dir_file)
if len(file_split) == 2 and file_split[0] != "" \
and file_split[1] == ".py":
files.append(file_path)
elif (os.path.isdir(dir_file) or os.path.isdir(file_path)) \
and dir_file not in ignore_folders:
path = dir_file + os.path.sep
if current_dir not in ["", "."]:
path = os.path.join(current_dir.rstrip(os.path.sep), path)
files += get_files_from_dir(path)
return files


def get_pylint_kwargs(pylint_version):
""" Get the correct keyword arguments for the pylint runner. """
pylint_version = pylint_version.split('.')[:3]
pylint_version[2] = re.sub(r'[a-z-].*', '', pylint_version[2])
pylint_version = [int(x) for x in pylint_version]
if pylint_version < [2, 5, 1]:
return {"do_exit": False}
return {"exit": False}
4 changes: 4 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
"""
Tests for pylint_runner
"""

def _assert_list_equals(list1, list2):
assert len(list1) == len(list2)
assert sorted(list1) == sorted(list2)
33 changes: 2 additions & 31 deletions tests/test_runner.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,10 @@
# pylint: disable=missing-docstring
import os
import pytest
import pylint_runner.main as runner


def test_get_files():
# make sure we use root of pylint_runner module
os.chdir(os.path.dirname(os.path.realpath(__file__)) + '/../')
actual = runner.Runner().get_files_from_dir(os.curdir)
expected = [
'pylint_runner/__init__.py',
'pylint_runner/main.py',
'setup.py',
'tests/__init__.py',
'tests/test_runner.py',
'tests/tests/dummy.py'
]
_assert_list_equals(expected, actual)


def test_get_files_current_dir():
path = os.path.dirname(os.path.realpath(__file__))
actual = runner.Runner().get_files_from_dir(path)
expected = [
path + '/__init__.py',
path + '/test_runner.py',
path + '/tests/dummy.py'
]
_assert_list_equals(expected, actual)
import pylint_runner.main as runner

from . import _assert_list_equals

def test_main():
with pytest.raises(SystemExit) as excinfo:
Expand Down Expand Up @@ -61,11 +37,6 @@ def test_rcparser_bad_file():
assert excinfo.value.code == 1


def _assert_list_equals(list1, list2):
assert len(list1) == len(list2)
assert sorted(list1) == sorted(list2)


def test_passthrough_args():
the_runner = runner.Runner(args=['-d', 'C0103', '-d', 'E0602'])
expected = [
Expand Down
64 changes: 64 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# pylint: disable=missing-docstring
import os
import pytest

from pylint_runner.utils import get_files_from_dir, get_pylint_kwargs

from . import _assert_list_equals

testdata = [
("1.0.0", {"do_exit": False}),
("2.0.0", {"do_exit": False}),
("2.5.0", {"do_exit": False}),
("2.5.1", {"exit": False}),
("2.5.1-dev", {"exit": False}),
("2.16.0.dev0", {"exit": False}),
("2.6.0", {"exit": False}),
("3.0.0b0", {"exit": False}),
("3.0.0", {"exit": False}),
]


@pytest.mark.parametrize("value,expected", testdata)
def test_get_pylint_kwargs(value, expected):
assert get_pylint_kwargs(value) == expected


def test_get_files():
# make sure we use root of pylint_runner module
os.chdir(os.path.dirname(os.path.realpath(__file__)) + '/../')
actual = get_files_from_dir(os.curdir)
expected = [
'pylint_runner/__init__.py',
'pylint_runner/main.py',
'pylint_runner/utils.py',
'setup.py',
'tests/__init__.py',
'tests/test_runner.py',
'tests/test_utils.py',
'tests/tests/dummy.py'
]
_assert_list_equals(expected, actual)


def test_get_files_current_dir():
path = os.path.dirname(os.path.realpath(__file__))
actual = get_files_from_dir(path)
expected = [
path + '/__init__.py',
path + '/test_runner.py',
path + '/test_utils.py',
path + '/tests/dummy.py'
]
_assert_list_equals(expected, actual)


def test_get_files_ignore():
path = os.path.dirname(os.path.realpath(__file__))
actual = get_files_from_dir(path, ignore_folders=['tests'])
expected = [
path + '/__init__.py',
path + '/test_runner.py',
path + '/test_utils.py'
]
_assert_list_equals(expected, actual)

0 comments on commit 39d43a7

Please sign in to comment.