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 test_json_report_when_file_is_missing(self): out = six.StringIO() module = join(HERE, 'regrtest_data', 'totally_missing.py') self._runtest([module], code=1, reporter=JSONReporter(out)) output = json.loads(out.getvalue()) assert isinstance(output, list) assert len(output) == 1 assert isinstance(output[0], dict) expected = { "obj": "", "column": 0, "line": 1, "type": "fatal", "symbol": "fatal", "module": module } message = output[0] for key, value in expected.items(): assert key in message assert message[key] == value assert message['message'].startswith("No module named")
def test_json_report_when_file_has_syntax_error(self): out = six.StringIO() module = join(HERE, 'regrtest_data', 'syntax_error.py') self._runtest([module], code=2, reporter=JSONReporter(out)) output = json.loads(out.getvalue()) assert isinstance(output, list) assert len(output) == 1 assert isinstance(output[0], dict) expected = { "obj": "", "column": 0, "line": 1, "type": "error", "symbol": "syntax-error", "module": "syntax_error" } message = output[0] for key, value in expected.items(): assert key in message assert message[key] == value assert 'invalid syntax' in message['message'].lower()
def test_json_report_when_file_has_syntax_error(self): out = six.StringIO() module = join(HERE, 'regrtest_data', 'syntax_error.py') self._runtest([module], code=2, reporter=JSONReporter(out)) output = json.loads(out.getvalue()) self.assertIsInstance(output, list) self.assertEqual(len(output), 1) self.assertIsInstance(output[0], dict) expected = { "obj": "", "column": 0, "line": 1, "type": "error", "symbol": "syntax-error", "module": "syntax_error" } message = output[0] for key, value in expected.items(): self.assertIn(key, message) self.assertEqual(message[key], value) self.assertIn("invalid syntax", message["message"].lower())
def test_json_report_does_not_escape_quotes(self): out = StringIO() module = join(HERE, "regrtest_data", "unused_variable.py") self._runtest([module], code=4, reporter=JSONReporter(out)) output = json.loads(out.getvalue()) assert isinstance(output, list) assert len(output) == 1 assert isinstance(output[0], dict) expected = { "symbol": "unused-variable", "module": "unused_variable", "column": 4, "message": "Unused variable 'variable'", "message-id": "W0612", "line": 4, "type": "warning", } message = output[0] for key, value in expected.items(): assert key in message assert message[key] == value
def validate_py3(path_to_module): """ Run pylint python3 validation on the python module/package provided """ with closing(StringIO()) as out: linter = PyLinter(reporter=JSONReporter(output=out)) linter.load_default_plugins() linter.python3_porting_mode() # Disable `no-absolute-import`, which checks for a behaviour that's already part of python 2.7 # cf https://www.python.org/dev/peps/pep-0328/ linter.disable("no-absolute-import") with fix_import_path([path_to_module]): linter.check(path_to_module) linter.generate_reports() raw_results = json.loads(out.getvalue() or "{}") results = [] for problem in raw_results: # An issue found by pylint is a dict like # { # "message": "Calling a dict.iter*() method", # "obj": "OpenFilesCheck.check", # "column": 27, # "path": "/path/to/file.py", # "line": 235, # "message-id": "W1620", # "type": "warning", # "symbol": "dict-iter-method",co # "module": "file" # } results.append({ "message": "Line {}, column {}: {}".format(problem["line"], problem["column"], problem["message"]), "path": problem["path"], }) return results
def apply_clicked(self, button): """Triggered when the Apply button in the source editor is clicked. """ if isinstance(self.model.state, LibraryState): logger.warn("It is not allowed to modify libraries.") self.view.set_text("") return # Ugly workaround to give user at least some feedback about the parser # Without the loop, this function would block the GTK main loop and the log message would appear after the # function has finished # TODO: run parser in separate thread while gtk.events_pending(): gtk.main_iteration_do() # get script current_text = self.view.get_text() # Directly apply script if linter was deactivated if not self.view['pylint_check_button'].get_active(): self.set_script_text(current_text) return logger.debug("Parsing execute script...") with open(self.tmp_file, "w") as text_file: text_file.write(current_text) # clear astroid module cache, see http://stackoverflow.com/questions/22241435/pylint-discard-cached-file-state MANAGER.astroid_cache.clear() lint_config_file = resource_filename(rafcon.__name__, "pylintrc") args = ["--rcfile={}".format(lint_config_file)] # put your own here with contextlib.closing(StringIO()) as dummy_buffer: json_report = JSONReporter(dummy_buffer) try: lint.Run([self.tmp_file] + args, reporter=json_report, exit=False) except: logger.exception("Could not run linter to check script") os.remove(self.tmp_file) if json_report.messages: def on_message_dialog_response_signal(widget, response_id): if response_id == 1: self.set_script_text(current_text) else: logger.debug("The script was not saved") widget.destroy() message_string = "Are you sure that you want to save this file?\n\nThe following errors were found:" line = None for message in json_report.messages: (error_string, line) = self.format_error_string(message) message_string += "\n\n" + error_string # focus line of error if line: tbuffer = self.view.get_buffer() start_iter = tbuffer.get_start_iter() start_iter.set_line(int(line) - 1) tbuffer.place_cursor(start_iter) message_string += "\n\nThe line was focused in the source editor." self.view.scroll_to_cursor_onscreen() # select state to show source editor sm_m = state_machine_manager_model.get_state_machine_model( self.model) if sm_m.selection.get_selected_state() is not self.model: sm_m.selection.set(self.model) RAFCONButtonDialog(message_string, ["Save with errors", "Do not save"], on_message_dialog_response_signal, message_type=gtk.MESSAGE_WARNING, parent=self.get_root_window()) else: self.set_script_text(current_text)