Skip to content

Commit

Permalink
flake
Browse files Browse the repository at this point in the history
  • Loading branch information
spacemanspiff2007 committed Jan 31, 2024
1 parent aa0265e commit 4aae221
Show file tree
Hide file tree
Showing 23 changed files with 80 additions and 55 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/run-tox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
python-version: '3.11'
- uses: pre-commit/[email protected]


Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ repos:


- repo: https://github.com/PyCQA/flake8
rev: '6.1.0'
rev: '7.0.0'
hooks:
- id: flake8
# additional_dependencies:
Expand Down
6 changes: 5 additions & 1 deletion .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ src = ["src", "test"]
# https://docs.astral.sh/ruff/settings/#ignore-init-module-imports
ignore-init-module-imports = true

extend-exclude = ["__init__.py"]
extend-exclude = [
"__init__.py",
"src/__test_*.py"
]

select = [
"E", "W", # https://docs.astral.sh/ruff/rules/#pycodestyle-e-w
Expand Down Expand Up @@ -62,6 +65,7 @@ builtins-ignorelist = ["id", "input"]
[lint.per-file-ignores]
"docs/conf.py" = ["INP001", "A001"]
"setup.py" = ["PTH123"]
"run/**" = ["INP001"]


[lint.isort]
Expand Down
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from docutils.nodes import Node, Text
from sphinx.addnodes import desc_signature


IS_RTD_BUILD = os.environ.get('READTHEDOCS', '-').lower() == 'true'
IS_CI = os.environ.get('CI', '-') == 'true'

Expand Down
1 change: 1 addition & 0 deletions run/conf/rules/logging_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import HABApp


log = logging.getLogger('MyRule')


Expand Down
6 changes: 3 additions & 3 deletions run/conf/rules/openhab_rule.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import HABApp
from HABApp.core.events import ValueUpdateEvent, ValueChangeEvent
from HABApp.openhab.events import ItemStateEvent, ItemCommandEvent, ItemStateChangedEvent
from HABApp.openhab.items import SwitchItem, ContactItem, DatetimeItem
from HABApp.core.events import ValueChangeEvent, ValueUpdateEvent
from HABApp.openhab.events import ItemCommandEvent, ItemStateChangedEvent, ItemStateEvent
from HABApp.openhab.items import ContactItem, DatetimeItem, SwitchItem


class MyOpenhabRule(HABApp.Rule):
Expand Down
2 changes: 1 addition & 1 deletion run/conf/rules/openhab_things.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from HABApp import Rule
from HABApp.core.events import EventFilter
from HABApp.openhab.events import ThingStatusInfoChangedEvent
from HABApp.openhab.items import Thing
from HABApp.core.events import EventFilter


class CheckAllThings(Rule):
Expand Down
2 changes: 1 addition & 1 deletion run/conf/rules/openhab_to_mqtt_rule.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import HABApp
from HABApp.openhab.events import ItemStateUpdatedEventFilter, ItemStateEvent
from HABApp.openhab.events import ItemStateEvent, ItemStateUpdatedEventFilter
from HABApp.openhab.items import OpenhabItem


Expand Down
3 changes: 2 additions & 1 deletion run/conf/rules/time_rule.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import time, timedelta, datetime
from datetime import datetime, time, timedelta

from HABApp import Rule


Expand Down
18 changes: 12 additions & 6 deletions run/conf_testing/lib/HABAppTests/event_waiter.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import logging
import time
from typing import TypeVar, Dict, Any
from typing import Union
from typing import Any, Dict, TypeVar, Union

from HABApp.core.events.filter import EventFilter
from HABApp.core.internals import EventBusListener, wrap_func, EventFilterBase, HINT_EVENT_FILTER_OBJ, \
get_current_context
from HABApp.core.internals import (
HINT_EVENT_FILTER_OBJ,
EventBusListener,
EventFilterBase,
get_current_context,
wrap_func,
)
from HABApp.core.items import BaseValueItem
from HABAppTests.errors import TestCaseFailed

from .compare_values import get_equal_text, get_value_text


log = logging.getLogger('HABApp.Tests')

EVENT_TYPE = TypeVar('EVENT_TYPE')
Expand Down Expand Up @@ -52,8 +58,8 @@ def wait_for_event(self, **kwargs) -> EVENT_TYPE:

if time.time() > start + self.timeout:
expected_values = "with " + ", ".join([f"{__k}={__v}" for __k, __v in kwargs.items()]) if kwargs else ""
raise TestCaseFailed(f'Timeout while waiting for {self.event_filter.describe()} '
f'for {self.name} {expected_values}')
msg = f'Timeout while waiting for {self.event_filter.describe()} for {self.name} {expected_values}'
raise TestCaseFailed(msg)

if not self._received_events:
continue
Expand Down
6 changes: 3 additions & 3 deletions run/conf_testing/lib/HABAppTests/item_waiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from HABAppTests.compare_values import get_equal_text
from HABAppTests.errors import TestCaseFailed


log = logging.getLogger('HABApp.Tests')


Expand Down Expand Up @@ -35,9 +36,8 @@ def wait_for_attribs(self, **kwargs):
for name, target in kwargs.items()
]
failed_msg = "\n".join(failed)
raise TestCaseFailed(f'Timeout waiting for {self.item.name}!\n{failed_msg}')

raise ValueError()
msg = f'Timeout waiting for {self.item.name}!\n{failed_msg}'
raise TestCaseFailed(msg)

def wait_for_state(self, state=None):
return self.wait_for_attribs(value=state)
Expand Down
14 changes: 8 additions & 6 deletions run/conf_testing/lib/HABAppTests/openhab_tmp_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@

import HABApp
from HABApp.openhab.definitions.topics import TOPIC_ITEMS
from . import get_random_name, EventWaiter

from . import EventWaiter, get_random_name


class OpenhabTmpItem:
@staticmethod
def use(type: str, name: Optional[str] = None, arg_name: str = 'item'):
def use(item_type: str, name: Optional[str] = None, arg_name: str = 'item'):
def decorator(func):
@wraps(func)
def new_func(*args, **kwargs):
assert arg_name not in kwargs, f'arg {arg_name} already set'
item = OpenhabTmpItem(type, name)
item = OpenhabTmpItem(item_type, name)
try:
kwargs[arg_name] = item
return func(*args, **kwargs)
Expand All @@ -24,11 +25,11 @@ def new_func(*args, **kwargs):
return decorator

@staticmethod
def create(type: str, name: Optional[str] = None, arg_name: Optional[str] = None):
def create(item_type: str, name: Optional[str] = None, arg_name: Optional[str] = None):
def decorator(func):
@wraps(func)
def new_func(*args, **kwargs):
with OpenhabTmpItem(type, name) as f:
with OpenhabTmpItem(item_type, name) as f:
if arg_name is not None:
assert arg_name not in kwargs, f'arg {arg_name} already set'
kwargs[arg_name] = f
Expand Down Expand Up @@ -69,7 +70,8 @@ def create_item(self, label="", category="", tags: List[str] = [], groups: List[
while not HABApp.core.Items.item_exists(self.name):
time.sleep(0.01)
if time.time() > stop:
raise TimeoutError(f'Item {self.name} was not found!')
msg = f'Item {self.name} was not found!'
raise TimeoutError(msg)

return HABApp.openhab.items.OpenhabItem.get_item(self.name)

Expand Down
5 changes: 3 additions & 2 deletions src/HABApp/openhab/items/group_item.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from typing import TYPE_CHECKING, Optional, FrozenSet, Mapping, Tuple, Any
from typing import TYPE_CHECKING, Any, FrozenSet, Mapping, Optional, Tuple

from HABApp.core.events import ComplexEventValue
from HABApp.openhab.item_to_reg import get_members
from HABApp.openhab.items.base_item import OpenhabItem, MetaData
from HABApp.openhab.items.base_item import MetaData, OpenhabItem


if TYPE_CHECKING:
Any = Any
Expand Down
9 changes: 5 additions & 4 deletions src/HABApp/openhab/items/number_item.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from typing import Optional, FrozenSet, Mapping, Union, TYPE_CHECKING
from typing import TYPE_CHECKING, FrozenSet, Mapping, Optional, Union

from HABApp.core.errors import InvalidItemValue, ItemValueIsNoneError
from HABApp.openhab.definitions import QuantityValue
from HABApp.openhab.items.base_item import MetaData, OpenhabItem

from HABApp.openhab.items.base_item import OpenhabItem, MetaData
from ..definitions import QuantityValue
from ...core.errors import ItemValueIsNoneError, InvalidItemValue

if TYPE_CHECKING:
Union = Union
Expand Down
2 changes: 1 addition & 1 deletion src/HABApp/parameters/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def set_file_validator(filename: str, validator: typing.Any, allow_extra_keys=Tr
validator, required=True, extra=(voluptuous.ALLOW_EXTRA if allow_extra_keys else voluptuous.PREVENT_EXTRA)
)

# todo: move this to file handling so we get the extension
# TODO: move this to file handling so we get the extension
if old_validator != new_validator:
reload_param_file(filename)

Expand Down
3 changes: 2 additions & 1 deletion src/HABApp/rule_manager/rule_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
from pathlib import Path

import HABApp
from HABApp.rule.rule_hook import HABAppRuleHook
from HABApp.core.internals import get_current_context
from HABApp.rule.rule_hook import HABAppRuleHook


log = logging.getLogger('HABApp.Rules')

Expand Down
9 changes: 5 additions & 4 deletions src/HABApp/rule_manager/rule_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@

import HABApp
import HABApp.__cmd_args__ as cmd_args
from HABApp.core.connections import Connections
from HABApp.core.files.errors import AlreadyHandledFileError
from HABApp.core.files.file import HABAppFile
from HABApp.core.files.folders import add_folder as add_habapp_folder
from HABApp.core.files.watcher import AggregatingAsyncEventHandler
from HABApp.core.internals import uses_item_registry
from HABApp.core.internals.wrapped_function import run_function
from HABApp.core.logger import log_warning
from HABApp.core.wrapper import log_exception
from HABApp.rule_manager.rule_file import RuleFile
from HABApp.runtime import shutdown
from .rule_file import RuleFile
from ..core.internals import uses_item_registry
from HABApp.core.internals.wrapped_function import run_function
from HABApp.core.connections import Connections


log = logging.getLogger('HABApp.Rules')

Expand Down
4 changes: 2 additions & 2 deletions src/HABApp/runtime/shutdown.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import itertools
import logging
import logging.handlers
import signal
import traceback
import typing
import signal
from asyncio import iscoroutinefunction, sleep
from dataclasses import dataclass
from types import FunctionType, MethodType
Expand All @@ -30,7 +30,7 @@ def register_func(func, last=False, msg: str = ''):
assert last is True or last is False, last
assert isinstance(msg, str)

_FUNCS.append(ShutdownInfo(func, f'{func.__module__}.{func.__name__}' if not msg else msg, last))
_FUNCS.append(ShutdownInfo(func, msg if msg else f'{func.__module__}.{func.__name__}', last))


def register_signal_handler():
Expand Down
22 changes: 14 additions & 8 deletions src/HABApp/util/listener_groups/listener_groups.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
from typing import Any, Callable, Dict, Iterable, Optional, Union

from HABApp.core.internals import HINT_EVENT_FILTER_OBJ
from HABApp.core.items import BaseItem, HINT_ITEM_OBJ

from HABApp.core.items import HINT_ITEM_OBJ, BaseItem
from HABApp.core.lib.parameters import TH_POSITIVE_TIME_DIFF
from .listener_creator import ListenerCreatorBase, EventListenerCreator, \
NoChangeEventListenerCreator, NoUpdateEventListenerCreator

from .listener_creator import (
EventListenerCreator,
ListenerCreatorBase,
NoChangeEventListenerCreator,
NoUpdateEventListenerCreator,
)


class ListenerCreatorNotFoundError(Exception):
pass
@classmethod
def from_name(cls, name: str):
return cls(f'ListenerCreator for "{name}" not found!')


class EventListenerGroup:
Expand Down Expand Up @@ -57,7 +63,7 @@ def activate_listener(self, name: str):
try:
obj = self._items[name]
except KeyError:
raise ListenerCreatorNotFoundError(f'ListenerCreator for "{name}" not found!') from None
raise ListenerCreatorNotFoundError.from_name(name) from None
if obj.active:
return False

Expand All @@ -76,7 +82,7 @@ def deactivate_listener(self, name: str, cancel_if_active=True):
try:
obj = self._items[name]
except KeyError:
raise ListenerCreatorNotFoundError(f'ListenerCreator for "{name}" not found!') from None
raise ListenerCreatorNotFoundError.from_name(name) from None
if not obj.active:
return False

Expand Down Expand Up @@ -135,7 +141,7 @@ def add_no_update_watcher(self, item: Union[HINT_ITEM_OBJ, Iterable[HINT_ITEM_OB
def add_no_change_watcher(self, item: Union[HINT_ITEM_OBJ, Iterable[HINT_ITEM_OBJ]], callback: Callable[[Any], Any],
seconds: TH_POSITIVE_TIME_DIFF, alias: Optional[str] = None
) -> 'EventListenerGroup':
"""Add an no change watcher to the group. On ``listen`` this this will create a no change watcher and
"""Add a no change watcher to the group. On ``listen`` this will create a no change watcher and
the corresponding event listener that will trigger the callback
:param item: Single or multiple items
Expand Down
1 change: 1 addition & 0 deletions src/HABApp/util/multimode/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from .mode_base import HINT_BASE_MODE, BaseMode


LOCK = Lock()


Expand Down
14 changes: 6 additions & 8 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@
import pytest

import HABApp
import tests
from HABApp.core.asyncio import async_context
from HABApp.core.const.topics import TOPIC_ERRORS
from HABApp.core.internals import setup_internals, EventBus, ItemRegistry
from tests.helpers import params, parent_rule, sync_worker, eb, get_dummy_cfg, LogCollector
from tests.helpers.log.log_matcher import LogLevelMatcher, AsyncDebugWarningMatcher
from HABApp.core.internals import EventBus, ItemRegistry, setup_internals
from tests.helpers import LogCollector, eb, get_dummy_cfg, params, parent_rule, sync_worker
from tests.helpers.log.log_matcher import AsyncDebugWarningMatcher, LogLevelMatcher


if typing.TYPE_CHECKING:
parent_rule = parent_rule
Expand Down Expand Up @@ -48,7 +47,7 @@ def use_dummy_cfg(monkeypatch):
monkeypatch.setattr(HABApp, 'CONFIG', cfg)
monkeypatch.setattr(HABApp.config, 'CONFIG', cfg)
monkeypatch.setattr(HABApp.config.config, 'CONFIG', cfg)
yield cfg
return cfg


@pytest.fixture(autouse=True, scope='session')
Expand All @@ -62,8 +61,7 @@ def event_loop():

@pytest.fixture(scope='function')
def ir():
ir = ItemRegistry()
yield ir
return ItemRegistry()


@pytest.fixture(autouse=True, scope='function')
Expand Down
1 change: 1 addition & 0 deletions tools/prettify_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from json import dumps, loads


INCLUDE_CHANNELS = False


Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ envlist =
python =
3.8: py38
3.9: py39
3.10: py310, flake, docs
3.10: py310, docs
3.11: py311
3.12: py312

Expand Down

0 comments on commit 4aae221

Please sign in to comment.