Skip to content

Commit 7dd5dde

Browse files
committed
Fixed some tests
1 parent ba6c1d1 commit 7dd5dde

11 files changed

+64
-110
lines changed

pylint/checkers/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def initialize(registry):
114114
"""Register the checkers in this package.
115115
116116
:param registry: The registry to register checkers with.
117-
:type registry: CheckerRegistry
117+
:type registry: PluginRegistry
118118
"""
119119
register_plugins(registry, __path__[0])
120120

pylint/config.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,9 @@ def add_option(self, option_definition):
245245
raise exceptions.ConfigurationError('Option "{0}" already exists.')
246246

247247
self._option_definitions[name] = definition
248+
if 'default' in definition:
249+
dest = definition.get('dest', name)
250+
self.set_option(dest, definition['default'])
248251

249252
def add_options(self, option_definitions):
250253
for option_definition in option_definitions:

pylint/lint.py

Lines changed: 9 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -866,45 +866,6 @@ def report_messages_by_module_stats(sect, stats, _):
866866
# utilities ###################################################################
867867

868868

869-
class ArgumentPreprocessingError(Exception):
870-
"""Raised if an error occurs during argument preprocessing."""
871-
872-
873-
def preprocess_options(args, search_for):
874-
"""look for some options (keys of <search_for>) which have to be processed
875-
before others
876-
877-
values of <search_for> are callback functions to call when the option is
878-
found
879-
"""
880-
i = 0
881-
while i < len(args):
882-
arg = args[i]
883-
if arg.startswith('--'):
884-
try:
885-
option, val = arg[2:].split('=', 1)
886-
except ValueError:
887-
option, val = arg[2:], None
888-
try:
889-
cb, takearg = search_for[option]
890-
except KeyError:
891-
i += 1
892-
else:
893-
del args[i]
894-
if takearg and val is None:
895-
if i >= len(args) or args[i].startswith('-'):
896-
msg = 'Option %s expects a value' % option
897-
raise ArgumentPreprocessingError(msg)
898-
val = args[i]
899-
del args[i]
900-
elif not takearg and val is not None:
901-
msg = "Option %s doesn't expects a value" % option
902-
raise ArgumentPreprocessingError(msg)
903-
cb(option, val)
904-
else:
905-
i += 1
906-
907-
908869
@contextlib.contextmanager
909870
def fix_import_path(args):
910871
"""Prepare sys.path for running the linter checks.
@@ -948,12 +909,12 @@ def guess_lint_path(args):
948909
return value
949910

950911

951-
class CheckerRegistry(object):
912+
class PluginRegistry(object):
952913
"""A class to register checkers to."""
953914

954-
def __init__(self, linter):
955-
super(CheckerRegistry, self).__init__()
956-
self.register_options = lambda options: None
915+
def __init__(self, linter, register_options=(lambda options: None)):
916+
super(PluginRegistry, self).__init__()
917+
self.register_options = register_options
957918
self._checkers = collections.defaultdict(list)
958919
# TODO: Remove. This is needed for the MessagesHandlerMixIn for now.
959920
linter._checkers = self._checkers
@@ -1103,7 +1064,7 @@ class CLIRunner(Runner):
11031064
def __init__(self):
11041065
super(CLIRunner, self).__init__()
11051066
self._linter = PyLinter()
1106-
self._checker_registry = CheckerRegistry(self._linter)
1067+
self._plugin_registry = PluginRegistry(self._linter)
11071068
self._loaded_plugins = set()
11081069

11091070
def run(self, args):
@@ -1168,9 +1129,9 @@ def register_options(options):
11681129
global_config.add_options(options)
11691130
parser.add_option_definitions(options)
11701131
file_parser.add_option_definitions(options)
1171-
self._checker_registry.register_options = register_options
1132+
self._plugin_registry.register_options = register_options
11721133

1173-
checkers.initialize(self._checker_registry)
1134+
checkers.initialize(self._plugin_registry)
11741135

11751136
# Load plugins from CLI
11761137
plugins = parsed.load_plugins or []
@@ -1225,7 +1186,7 @@ def register_options(options):
12251186
self._linter.disable('I')
12261187
self._linter.enable('c-extension-no-member')
12271188

1228-
for checker in self._checker_registry.for_all_checkers():
1189+
for checker in self._plugin_registry.for_all_checkers():
12291190
checker.config = global_config
12301191

12311192
with fix_import_path(global_config.module_or_package):
@@ -1242,7 +1203,7 @@ def load_plugin(self, module_name):
12421203
warnings.warn(msg)
12431204
else:
12441205
module = astroid.modutils.load_module_from_name(module_name)
1245-
module.register(self._checker_registry)
1206+
module.register(self._plugin_registry)
12461207

12471208
def load_plugins(self, module_names):
12481209
"""Load a plugin.

pylint/test/test_functional.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from pylint import interfaces
3030
from pylint import lint
3131
from pylint import reporters
32+
import pylint.config
3233

3334
class test_dialect(csv.excel):
3435
if sys.version_info[0] < 3:
@@ -231,15 +232,17 @@ class LintModuleTest(object):
231232
def __init__(self, test_file):
232233
test_reporter = FunctionalTestReporter()
233234
self._linter = lint.PyLinter()
235+
global_config = pylint.config.Configuration()
236+
self._linter.config = global_config
237+
global_config.add_options(self._linter.options)
238+
registry = lint.PluginRegistry(self._linter)
239+
file_parser = pylint.config.IniFileParser()
240+
file_parser.add_option_definitions(self._linter.options)
234241
self._linter.set_reporter(test_reporter)
235242
self._linter.config.persistent = 0
236-
checkers.initialize(self._linter)
243+
checkers.initialize(registry)
237244
self._linter.disable('I')
238-
try:
239-
self._linter.read_config_file(test_file.option_file)
240-
self._linter.load_config_file()
241-
except NoFileError:
242-
pass
245+
file_parser.parse(test_file.option_file, global_config)
243246
self._test_file = test_file
244247

245248
def setUp(self):

pylint/test/test_self.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727

2828
import six
2929

30-
from pylint.lint import Run
30+
from pylint.lint import CLIRunner
3131
from pylint.reporters import BaseReporter
3232
from pylint.reporters.text import *
3333
from pylint.reporters.json import JSONReporter
@@ -115,7 +115,8 @@ def _run_pylint(self, args, out, reporter=None):
115115
with pytest.raises(SystemExit) as cm:
116116
with warnings.catch_warnings():
117117
warnings.simplefilter("ignore")
118-
Run(args, reporter=reporter)
118+
runner = CLIRunner()
119+
runner.run(args)
119120
return cm.value.code
120121

121122
def _test_output(self, args, expected_output):
@@ -210,10 +211,12 @@ def test_no_out_encoding(self):
210211
'--enable=all'],
211212
out=strio, code=28)
212213

214+
@pytest.mark.xfail(reason='Removed parallel execution for now')
213215
def test_parallel_execution(self):
214216
self._runtest(['-j 2', 'pylint/test/functional/arguments.py',
215217
'pylint/test/functional/bad_continuation.py'], code=1)
216218

219+
@pytest.mark.xfail(reason='Removed parallel execution for now')
217220
def test_parallel_execution_missing_arguments(self):
218221
self._runtest(['-j 2', 'not_here', 'not_here_too'], code=1)
219222

pylint/test/unittest_config.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,38 +16,38 @@
1616
import pytest
1717

1818
def test__regexp_validator_valid():
19-
result = config._regexp_validator(None, None, "test_.*")
19+
result = config.VALIDATORS['regex']("test_.*")
2020
assert isinstance(result, re._pattern_type)
2121
assert result.pattern == "test_.*"
2222

2323
def test__regexp_validator_invalid():
2424
with pytest.raises(sre_constants.error):
25-
config._regexp_validator(None, None, "test_)")
25+
config.VALIDATORS['regex']("test_)")
2626

2727
def test__csv_validator_no_spaces():
2828
values = ["One", "Two", "Three"]
29-
result = config._csv_validator(None, None, ",".join(values))
29+
result = config.VALIDATORS['csv'](",".join(values))
3030
assert isinstance(result, list)
3131
assert len(result) == 3
3232
for i, value in enumerate(values):
3333
assert result[i] == value
3434

3535
def test__csv_validator_spaces():
3636
values = ["One", "Two", "Three"]
37-
result = config._csv_validator(None, None, ", ".join(values))
37+
result = config.VALIDATORS['csv'](", ".join(values))
3838
assert isinstance(result, list)
3939
assert len(result) == 3
4040
for i, value in enumerate(values):
4141
assert result[i] == value
4242

4343
def test__regexp_csv_validator_valid():
4444
pattern_strings = ["test_.*", "foo\\.bar", "^baz$"]
45-
result = config._regexp_csv_validator(None, None, ",".join(pattern_strings))
45+
result = config.VALIDATORS['regexp_csv'](",".join(pattern_strings))
4646
for i, regex in enumerate(result):
4747
assert isinstance(regex, re._pattern_type)
4848
assert regex.pattern == pattern_strings[i]
4949

5050
def test__regexp_csv_validator_invalid():
5151
pattern_strings = ["test_.*", "foo\\.bar", "^baz)$"]
5252
with pytest.raises(sre_constants.error):
53-
config._regexp_csv_validator(None, None, ",".join(pattern_strings))
53+
config.VALIDATORS['regexp_csv'](",".join(pattern_strings))

pylint/test/unittest_lint.py

Lines changed: 7 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
from six.moves import reload_module
3434

3535
from pylint import config, lint
36-
from pylint.lint import PyLinter, Run, preprocess_options, ArgumentPreprocessingError
36+
from pylint.lint import CLIRunner, PluginRegistry, PyLinter
3737
from pylint.utils import MSG_STATE_SCOPE_CONFIG, MSG_STATE_SCOPE_MODULE, MSG_STATE_CONFIDENCE, \
3838
MessagesStore, MessageDefinition, FileState, tokenize_module
3939
from pylint.exceptions import InvalidMessageError, UnknownMessageError
@@ -488,10 +488,11 @@ def test_addmessage_invalid(linter):
488488

489489

490490
def test_init_hooks_called_before_load_plugins():
491+
runner = CLIRunner()
491492
with pytest.raises(RuntimeError):
492-
Run(['--load-plugins', 'unexistant', '--init-hook', 'raise RuntimeError'])
493+
runner.run(['--load-plugins', 'unexistant', '--init-hook', 'raise RuntimeError'])
493494
with pytest.raises(RuntimeError):
494-
Run(['--init-hook', 'raise RuntimeError', '--load-plugins', 'unexistant'])
495+
runner.run(['--init-hook', 'raise RuntimeError', '--load-plugins', 'unexistant'])
495496

496497

497498
def test_analyze_explicit_script(linter):
@@ -612,37 +613,6 @@ def test_pylintrc_parentdir_no_package():
612613
assert config.find_pylintrc() == expected
613614

614615

615-
class TestPreprocessOptions(object):
616-
def _callback(self, name, value):
617-
self.args.append((name, value))
618-
619-
def test_value_equal(self):
620-
self.args = []
621-
preprocess_options(['--foo', '--bar=baz', '--qu=ux'],
622-
{'foo': (self._callback, False),
623-
'qu': (self._callback, True)})
624-
assert [('foo', None), ('qu', 'ux')] == self.args
625-
626-
def test_value_space(self):
627-
self.args = []
628-
preprocess_options(['--qu', 'ux'],
629-
{'qu': (self._callback, True)})
630-
assert [('qu', 'ux')] == self.args
631-
632-
def test_error_missing_expected_value(self):
633-
with pytest.raises(ArgumentPreprocessingError):
634-
preprocess_options(['--foo', '--bar', '--qu=ux'],
635-
{'bar': (None, True)})
636-
with pytest.raises(ArgumentPreprocessingError):
637-
preprocess_options(['--foo', '--bar'],
638-
{'bar': (None, True)})
639-
640-
def test_error_unexpected_value(self):
641-
with pytest.raises(ArgumentPreprocessingError):
642-
preprocess_options(['--foo', '--bar=spam', '--qu=ux'],
643-
{'bar': (None, False)})
644-
645-
646616
@pytest.fixture
647617
def store():
648618
store = MessagesStore()
@@ -744,7 +714,9 @@ def should_analyze_file(self, modname, path, is_argument=False):
744714
package_dir = os.path.join(HERE, 'regrtest_data', 'bad_package')
745715
wrong_file = os.path.join(package_dir, 'wrong.py')
746716
reporter = testutils.TestReporter()
747-
linter = CustomPyLinter()
717+
global_config = config.Configuration()
718+
linter = CustomPyLinter(global_config)
719+
registry = PluginRegistry(linter, register_options=global_config.add_options)
748720
linter.config.persistent = 0
749721
linter.open()
750722
linter.set_reporter(reporter)

pylint/test/unittest_reporters_json.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313

1414
import six
1515

16-
from pylint.lint import PyLinter
16+
import pylint.config
17+
from pylint.lint import PluginRegistry, PyLinter
1718
from pylint import checkers
1819
from pylint.reporters.json import JSONReporter
1920

@@ -22,8 +23,11 @@ def test_simple_json_output():
2223
output = six.StringIO()
2324

2425
reporter = JSONReporter()
25-
linter = PyLinter(reporter=reporter)
26-
checkers.initialize(linter)
26+
global_config = pylint.config.Configuration()
27+
linter = PyLinter(global_config)
28+
registry = PluginRegistry(linter, register_options=global_config.add_options)
29+
checkers.initialize(registry)
30+
linter.set_reporter(reporter)
2731

2832
linter.config.persistent = 0
2933
linter.reporter.set_output(output)

pylint/test/unittest_reporting.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313

1414
import six
1515

16-
from pylint.lint import PyLinter
16+
import pylint.config
17+
from pylint.lint import PluginRegistry, PyLinter
1718
from pylint import checkers
1819
from pylint.reporters.text import TextReporter, ParseableTextReporter
1920
import pytest
@@ -55,12 +56,15 @@ def test_parseable_output_deprecated():
5556
def test_parseable_output_regression():
5657
output = six.StringIO()
5758
with warnings.catch_warnings(record=True):
58-
linter = PyLinter(reporter=ParseableTextReporter())
59+
global_config = pylint.config.Configuration()
60+
linter = PyLinter(global_config)
61+
registry = PluginRegistry(linter, register_options=global_config.add_options)
62+
linter.set_reporter(ParseableTextReporter())
5963

60-
checkers.initialize(linter)
64+
checkers.initialize(registry)
6165
linter.config.persistent = 0
6266
linter.reporter.set_output(output)
63-
linter.set_option('output-format', 'parseable')
67+
linter.config.output_format = 'parseable'
6468
linter.open()
6569
linter.set_current_module('0123')
6670
linter.add_message('line-too-long', line=1, args=(1, 2))

pylint/testutils.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,11 @@
3535

3636
import astroid
3737
from pylint import checkers
38+
import pylint.config
3839
from pylint.utils import PyLintASTWalker
3940
from pylint.reporters import BaseReporter
4041
from pylint.interfaces import IReporter
41-
from pylint.lint import PyLinter
42+
from pylint.lint import PluginRegistry, PyLinter
4243

4344
# Utils
4445

@@ -169,6 +170,7 @@ class UnittestLinter(object):
169170
def __init__(self):
170171
self._messages = []
171172
self.stats = {}
173+
self.config = pylint.config.Configuration()
172174

173175
def release_messages(self):
174176
try:
@@ -216,7 +218,9 @@ class CheckerTestCase(object):
216218

217219
def setup_method(self):
218220
self.linter = UnittestLinter()
219-
self.checker = self.CHECKER_CLASS(self.linter) # pylint: disable=not-callable
221+
registry = pylint.config.PluginRegistry(self.linter)
222+
registry.register_options = self.linter.config.add_options
223+
self.checker = self.CHECKER_CLASS(registry) # pylint: disable=not-callable
220224
for key, value in six.iteritems(self.CONFIG):
221225
setattr(self.checker.config, key, value)
222226
self.checker.open()
@@ -251,10 +255,10 @@ def walk(self, node):
251255

252256
# Init
253257
test_reporter = TestReporter()
254-
linter = PyLinter()
258+
linter = PyLinter(pylint.config.Configuration())
255259
linter.set_reporter(test_reporter)
256260
linter.config.persistent = 0
257-
checkers.initialize(linter)
261+
checkers.initialize(PluginRegistry(linter))
258262

259263

260264
def _tokenize_str(code):

0 commit comments

Comments
 (0)