Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix import pylint warning in core tests #119359

Merged
merged 2 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@
issue_registry as ir,
label_registry as lr,
recorder as recorder_helper,
restore_state,
restore_state as rs,
storage,
translation,
Expand Down Expand Up @@ -100,7 +99,7 @@
from homeassistant.util.unit_system import METRIC_SYSTEM
import homeassistant.util.yaml.loader as yaml_loader

from tests.testing_config.custom_components.test_constant_deprecation import (
from .testing_config.custom_components.test_constant_deprecation import (
import_deprecated_constant,
)

Expand Down Expand Up @@ -1133,6 +1132,7 @@ def init_recorder_component(hass, add_config=None, db_url="sqlite://"):
"""Initialize the recorder."""
# Local import to avoid processing recorder and SQLite modules when running a
# testcase which does not use the recorder.
# pylint: disable-next=import-outside-toplevel
from homeassistant.components import recorder

config = dict(add_config) if add_config else {}
Expand All @@ -1154,8 +1154,8 @@ def init_recorder_component(hass, add_config=None, db_url="sqlite://"):

def mock_restore_cache(hass: HomeAssistant, states: Sequence[State]) -> None:
"""Mock the DATA_RESTORE_CACHE."""
key = restore_state.DATA_RESTORE_STATE
data = restore_state.RestoreStateData(hass)
key = rs.DATA_RESTORE_STATE
data = rs.RestoreStateData(hass)
now = dt_util.utcnow()

last_states = {}
Expand All @@ -1167,23 +1167,23 @@ def mock_restore_cache(hass: HomeAssistant, states: Sequence[State]) -> None:
json.dumps(restored_state["attributes"], cls=JSONEncoder)
),
}
last_states[state.entity_id] = restore_state.StoredState.from_dict(
last_states[state.entity_id] = rs.StoredState.from_dict(
{"state": restored_state, "last_seen": now}
)
data.last_states = last_states
_LOGGER.debug("Restore cache: %s", data.last_states)
assert len(data.last_states) == len(states), f"Duplicate entity_id? {states}"

restore_state.async_get.cache_clear()
rs.async_get.cache_clear()
hass.data[key] = data


def mock_restore_cache_with_extra_data(
hass: HomeAssistant, states: Sequence[tuple[State, Mapping[str, Any]]]
) -> None:
"""Mock the DATA_RESTORE_CACHE."""
key = restore_state.DATA_RESTORE_STATE
data = restore_state.RestoreStateData(hass)
key = rs.DATA_RESTORE_STATE
data = rs.RestoreStateData(hass)
now = dt_util.utcnow()

last_states = {}
Expand All @@ -1195,22 +1195,22 @@ def mock_restore_cache_with_extra_data(
json.dumps(restored_state["attributes"], cls=JSONEncoder)
),
}
last_states[state.entity_id] = restore_state.StoredState.from_dict(
last_states[state.entity_id] = rs.StoredState.from_dict(
{"state": restored_state, "extra_data": extra_data, "last_seen": now}
)
data.last_states = last_states
_LOGGER.debug("Restore cache: %s", data.last_states)
assert len(data.last_states) == len(states), f"Duplicate entity_id? {states}"

restore_state.async_get.cache_clear()
rs.async_get.cache_clear()
hass.data[key] = data


async def async_mock_restore_state_shutdown_restart(
hass: HomeAssistant,
) -> restore_state.RestoreStateData:
) -> rs.RestoreStateData:
"""Mock shutting down and saving restore state and restoring."""
data = restore_state.async_get(hass)
data = rs.async_get(hass)
await data.async_dump_states()
await async_mock_load_restore_state_from_storage(hass)
return data
Expand All @@ -1223,7 +1223,7 @@ async def async_mock_load_restore_state_from_storage(

hass_storage must already be mocked.
"""
await restore_state.async_get(hass).async_load()
await rs.async_get(hass).async_load()


class MockEntity(entity.Entity):
Expand Down Expand Up @@ -1571,6 +1571,7 @@ def async_get_persistent_notifications(

def async_mock_cloud_connection_status(hass: HomeAssistant, connected: bool) -> None:
"""Mock a signal the cloud disconnected."""
# pylint: disable-next=import-outside-toplevel
from homeassistant.components.cloud import (
SIGNAL_CLOUD_CONNECTION_STATE,
CloudConnectionState,
Expand Down
40 changes: 24 additions & 16 deletions tests/components/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ def entity_registry_enabled_by_default() -> Generator[None]:
@pytest.fixture(name="stub_blueprint_populate")
def stub_blueprint_populate_fixture() -> Generator[None]:
"""Stub copying the blueprints to the config folder."""
from tests.components.blueprint.common import stub_blueprint_populate_fixture_helper
# pylint: disable-next=import-outside-toplevel
from .blueprint.common import stub_blueprint_populate_fixture_helper

yield from stub_blueprint_populate_fixture_helper()

Expand All @@ -63,7 +64,8 @@ def stub_blueprint_populate_fixture() -> Generator[None]:
@pytest.fixture(name="mock_tts_get_cache_files")
def mock_tts_get_cache_files_fixture() -> Generator[MagicMock]:
"""Mock the list TTS cache function."""
from tests.components.tts.common import mock_tts_get_cache_files_fixture_helper
# pylint: disable-next=import-outside-toplevel
from .tts.common import mock_tts_get_cache_files_fixture_helper

yield from mock_tts_get_cache_files_fixture_helper()

Expand All @@ -73,17 +75,17 @@ def mock_tts_init_cache_dir_fixture(
init_tts_cache_dir_side_effect: Any,
) -> Generator[MagicMock]:
"""Mock the TTS cache dir in memory."""
from tests.components.tts.common import mock_tts_init_cache_dir_fixture_helper
# pylint: disable-next=import-outside-toplevel
from .tts.common import mock_tts_init_cache_dir_fixture_helper

yield from mock_tts_init_cache_dir_fixture_helper(init_tts_cache_dir_side_effect)


@pytest.fixture(name="init_tts_cache_dir_side_effect")
def init_tts_cache_dir_side_effect_fixture() -> Any:
"""Return the cache dir."""
from tests.components.tts.common import (
init_tts_cache_dir_side_effect_fixture_helper,
)
# pylint: disable-next=import-outside-toplevel
from .tts.common import init_tts_cache_dir_side_effect_fixture_helper

return init_tts_cache_dir_side_effect_fixture_helper()

Expand All @@ -96,7 +98,8 @@ def mock_tts_cache_dir_fixture(
request: pytest.FixtureRequest,
) -> Generator[Path]:
"""Mock the TTS cache dir with empty dir."""
from tests.components.tts.common import mock_tts_cache_dir_fixture_helper
# pylint: disable-next=import-outside-toplevel
from .tts.common import mock_tts_cache_dir_fixture_helper

yield from mock_tts_cache_dir_fixture_helper(
tmp_path, mock_tts_init_cache_dir, mock_tts_get_cache_files, request
Expand All @@ -106,17 +109,17 @@ def mock_tts_cache_dir_fixture(
@pytest.fixture(name="tts_mutagen_mock")
def tts_mutagen_mock_fixture() -> Generator[MagicMock]:
"""Mock writing tags."""
from tests.components.tts.common import tts_mutagen_mock_fixture_helper
# pylint: disable-next=import-outside-toplevel
from .tts.common import tts_mutagen_mock_fixture_helper

yield from tts_mutagen_mock_fixture_helper()


@pytest.fixture(name="mock_conversation_agent")
def mock_conversation_agent_fixture(hass: HomeAssistant) -> MockAgent:
"""Mock a conversation agent."""
from tests.components.conversation.common import (
mock_conversation_agent_fixture_helper,
)
# pylint: disable-next=import-outside-toplevel
from .conversation.common import mock_conversation_agent_fixture_helper

return mock_conversation_agent_fixture_helper(hass)

Expand All @@ -133,7 +136,8 @@ def prevent_ffmpeg_subprocess() -> Generator[None]:
@pytest.fixture
def mock_light_entities() -> list[MockLight]:
"""Return mocked light entities."""
from tests.components.light.common import MockLight
# pylint: disable-next=import-outside-toplevel
from .light.common import MockLight

return [
MockLight("Ceiling", STATE_ON),
Expand All @@ -145,30 +149,34 @@ def mock_light_entities() -> list[MockLight]:
@pytest.fixture
def mock_sensor_entities() -> dict[str, MockSensor]:
"""Return mocked sensor entities."""
from tests.components.sensor.common import get_mock_sensor_entities
# pylint: disable-next=import-outside-toplevel
from .sensor.common import get_mock_sensor_entities

return get_mock_sensor_entities()


@pytest.fixture
def mock_switch_entities() -> list[MockSwitch]:
"""Return mocked toggle entities."""
from tests.components.switch.common import get_mock_switch_entities
# pylint: disable-next=import-outside-toplevel
from .switch.common import get_mock_switch_entities

return get_mock_switch_entities()


@pytest.fixture
def mock_legacy_device_scanner() -> MockScanner:
"""Return mocked legacy device scanner entity."""
from tests.components.device_tracker.common import MockScanner
# pylint: disable-next=import-outside-toplevel
from .device_tracker.common import MockScanner

return MockScanner()


@pytest.fixture
def mock_legacy_device_tracker_setup() -> Callable[[HomeAssistant, MockScanner], None]:
"""Return setup callable for legacy device tracker setup."""
from tests.components.device_tracker.common import mock_legacy_device_tracker_setup
# pylint: disable-next=import-outside-toplevel
from .device_tracker.common import mock_legacy_device_tracker_setup

return mock_legacy_device_tracker_setup
2 changes: 1 addition & 1 deletion tests/test_backports.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
functools as backports_functools,
)

from tests.common import import_and_test_deprecated_alias
from .common import import_and_test_deprecated_alias


@pytest.mark.parametrize(
Expand Down
2 changes: 1 addition & 1 deletion tests/test_block_async_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from homeassistant import block_async_io
from homeassistant.core import HomeAssistant

from tests.common import extract_stack_to_frame
from .common import extract_stack_to_frame


async def test_protect_loop_debugger_sleep(caplog: pytest.LogCaptureFixture) -> None:
Expand Down
3 changes: 1 addition & 2 deletions tests/test_config_entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,12 @@
MockPlatform,
async_capture_events,
async_fire_time_changed,
async_get_persistent_notifications,
mock_config_flow,
mock_integration,
mock_platform,
)

from tests.common import async_get_persistent_notifications


@pytest.fixture(autouse=True)
def mock_handlers() -> Generator[None]:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_const.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from homeassistant import const
from homeassistant.components import sensor

from tests.common import (
from .common import (
help_test_all,
import_and_test_deprecated_constant,
import_and_test_deprecated_constant_enum,
Expand Down
5 changes: 4 additions & 1 deletion tests/test_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ async def test_custom_component_name(
assert platform.__package__ == "custom_components.test"

# Test custom components is mounted
# pylint: disable-next=import-outside-toplevel
from custom_components.test_package import TEST

assert TEST == 5
Expand Down Expand Up @@ -1247,14 +1248,16 @@ def test_import_executor_default(hass: HomeAssistant) -> None:
assert built_in_comp.import_executor is True


async def test_config_folder_not_in_path(hass):
async def test_config_folder_not_in_path() -> None:
"""Test that config folder is not in path."""

# Verify that we are unable to import this file from top level
with pytest.raises(ImportError):
# pylint: disable-next=import-outside-toplevel
import check_config_not_in_path # noqa: F401

# Verify that we are able to load the file with absolute path
# pylint: disable-next=import-outside-toplevel,hass-relative-import
import tests.testing_config.check_config_not_in_path # noqa: F401


Expand Down