Skip to content

Commit

Permalink
flake8
Browse files Browse the repository at this point in the history
  • Loading branch information
mazborowski committed Jun 26, 2024
1 parent 0fceb71 commit 30a00a7
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 91 deletions.
10 changes: 10 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,13 @@ classifiers = [
[project.urls]
Homepage = "https://github.com/zeebrow/quickhost"
Issues = "https://github.com/zeebrow/quickhost/issues"

[flake8]
ignore = E501
exclude =
.git,
__pycache__,
venv*,
build,
tmp,
dist,
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ exclude =
build,
tmp,
dist,
deb_dist
14 changes: 7 additions & 7 deletions src/quickhost/QuickhostPlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

import typing as t

from collections import defaultdict
from dataclasses import dataclass

from .quickhost_app_base import AppBase, ParserBase
Expand Down Expand Up @@ -58,11 +57,11 @@ def get_plugin(plugin_name: PluginName) -> Plugin:
:rtype: quickhost.QuickhostPlugin.Plugin
[options.entry_points]
quickhost_plugin =
quickhost_plugin =
<plugin_name>_app = quickhost_<plugin_name>:get_app
<plugin_name>_parser = quickhost_<plugin_name>:get_parser
"""

qh_plugins = metadata.entry_points(group='quickhost_plugin')
try:
v = version(f'quickhost_{plugin_name}')
Expand All @@ -87,7 +86,7 @@ def get_plugin(plugin_name: PluginName) -> Plugin:
def get_plugin_app_getter(plugin_name: PluginName) -> t.Callable[..., AppBase]:
"""
Get the loader a :class:`quickhost.quickhost_app_base.AppBase` subclass.
:param name: Name of the plugin
:type name: str
:raises NoPluginFoundError: The pip package 'quickhost-<plugin_name>' is not installed
Expand All @@ -97,14 +96,15 @@ def get_plugin_app_getter(plugin_name: PluginName) -> t.Callable[..., AppBase]:
try:
qh_plugins = metadata.entry_points(group='quickhost_plugin')[f'{plugin_name}_app']
return qh_plugins.load()
except:
# "do not use bare except" ???
except: # noqa: E722
raise NoPluginFoundError(f"No plugin found for '{plugin_name}' -- try running pip install quickhost-{plugin_name}")


def get_plugin_parser_getter(plugin_name: PluginName) -> t.Callable[..., ParserBase]:
"""
Get the loader a :class:`quickhost.quickhost_app_base.ParserBase` subclass.
:param name: Name of the plugin
:type name: str
:raises NoPluginFoundError: The pip package 'quickhost-<plugin_name>' is not installed
Expand All @@ -114,7 +114,7 @@ def get_plugin_parser_getter(plugin_name: PluginName) -> t.Callable[..., ParserB
try:
qh_plugins = metadata.entry_points(group='quickhost_plugin')[f'{plugin_name}_parser']
return qh_plugins.load()
except:
except: # noqa: E722
raise NoPluginFoundError(f"No plugin found for '{plugin_name}' -- try running pip install quickhost-{plugin_name}")


Expand Down
2 changes: 0 additions & 2 deletions src/quickhost/quickhost_app_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
from abc import abstractmethod, abstractclassmethod
import logging

from .constants import APP_CONST as C

logger = logging.getLogger(__name__)


Expand Down
4 changes: 2 additions & 2 deletions src/quickhost/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def format(self, record):
elif record.levelno == logging.CRITICAL:
self._style._fmt = QHLogFormatter.ErrorFormatColor
else: # make coverage happy
self._style._fmt = self._style._fmt
self._style._fmt = self._style._fmt
else:
if record.levelno == logging.DEBUG:
self._style._fmt = QHLogFormatter.DebugFormat
Expand All @@ -89,5 +89,5 @@ def format(self, record):
elif record.levelno == logging.CRITICAL:
self._style._fmt = QHLogFormatter.ErrorFormat
else: # make coverage happy
self._style._fmt = self._style._fmt
self._style._fmt = self._style._fmt
return super().format(record)
140 changes: 68 additions & 72 deletions tests/test_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,110 +14,106 @@
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import sys
if sys.version_info.minor == 7:
import importlib_metadata as metadata
from importlib_metadata import version
import importlib_metadata as metadata
else:
from importlib import metadata
from importlib.metadata import version
import importlib
from importlib import metadata # noqa: F401
import tempfile
import shutil
from pathlib import Path
from textwrap import dedent

from unittest.mock import patch
import pytest
from pytest import MonkeyPatch
from mock import patch, Mock, MagicMock

from quickhost.QuickhostPlugin import (
fetch_all_plugins,
get_plugin,
get_plugin_app_getter,
get_plugin_parser_getter,
NoPluginFoundError,
Plugin,
PluginName
fetch_all_plugins,
get_plugin,
get_plugin_app_getter,
get_plugin_parser_getter,
NoPluginFoundError,
)


PLUGIN_NAME = 'fakeplugin'
PLUGIN_VERSION = 'fake.version'


@pytest.fixture
def mock_package(monkeypatch: MonkeyPatch):
try:
with monkeypatch.context() as m:
temp_dir = Path(tempfile.mkdtemp())
pkg_root = temp_dir / 'src'
plugin_dir = pkg_root / f'quickhost_{PLUGIN_NAME}'
plugin_dir.mkdir(parents=True)
init_py = plugin_dir / '__init__.py'
with init_py.open('w') as f:
f.write(dedent(f"""\
def get_app(): return "{PLUGIN_NAME}_app"
def get_parser(): return "{PLUGIN_NAME}_parser"
"""))

dist_info_base = temp_dir / 'test-site-pkg'
dist_info = dist_info_base / f'quickhost_{PLUGIN_NAME}-{PLUGIN_VERSION}.dist-info'
dist_info.mkdir(parents=True)

METADATA_txt = dist_info / 'METADATA'
with METADATA_txt.open('w') as f:
f.write(dedent(f"""\
Metadata-Version: 2.1
Name: quickhost-{PLUGIN_NAME}
Version: {PLUGIN_VERSION}
Requires-Dist: quickhost
"""))

entry_points_txt = dist_info / 'entry_points.txt'
with entry_points_txt.open('w') as f:
f.write(dedent(f"""\
[quickhost_plugin]
{PLUGIN_NAME}_app = quickhost_{PLUGIN_NAME}:get_app
{PLUGIN_NAME}_parser = quickhost_{PLUGIN_NAME}:get_parser
"""))

m.syspath_prepend(str(pkg_root.absolute()))
m.syspath_prepend(str(dist_info_base.absolute()))
yield
finally:
shutil.rmtree(temp_dir)
try:
with monkeypatch.context() as m:
temp_dir = Path(tempfile.mkdtemp())
pkg_root = temp_dir / 'src'
plugin_dir = pkg_root / f'quickhost_{PLUGIN_NAME}'
plugin_dir.mkdir(parents=True)
init_py = plugin_dir / '__init__.py'
with init_py.open('w') as f:
f.write(dedent(f"""\
def get_app(): return "{PLUGIN_NAME}_app"
def get_parser(): return "{PLUGIN_NAME}_parser"
"""))

dist_info_base = temp_dir / 'test-site-pkg'
dist_info = dist_info_base / f'quickhost_{PLUGIN_NAME}-{PLUGIN_VERSION}.dist-info'
dist_info.mkdir(parents=True)

METADATA_txt = dist_info / 'METADATA'
with METADATA_txt.open('w') as f:
f.write(dedent(f"""\
Metadata-Version: 2.1
Name: quickhost-{PLUGIN_NAME}
Version: {PLUGIN_VERSION}
Requires-Dist: quickhost
"""))

entry_points_txt = dist_info / 'entry_points.txt'
with entry_points_txt.open('w') as f:
f.write(dedent(f"""\
[quickhost_plugin]
{PLUGIN_NAME}_app = quickhost_{PLUGIN_NAME}:get_app
{PLUGIN_NAME}_parser = quickhost_{PLUGIN_NAME}:get_parser
"""))

m.syspath_prepend(str(pkg_root.absolute()))
m.syspath_prepend(str(dist_info_base.absolute()))
yield
finally:
shutil.rmtree(temp_dir)


@pytest.fixture
def fake_plugin_entrypoints(mock_package):
app_getter = metadata.EntryPoint(name=f'{PLUGIN_NAME}_app', value=f'quickhost_{PLUGIN_NAME}:get_app', group='quickhost_plugin')
parser_getter = metadata.EntryPoint(name=f'{PLUGIN_NAME}_parser', value=f'quickhost_{PLUGIN_NAME}:get_parser', group='quickhost_plugin')
return metadata.EntryPoints({app_getter, parser_getter})
app_getter = metadata.EntryPoint(name=f'{PLUGIN_NAME}_app', value=f'quickhost_{PLUGIN_NAME}:get_app', group='quickhost_plugin')
parser_getter = metadata.EntryPoint(name=f'{PLUGIN_NAME}_parser', value=f'quickhost_{PLUGIN_NAME}:get_parser', group='quickhost_plugin')
return metadata.EntryPoints({app_getter, parser_getter})


def test_plugin(fake_plugin_entrypoints):
with patch('quickhost.QuickhostPlugin.metadata.entry_points', lambda *args, **kwargs: fake_plugin_entrypoints):
plugin = get_plugin(PLUGIN_NAME)
assert get_plugin_app_getter(PLUGIN_NAME)() == f"{PLUGIN_NAME}_app" == plugin.app
assert get_plugin_parser_getter(PLUGIN_NAME)() == f"{PLUGIN_NAME}_parser" == plugin.parser
assert plugin.name == PLUGIN_NAME
assert plugin.version == PLUGIN_VERSION
assert plugin.package_name == f"quickhost_{PLUGIN_NAME}"
with patch('quickhost.QuickhostPlugin.metadata.entry_points', lambda *args, **kwargs: fake_plugin_entrypoints):
plugin = get_plugin(PLUGIN_NAME)
assert get_plugin_app_getter(PLUGIN_NAME)() == f"{PLUGIN_NAME}_app" == plugin.app
assert get_plugin_parser_getter(PLUGIN_NAME)() == f"{PLUGIN_NAME}_parser" == plugin.parser
assert plugin.name == PLUGIN_NAME
assert plugin.version == PLUGIN_VERSION
assert plugin.package_name == f"quickhost_{PLUGIN_NAME}"


def test_get_plugin_nonexistant_plugin_raises():
with pytest.raises(NoPluginFoundError):
get_plugin('nonexistant')
with pytest.raises(NoPluginFoundError):
get_plugin('nonexistant')


def test_get_plugin_app_nonexistant_plugin_raises():
with pytest.raises(NoPluginFoundError):
get_plugin_app_getter('nonexistant')
with pytest.raises(NoPluginFoundError):
get_plugin_app_getter('nonexistant')


def test_get_plugin_parser_nonexistant_plugin_raises():
with pytest.raises(NoPluginFoundError):
get_plugin_parser_getter('nonexistant')
with pytest.raises(NoPluginFoundError):
get_plugin_parser_getter('nonexistant')


def test_fetch_all_plugins(fake_plugin_entrypoints):
plugins = fetch_all_plugins()
assert PLUGIN_NAME in plugins.keys()

plugins = fetch_all_plugins()
assert PLUGIN_NAME in plugins.keys()
4 changes: 0 additions & 4 deletions tests/test_todo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,2 @@
import pytest

from quickhost import Cli, constants, quickhost_app_base, QuickhostPlugin, utilities

def test_test():
pass
6 changes: 2 additions & 4 deletions tests/test_utilities.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import pytest
from pytest import MonkeyPatch
from unittest.mock import patch, Mock, MagicMock
from unittest.mock import patch, MagicMock
import datetime
import json
import logging
Expand All @@ -22,7 +21,6 @@ def test_get_my_ip():
def test_get_my_ip_exception():
"""icanhazip.com is always available"""
m = MagicMock(side_effect=Exception)
i = MagicMock()
with patch('urllib.request.urlopen', m), \
patch('quickhost.utilities.input', return_value='4.3.2.1'):
assert get_my_public_ip() == '4.3.2.1/32'
Expand Down Expand Up @@ -103,4 +101,4 @@ def test_colorized_log_formatter_turns_off(caplog):
assert '\033[31m' not in fmted_r
if r.levelno == logging.CRITICAL:
assert '\033[31m' not in fmted_r
assert '\033[0m' not in fmted_r
assert '\033[0m' not in fmted_r

0 comments on commit 30a00a7

Please sign in to comment.