Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def create_plugin_mock(raise_exception=False):
"""Create an auto-spec'd mock of a flake8 Plugin."""
plugin = mock.create_autospec(manager.Plugin, instance=True)
if raise_exception:
plugin.load_plugin.side_effect = exceptions.FailedToLoadPlugin(
plugin_name='T101',
exception=ValueError('Test failure'),
)
return plugin
def test_load_noncallable_plugin():
"""Verify that we do not load a non-callable plugin."""
entry_point = mock.Mock(spec=['load'])
entry_point.load.return_value = mock.NonCallableMock()
plugin = manager.Plugin('T000', entry_point)
with pytest.raises(exceptions.FailedToLoadPlugin):
plugin.load_plugin()
entry_point.load.assert_called_once_with()
err = exceptions.InvalidSyntax(exception=ValueError('Unexpected token: $'))
class TestPluginRequestedUnknownParameters(_ExceptionTest):
"""Tests for the PluginRequestedUnknownParameters exception."""
err = exceptions.PluginRequestedUnknownParameters(
plugin={'plugin_name': 'plugin_name'},
exception=ValueError('boom!'),
)
class TestPluginExecutionFailed(_ExceptionTest):
"""Tests for the PluginExecutionFailed exception."""
err = exceptions.PluginExecutionFailed(
plugin={'plugin_name': 'plugin_name'},
exception=ValueError('boom!'),
)
This will intelligently decide whether to run the checks in parallel
or whether to run them in serial.
If running the checks in parallel causes a problem (e.g.,
https://gitlab.com/pycqa/flake8/issues/74) this also implements
fallback to serial processing.
"""
try:
if self.jobs > 1 and len(self.checkers) > 1:
self.run_parallel()
else:
self.run_serial()
except KeyboardInterrupt:
LOG.warning("Flake8 was interrupted by the user")
raise exceptions.EarlyQuit("Early quit while running checks")
def generate_tokens(self): # type: () -> Generator[_Token, None, None]
"""Tokenize the file and yield the tokens.
:raises flake8.exceptions.InvalidSyntax:
If a :class:`tokenize.TokenError` is raised while generating
tokens.
"""
try:
for token in tokenize.generate_tokens(self.next_line):
if token[2][0] > self.total_lines:
break
self.tokens.append(token)
yield token
except (tokenize.TokenError, SyntaxError) as exc:
raise exceptions.InvalidSyntax(exception=exc)
def generate_tokens(self):
"""Tokenize the file and yield the tokens.
:raises flake8.exceptions.InvalidSyntax:
If a :class:`tokenize.TokenError` is raised while generating
tokens.
"""
try:
for token in tokenize.generate_tokens(self.next_line):
if token[2][0] > self.total_lines:
break
self.tokens.append(token)
yield token
except (tokenize.TokenError, SyntaxError) as exc:
raise exceptions.InvalidSyntax(exception=exc)
"""Retrieve the plugin for this entry-point.
This loads the plugin, stores it on the instance and then returns it.
It does not reload it after the first time, it merely returns the
cached plugin.
:returns:
Nothing
"""
if self._plugin is None:
LOG.info('Loading plugin "%s" from entry-point.', self.name)
try:
self._load()
except Exception as load_exception:
LOG.exception(load_exception)
failed_to_load = exceptions.FailedToLoadPlugin(
plugin=self, exception=load_exception
)
LOG.critical(str(failed_to_load))
raise failed_to_load
# type: (Optional[List[str]]) -> None
"""Run the actual checks with the FileChecker Manager.
This method encapsulates the logic to make a
:class:`~flake8.checker.Manger` instance run the checks it is
managing.
:param list files:
List of filenames to process
"""
if self.running_against_diff:
files = sorted(self.parsed_diff)
self.file_checker_manager.start(files)
try:
self.file_checker_manager.run()
except exceptions.PluginExecutionFailed as plugin_failed:
print(str(plugin_failed))
print("Run flake8 with greater verbosity to see more details")
self.catastrophic_failure = True
LOG.info("Finished running")
self.file_checker_manager.stop()
self.end_time = time.time()
entirety of the flake8 application. If it sees a KeyboardInterrupt it
will forcibly clean up the :class:`~flake8.checker.Manager`.
"""
try:
self._run(argv)
except KeyboardInterrupt as exc:
print("... stopped")
LOG.critical("Caught keyboard interrupt from user")
LOG.exception(exc)
self.catastrophic_failure = True
except exceptions.ExecutionError as exc:
print("There was a critical error during execution of Flake8:")
print(exc)
LOG.exception(exc)
self.catastrophic_failure = True
except exceptions.EarlyQuit:
self.catastrophic_failure = True
print("... stopped while processing files")
:raises:
flake8.exceptions.MercurialCommitHookAlreadyExists
:raises:
flake8.exceptions.MercurialQRefreshHookAlreadyExists
"""
hgrc = find_hgrc(create_if_missing=True)
if hgrc is None:
return False
hgconfig = configparser_for(hgrc)
if not hgconfig.has_section("hooks"):
hgconfig.add_section("hooks")
if hgconfig.has_option("hooks", "commit"):
raise exc.MercurialCommitHookAlreadyExists(
path=hgrc, value=hgconfig.get("hooks", "commit")
)
if hgconfig.has_option("hooks", "qrefresh"):
raise exc.MercurialQRefreshHookAlreadyExists(
path=hgrc, value=hgconfig.get("hooks", "qrefresh")
)
hgconfig.set("hooks", "commit", "python:flake8.main.mercurial.hook")
hgconfig.set("hooks", "qrefresh", "python:flake8.main.mercurial.hook")
if not hgconfig.has_section("flake8"):
hgconfig.add_section("flake8")
if not hgconfig.has_option("flake8", "strict"):
hgconfig.set("flake8", "strict", False)