def setUp(self): self.linter = PyLinter(reporter=TextReporter()) self.linter.disable('I') self.linter.config.persistent = 0 # register checkers checkers.initialize(self.linter) os.environ.pop('PYLINTRC', None)
def process_file(filename): """ Analyze the file with pylint and write the result to a database """ linter = PyLinter() checkers.initialize(linter) linter.read_config_file() linter.quiet = 1 filemods = linter.expand_files((filename, )) if filemods: old_stats = config.load_results(filemods[0].get('basename')) old_score = old_stats.get('global_note', 0.0) linter.check(filename) score = eval(linter.config.evaluation, {}, linter.stats) # Calculate the credit for both scores if score < 0: credit = 2.0 * score elif score < old_score: credit = -1.5 * (old_score - score) elif score < MINIMUM_SCORE: credit = -1.5 * (MINIMUM_SCORE - score) else: credit = score - old_score return score, old_score, credit
def test_html_reporter_msg_template(self): expected = ''' <html> <body> <div> <div> <h2>Messages</h2> <table> <tr class="header"> <th>category</th> <th>msg_id</th> </tr> <tr class="even"> <td>warning</td> <td>W0332</td> </tr> </table> </div> </div> </body> </html>'''.strip().splitlines() output = six.StringIO() linter = PyLinter(reporter=HTMLReporter()) checkers.initialize(linter) linter.config.persistent = 0 linter.reporter.set_output(output) linter.set_option('msg-template', '{category}{msg_id}') linter.open() linter.set_current_module('0123') linter.add_message('lowercase-l-suffix', line=1) linter.reporter.display_results(Section()) self.assertEqual(output.getvalue().splitlines(), expected)
def _init_pylint(): from pylint import lint, checkers import re class VimReporter(object): def __init__(self): self.errors = [] def add_message(self, msg_id, location, msg): _, _, line, col = location[1:] self.errors.append(dict( lnum=line, col=col, text="%s %s" % (msg_id, msg), type=msg_id[0] )) PYLINT['lint'] = lint.PyLinter() PYLINT['re'] = re.compile('^(?:.:)?[^:]+:(\d+): \[([EWRCI]+)[^\]]*\] (.*)$') checkers.initialize(PYLINT['lint']) PYLINT['lint'].load_file_configuration(vim.eval("g:pymode_lint_config")) PYLINT['lint'].set_option("output-format", "parseable") PYLINT['lint'].set_option("include-ids", 1) PYLINT['lint'].set_option("reports", 0) PYLINT['lint'].reporter = VimReporter()
def linter(): linter = PyLinter() linter.set_reporter(MinimalTestReporter()) checkers.initialize(linter) linter.register_checker(OverlappingExceptionsChecker(linter)) linter.disable('I') return linter
def setUpClass(cls): cls._linter = PyLinter() cls._linter.set_reporter(TestReporter()) checkers.initialize(cls._linter) register(cls._linter) cls._linter.disable('all') cls._linter.enable('too-complex')
def __init__(self, reporter=None, quiet=0, pylintrc=None, crunchy_report=None): if crunchy_report == "full": self.full_report = True else: self.full_report = False self.LinterClass = lint.PyLinter self._rcfile = pylintrc self.linter = self.LinterClass( reporter=reporter, pylintrc=self._rcfile, ) self.linter.quiet = quiet self._report = None self._code = None # register standard checkers checkers.initialize(self.linter) # read configuration self.linter.read_config_file() self.linter.load_config_file() # Disable some errors. if self.full_report: self.linter.load_command_line_configuration([ '--module-rgx=.*', # don't check the module name '--persistent=n', # don't save the old score (no sens for temp) ]) else: self.linter.load_command_line_configuration([ '--module-rgx=.*', # don't check the module name '--reports=n', # remove tables '--persistent=n', # don't save the old score (no sens for temp) ]) self.linter.load_configuration() self.linter.disable_message('C0121')# required attribute "__revision__" if reporter: self.linter.set_reporter(reporter)
def test_simple_json_output(): output = StringIO() reporter = JSONReporter() linter = PyLinter(reporter=reporter) checkers.initialize(linter) linter.config.persistent = 0 linter.reporter.set_output(output) linter.open() linter.set_current_module("0123") linter.add_message("line-too-long", line=1, args=(1, 2)) # we call this method because we didn't actually run the checkers reporter.display_messages(None) expected_result = [ [ ("column", 0), ("line", 1), ("message", "Line too long (1/2)"), ("message-id", "C0301"), ("module", "0123"), ("obj", ""), ("path", "0123"), ("symbol", "line-too-long"), ("type", "convention"), ] ] report_result = json.loads(output.getvalue()) report_result = [sorted(report_result[0].items(), key=lambda item: item[0])] assert report_result == expected_result
def lint(cls, namespace): 'Performs pylint checks' from pylint import lint linter = lint.PyLinter() from pylint import checkers checkers.initialize(linter) linter.check([str(path) for path in Path.cwd().iterfiles()])
def linter(): linter = PyLinter() linter.set_reporter(MinimalTestReporter()) checkers.initialize(linter) linter.register_checker(BadBuiltinChecker(linter)) linter.disable('I') return linter
def __init__(self, *args, **kwargs): self.sema = Semaphore(0) self._output = [] self.running = True self._plugins = [] pylintrc = kwargs.pop('pylintrc', None) super(PidaLinter, self).__init__(*args, **kwargs) #self.load_plugin_modules(self._plugins) from pylint import checkers checkers.initialize(self) #self._rcfile = gconfig = os.path.join( environment.get_plugin_global_settings_path('python_lint'), 'pylintrc') if os.path.exists(gconfig): self.read_config_file(gconfig) if pylintrc and os.path.exists(pylintrc): self.read_config_file(pylintrc) config_parser = self._config_parser if config_parser.has_option('MASTER', 'load-plugins'): plugins = get_csv(config_parser.get('MASTER', 'load-plugins')) self.load_plugin_modules(plugins) try: self.load_config_file() except Exception, e: log.exception(e) log.error(_("pylint couldn't load your config file: %s") %e)
def setUp(self): self.linter = PyLinter() self.linter.disable('I') self.linter.config.persistent = 0 # register checkers checkers.initialize(self.linter) self.linter.set_reporter(TestReporter())
def run_linter(self): from pylint.lint import PyLinter from pylint import checkers from os.path import join linter = PyLinter(pylintrc=self.lint_config) # same, but not all pylint versions have load_default_plugins if hasattr(linter, 'load_default_plugins'): linter.load_default_plugins() else: checkers.initialize(linter) linter.read_config_file() linter.load_config_file() if self.packages: self.announce("checking packages", 2) report_fn = "packages_report." + linter.reporter.extension report_fn = join(self.build_base, report_fn) with open(report_fn, "wt") as out: linter.reporter.set_output(out) linter.check(self.packages) self.announce_overview(linter, report_fn) if self.build_scripts: self.announce("checking scripts", 2) report_fn = "scripts_report." + linter.reporter.extension report_fn = join(self.build_base, report_fn) with open(report_fn, "wt") as out: linter.reporter.set_output(out) linter.check(self.build_scripts) self.announce_overview(linter, report_fn)
def linter(): test_reporter = testutils.TestReporter() linter = lint.PyLinter() linter.set_reporter(test_reporter) linter.disable('I') linter.config.persistent = 0 checkers.initialize(linter) return linter
def linter(): linter = PyLinter() linter.set_reporter(MinimalTestReporter()) checkers.initialize(linter) register(linter) linter.disable('all') linter.enable('too-complex') return linter
def linter(): linter = PyLinter(reporter=TextReporter()) linter.disable('I') linter.config.persistent = 0 # register checkers checkers.initialize(linter) os.environ.pop('PYLINTRC', None) return linter
def linter(): linter = PyLinter() linter.disable('I') linter.config.persistent = 0 # register checkers checkers.initialize(linter) linter.set_reporter(testutils.TestReporter()) return linter
def __init__(self, test_file): test_reporter = FunctionalTestReporter() self._linter = lint.PyLinter() self._linter.set_reporter(test_reporter) self._linter.config.persistent = 0 checkers.initialize(self._linter) self._linter.disable('I') try: self._linter.read_config_file(test_file.option_file) self._linter.load_config_file() except NoFileError: pass self._test_file = test_file
def __init__(self, test_file): super(LintModuleTest, self).__init__('_runTest') test_reporter = TestReporter() self._linter = lint.PyLinter() self._linter.set_reporter(test_reporter) self._linter.config.persistent = 0 checkers.initialize(self._linter) self._linter.disable('I') try: self._linter.load_file_configuration(test_file.option_file) except NoFileError: pass self._test_file = test_file
def check(self): """ Perform a check on current file. """ self.view.progressbar.set_fraction(0.0) self.set_score('?') self.throbber_icon.start() self.idx = 0 self.linter = lint.PyLinter() self.linter.set_reporter(self) checkers.initialize(self.linter) deferred = threads.deferToThread(self.linter.check, self.lastfilename) deferred.addCallback(self._check_done) deferred.addErrback(self._check_error)
def test_parseable_output_regression(self): output = six.StringIO() linter = PyLinter(reporter=ParseableTextReporter()) checkers.initialize(linter) linter.config.persistent = 0 linter.reporter.set_output(output) linter.set_option('output-format', 'parseable') linter.open() linter.set_current_module('0123') linter.add_message('line-too-long', line=1, args=(1, 2)) self.assertMultiLineEqual(output.getvalue(), '************* Module 0123\n' '0123:1: [C0301(line-too-long), ] ' 'Line too long (1/2)\n')
def load_file(self, filename): """ Load and check a file. """ self.linter = lint.PyLinter() self.linter.set_reporter(self) checkers.initialize(self.linter) source_file = open(filename, 'r') text = source_file.read() source_file.close() self.buffer.set_property('text', text) self.linecount = self.buffer.get_line_count() self.text = text self.lastfilename = filename self.check()
def linter(checker, register, enable, disable, reporter): _linter = PyLinter() _linter.set_reporter(reporter()) checkers.initialize(_linter) if register: register(_linter) if checker: _linter.register_checker(checker(_linter)) if disable: for msg in disable: _linter.disable(msg) if enable: for msg in enable: _linter.enable(msg) os.environ.pop("PYLINTRC", None) return _linter
def test_parseable_output_regression(): output = StringIO() with warnings.catch_warnings(record=True): linter = PyLinter(reporter=ParseableTextReporter()) checkers.initialize(linter) linter.config.persistent = 0 linter.reporter.set_output(output) linter.set_option('output-format', 'parseable') linter.open() linter.set_current_module('0123') linter.add_message('line-too-long', line=1, args=(1, 2)) assert output.getvalue() == \ '************* Module 0123\n' \ '0123:1: [C0301(line-too-long), ] ' \ 'Line too long (1/2)\n'
def test_html_reporter_type(self): # Integration test for issue #263 # https://bitbucket.org/logilab/pylint/issue/263/html-report-type-problems expected = '''<html> <body> <div> <div> <h2>Messages</h2> <table> <tr class="header"> <th>type</th> <th>module</th> <th>object</th> <th>line</th> <th>col_offset</th> <th>message</th> </tr> <tr class="even"> <td>convention</td> <td>0123</td> <td> </td> <td>1</td> <td>0</td> <td>Exactly one space required before comparison a< 5: print "zero"</td> </tr> </table> </div> </div> </body> </html> ''' output = six.StringIO() with testutils.catch_warnings(): linter = PyLinter(reporter=HTMLReporter()) checkers.initialize(linter) linter.config.persistent = 0 linter.reporter.set_output(output) linter.open() linter.set_current_module('0123') linter.add_message('bad-whitespace', line=1, args=('Exactly one', 'required', 'before', 'comparison', 'a< 5: print "zero"')) linter.reporter.display_reports(Section()) self.assertMultiLineEqual(output.getvalue(), expected)
def run(argv, show_reports=False): linter = lint.PyLinter() checkers.initialize(linter) AstCheckers.register(linter) for warning in DISABLED_WARNINGS: linter.disable(warning) linter.set_option('ignore', ['local_settings.py', 'migrations']) linter.set_option('include-ids', True) if not show_reports: linter.set_option('reports', False) if not argv: # django lint uses deprecated style of pylint warning and we are not # interested in seeing warnings about this with warnings.catch_warnings(): targets = [x for x in os.listdir('.') if (os.path.isdir(x) and os.path.exists('%s/__init__.py' % (x,)))] warnings.simplefilter('ignore') linter.check(targets) else: files = linter.load_command_line_configuration(argv) linter.check(files)
def run_linter(self): linter = PyLinter(pylintrc=self.lint_config) # load_default_plugins will call checkers.initialize if # implemented, but some older versions of pylint don't have # this method so we fall back to calling is manually. if hasattr(linter, 'load_default_plugins'): linter.load_default_plugins() else: checkers.initialize(linter) linter.read_config_file() linter.load_config_file() # don't emit messages about suppressed or useless suppressed # configs, it's just annoying and doesn't help. #linter.disable('suppressed-message') #linter.disable('useless-suppression') if self.packages: self.announce("pylint is checking packages", 2) report_fn = "packages_report." + linter.reporter.extension report_fn = join(self.build_base, report_fn) with open(report_fn, "wt") as out: linter.reporter.set_output(out) linter.check(self.packages) self.announce_overview(linter, report_fn) if self.build_scripts: self.announce("pylint is checking scripts", 2) report_fn = "scripts_report." + linter.reporter.extension report_fn = join(self.build_base, report_fn) with open(report_fn, "wt") as out: linter.reporter.set_output(out) linter.check(self.build_scripts) self.announce_overview(linter, report_fn)
def built_in_check(self, view, code, filename): linter = lint.PyLinter() checkers.initialize(linter) # Disable some errors. linter.load_command_line_configuration([ '--module-rgx=.*', # don't check the module name '--reports=n', # remove tables '--persistent=n', # don't save the old score (no sense for temp) ]) temp = tempfile.NamedTemporaryFile(suffix='.py') temp.write(code) temp.flush() output_buffer = StringIO() linter.reporter.set_output(output_buffer) linter.check(temp.name) report = output_buffer.getvalue().replace(temp.name, 'line ') output_buffer.close() temp.close() return report
def setUp(self): self.linter = PyLinter() self.linter.disable('I') self.linter.config.persistent = 0 # register checkers checkers.initialize(self.linter)
def setUpClass(cls): cls._linter = PyLinter() cls._linter.set_reporter(TestReporter()) checkers.initialize(cls._linter) cls._linter.register_checker(DocStringAddicChecker(cls._linter))
def linter() -> PyLinter: pylinter = PyLinter(reporter=testutils.GenericTestReporter()) initialize(pylinter) return pylinter
def setUpClass(cls): cls._linter = PyLinter() cls._linter.set_reporter(CompareToZeroTestReporter()) checkers.initialize(cls._linter) cls._linter.register_checker(CompareToZeroChecker(cls._linter)) cls._linter.disable('I')
def setUpClass(cls): cls._linter = PyLinter() cls._linter.set_reporter(BroadTryClauseTestReporter()) checkers.initialize(cls._linter) cls._linter.register_checker(BroadTryClauseChecker(cls._linter)) cls._linter.disable("I")
def load_default_plugins(self): from pylint import checkers checkers.initialize(self)
for m in messages), '\n'.join(repr(m) for m in got))) self.assertEqual(list(messages), got, msg) def walk(self, node): """recursive walk on the given node""" walker = PyLintASTWalker(linter) walker.add_checker(self.checker) walker.walk(node) # Init test_reporter = TestReporter() linter = PyLinter() linter.set_reporter(test_reporter) linter.config.persistent = 0 checkers.initialize(linter) linter.global_set_option('required-attributes', ('__revision__', )) if linesep != '\n': LINE_RGX = re.compile(linesep) def ulines(string): return LINE_RGX.sub('\n', string) else: def ulines(string): return string INFO_TEST_RGX = re.compile(r'^func_i\d\d\d\d$')
class Run: """helper class to use as main for pylint : run(*sys.argv[1:]) """ LinterClass = PyLinter option_groups = ( ('Commands', 'Options which are actually commands. Options in this \ group are mutually exclusive.'), ) def __init__(self, args, reporter=None, exit=True): self._rcfile = None self._plugins = [] try: preprocess_options(args, { # option: (callback, takearg) 'rcfile': (self.cb_set_rcfile, True), 'load-plugins': (self.cb_add_plugins, True), }) except ArgumentPreprocessingError, e: print >> sys.stderr, 'Argument %s expects a value.' % (e.args[0],) sys.exit(32) self.linter = linter = self.LinterClass(( ('rcfile', {'action' : 'callback', 'callback' : lambda *args: 1, 'type': 'string', 'metavar': '<file>', 'help' : 'Specify a configuration file.'}), ('init-hook', {'action' : 'callback', 'type' : 'string', 'metavar': '<code>', 'callback' : cb_init_hook, 'level': 1, 'help' : 'Python code to execute, usually for sys.path \ manipulation such as pygtk.require().'}), ('help-msg', {'action' : 'callback', 'type' : 'string', 'metavar': '<msg-id>', 'callback' : self.cb_help_message, 'group': 'Commands', 'help' : '''Display a help message for the given message id and \ exit. The value may be a comma separated list of message ids.'''}), ('list-msgs', {'action' : 'callback', 'metavar': '<msg-id>', 'callback' : self.cb_list_messages, 'group': 'Commands', 'level': 1, 'help' : "Generate pylint's messages."}), ('full-documentation', {'action' : 'callback', 'metavar': '<msg-id>', 'callback' : self.cb_full_documentation, 'group': 'Commands', 'level': 1, 'help' : "Generate pylint's full documentation."}), ('generate-rcfile', {'action' : 'callback', 'callback' : self.cb_generate_config, 'group': 'Commands', 'help' : '''Generate a sample configuration file according to \ the current configuration. You can put other options before this one to get \ them in the generated configuration.'''}), ('generate-man', {'action' : 'callback', 'callback' : self.cb_generate_manpage, 'group': 'Commands', 'help' : "Generate pylint's man page.",'hide': True}), ('errors-only', {'action' : 'callback', 'callback' : self.cb_error_mode, 'short': 'E', 'help' : '''In error mode, checkers without error messages are \ disabled and for others, only the ERROR messages are displayed, and no reports \ are done by default'''}), ('profile', {'type' : 'yn', 'metavar' : '<y_or_n>', 'default': False, 'hide': True, 'help' : 'Profiled execution.'}), ), option_groups=self.option_groups, reporter=reporter, pylintrc=self._rcfile) # register standard checkers from pylint import checkers checkers.initialize(linter) # load command line plugins linter.load_plugin_modules(self._plugins) # add some help section linter.add_help_section('Environment variables', config.ENV_HELP, level=1) linter.add_help_section('Output', ''' Using the default text output, the message format is : MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE There are 5 kind of message types : * (C) convention, for programming standard violation * (R) refactor, for bad code smell * (W) warning, for python specific problems * (E) error, for probable bugs in the code * (F) fatal, if an error occurred which prevented pylint from doing further processing. ''', level=1) linter.add_help_section('Output status code', ''' Pylint should leave with following status code: * 0 if everything went fine * 1 if a fatal message was issued * 2 if an error message was issued * 4 if a warning message was issued * 8 if a refactor message was issued * 16 if a convention message was issued * 32 on usage error status 1 to 16 will be bit-ORed so you can know which different categories has been issued by analysing pylint output status code ''', level=1) # read configuration linter.disable('W0704') linter.read_config_file() # is there some additional plugins in the file configuration, in config_parser = linter.cfgfile_parser if config_parser.has_option('MASTER', 'load-plugins'): plugins = splitstrip(config_parser.get('MASTER', 'load-plugins')) linter.load_plugin_modules(plugins) # now we can load file config and command line, plugins (which can # provide options) have been registered linter.load_config_file() if reporter: # if a custom reporter is provided as argument, it may be overridden # by file parameters, so re-set it here, but before command line # parsing so it's still overrideable by command line option linter.set_reporter(reporter) try: args = linter.load_command_line_configuration(args) except SystemExit, exc: if exc.code == 2: # bad options exc.code = 32 raise
def __init__(self, args, reporter=None): self._rcfile = None self._plugins = [] preprocess_options( args, { # option: (callback, takearg) 'rcfile': (self.cb_set_rcfile, True), 'load-plugins': (self.cb_add_plugins, True), }) self.linter = linter = self.LinterClass(( ('rcfile', { 'action': 'callback', 'callback': lambda *args: 1, 'type': 'string', 'metavar': '<file>', 'help': 'Specify a configuration file.' }), ('init-hook', { 'action': 'callback', 'type': 'string', 'metavar': '<code>', 'callback': cb_init_hook, 'help': 'Python code to execute, usually for sys.path \ manipulation such as pygtk.require().' }), ('help-msg', { 'action': 'callback', 'type': 'string', 'metavar': '<msg-id>', 'callback': self.cb_help_message, 'group': 'Commands', 'help': '''Display a help message for the given message id and \ exit. The value may be a comma separated list of message ids.''' }), ('list-msgs', { 'action': 'callback', 'metavar': '<msg-id>', 'callback': self.cb_list_messages, 'group': 'Commands', 'help': "Generate pylint's full documentation." }), ('generate-rcfile', { 'action': 'callback', 'callback': self.cb_generate_config, 'group': 'Commands', 'help': '''Generate a sample configuration file according to \ the current configuration. You can put other options before this one to get \ them in the generated configuration.''' }), ('generate-man', { 'action': 'callback', 'callback': self.cb_generate_manpage, 'group': 'Commands', 'help': "Generate pylint's man page.", 'hide': 'True' }), ('errors-only', { 'action': 'callback', 'callback': self.cb_error_mode, 'short': 'e', 'help': '''In error mode, checkers without error messages are \ disabled and for others, only the ERROR messages are displayed, and no reports \ are done by default''' }), ('profile', { 'type': 'yn', 'metavar': '<y_or_n>', 'default': False, 'help': 'Profiled execution.' }), ), option_groups=self. option_groups, reporter=reporter, pylintrc=self._rcfile) # register standard checkers checkers.initialize(linter) # load command line plugins linter.load_plugin_modules(self._plugins) # read configuration linter.disable_message('W0704') linter.read_config_file() # is there some additional plugins in the file configuration, in config_parser = linter._config_parser if config_parser.has_option('MASTER', 'load-plugins'): plugins = splitstrip( config_parser.get('MASTER', 'load-plugins')) linter.load_plugin_modules(plugins) # now we can load file config and command line, plugins (which can # provide options) have been registered linter.load_config_file() if reporter: # if a custom reporter is provided as argument, it may be overriden # by file parameters, so re-set it here, but before command line # parsing so it's still overrideable by command line option linter.set_reporter(reporter) args = linter.load_command_line_configuration(args) # insert current working directory to the python path to have a correct # behaviour sys.path.insert(0, os.getcwd()) if self.linter.config.profile: print >> sys.stderr, '** profiled run' from hotshot import Profile, stats prof = Profile('stones.prof') prof.runcall(linter.check, args) prof.close() data = stats.load('stones.prof') data.strip_dirs() data.sort_stats('time', 'calls') data.print_stats(30) sys.path.pop(0)
import os from os.path import abspath, dirname, join from logilab.common.testlib import TestCase, unittest_main from utils import TestReporter from pylint.lint import PyLinter from pylint import checkers test_reporter = TestReporter() linter = PyLinter() linter.set_reporter(test_reporter) linter.disable('I') linter.config.persistent = 0 checkers.initialize(linter) REGR_DATA = join(dirname(abspath(__file__)), 'regrtest_data') sys.path.insert(1, REGR_DATA) class NonRegrTC(TestCase): def setUp(self): """call reporter.finalize() to cleanup pending messages if a test finished badly """ linter.reporter.finalize() def test_package___path___manipulation(self): linter.check('package.__init__') got = linter.reporter.finalize().strip() self.assertEqual(got, '')
def linter(): l = PyLinter(reporter=testutils.TestReporter()) initialize(l) return l