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 tests and change some objects #262

Merged
merged 5 commits into from
Aug 1, 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
12 changes: 8 additions & 4 deletions custom_components/bermuda/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

from typing import TYPE_CHECKING

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv

Expand All @@ -20,7 +22,7 @@

if TYPE_CHECKING:
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import Config, HomeAssistant
from homeassistant.core import HomeAssistant

# from .const import _LOGGER_SPAM_LESS

Expand All @@ -34,9 +36,11 @@
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)


async def async_setup(hass: HomeAssistant, config: Config): # pylint: disable=unused-argument;
"""Setting up this integration using YAML is not supported."""
return True
# async def async_setup(
# hass: HomeAssistant, config: Config
# ): # pylint: disable=unused-argument;
# """Setting up this integration using YAML is not supported."""
# return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
Expand Down
7 changes: 3 additions & 4 deletions custom_components/bermuda/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.bluetooth import MONOTONIC_TIME, BluetoothServiceInfoBleak
from homeassistant.config_entries import ConfigEntry, OptionsFlowWithConfigEntry
from homeassistant.core import callback
from homeassistant.helpers.selector import selector

Expand Down Expand Up @@ -104,14 +105,12 @@ def async_get_options_flow(config_entry):
# )


class BermudaOptionsFlowHandler(config_entries.OptionsFlow):
class BermudaOptionsFlowHandler(OptionsFlowWithConfigEntry):
"""Config flow options handler for bermuda."""

def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize HACS options flow."""
super().__init__()
self.config_entry = config_entry
self.options = dict(config_entry.options)
super().__init__(config_entry)
agittins marked this conversation as resolved.
Show resolved Hide resolved
self.coordinator: BermudaDataUpdateCoordinator
self.devices: dict[str, BermudaDevice]

Expand Down
28 changes: 28 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@
from unittest.mock import patch

import pytest
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from pytest_homeassistant_custom_component.common import MockConfigEntry

from custom_components.bermuda.const import DOMAIN
from custom_components.bermuda.const import NAME

# from .const import MOCK_OPTIONS
from .const import MOCK_CONFIG

# from custom_components.bermuda import BermudaDataUpdateCoordinator

Expand Down Expand Up @@ -73,3 +82,22 @@ def error_get_data_fixture():
# """Simulate a discovered advertisement for config_flow"""
# with patch("custom_components.bermuda.bluetooth.async_discovered_service_info"):
# return SERVICE_INFOS


@pytest.fixture()
async def mock_bermuda_entry(hass: HomeAssistant):
"""This creates a mock config entry"""
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG, entry_id="test", title=NAME)
config_entry.add_to_hass(hass)
await hass.async_block_till_done()
return config_entry


@pytest.fixture()
async def setup_bermuda_entry(hass: HomeAssistant):
"""This setups a entry so that it can be used."""
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG, entry_id="test", title=NAME)
config_entry.add_to_hass(hass)
await async_setup_component(hass, DOMAIN, {})
assert DOMAIN in hass.data and config_entry.entry_id in hass.data[DOMAIN]
return config_entry
37 changes: 5 additions & 32 deletions tests/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@

from __future__ import annotations

from unittest.mock import patch

import pytest
from homeassistant import config_entries
from homeassistant import data_entry_flow
from homeassistant.core import HomeAssistant

# from homeassistant.core import HomeAssistant # noqa: F401
from homeassistant.data_entry_flow import FlowResultType
Expand All @@ -20,25 +18,6 @@
from .const import MOCK_OPTIONS_GLOBALS


# This fixture bypasses the actual setup of the integration
# since we only want to test the config flow. We test the
# actual functionality of the integration in other test modules.
@pytest.fixture(autouse=True)
def bypass_setup_fixture():
"""Prevent setup."""
with (
patch(
"custom_components.bermuda.async_setup",
return_value=True,
),
patch(
"custom_components.bermuda.async_setup_entry",
return_value=True,
),
):
yield


# Here we simiulate a successful config flow from the backend.
# Note that we use the `bypass_get_data` fixture here because
# we want the config flow validation to succeed during the test.
Expand Down Expand Up @@ -83,16 +62,10 @@ async def test_failed_config_flow(hass, error_on_get_data):


# Our config flow also has an options flow, so we must test it as well.
async def test_options_flow(hass):
async def test_options_flow(hass: HomeAssistant, setup_bermuda_entry: MockConfigEntry):
"""Test an options flow."""
# Create a new MockConfigEntry and add to HASS (we're bypassing config
# flow entirely)
entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG, entry_id="test")
entry.add_to_hass(hass)

# Initialize an options flow
await hass.config_entries.async_setup(entry.entry_id)
result = await hass.config_entries.options.async_init(entry.entry_id)
# Go through options flow
result = await hass.config_entries.options.async_init(setup_bermuda_entry.entry_id)

# Verify that the first options step is a user form
assert result["type"] == FlowResultType.MENU
Expand All @@ -117,4 +90,4 @@ async def test_options_flow(hass):
assert result["title"] == NAME

# Verify that the options were updated
assert entry.options == MOCK_OPTIONS_GLOBALS
assert setup_bermuda_entry.options == MOCK_OPTIONS_GLOBALS
31 changes: 11 additions & 20 deletions tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

from __future__ import annotations

from homeassistant.core import HomeAssistant

# from homeassistant.exceptions import ConfigEntryNotReady
from pytest_homeassistant_custom_component.common import MockConfigEntry

from custom_components.bermuda import async_reload_entry
from custom_components.bermuda import async_setup_entry
from custom_components.bermuda import async_unload_entry
from custom_components.bermuda.const import DOMAIN
from custom_components.bermuda.coordinator import BermudaDataUpdateCoordinator

Expand All @@ -21,28 +20,20 @@
# Home Assistant using the pytest_homeassistant_custom_component plugin.
# Assertions allow you to verify that the return value of whatever is on the left
# side of the assertion matches with the right side.
async def test_setup_unload_and_reload_entry(hass, bypass_get_data):
async def test_setup_unload_and_reload_entry(
hass: HomeAssistant, bypass_get_data, setup_bermuda_entry: MockConfigEntry
):
"""Test entry setup and unload."""
# Create a mock entry so we don't have to go through config flow
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG, entry_id="test")

# Set up the entry and assert that the values
# set during setup are where we expect
# them to be. Because we have patched
# the BermudaDataUpdateCoordinator.async_get_data
# call, no code from custom_components/bermuda/api.py actually runs.
assert await async_setup_entry(hass, config_entry)
assert DOMAIN in hass.data and config_entry.entry_id in hass.data[DOMAIN]
assert isinstance(hass.data[DOMAIN][config_entry.entry_id], BermudaDataUpdateCoordinator)
assert isinstance(hass.data[DOMAIN][setup_bermuda_entry.entry_id], BermudaDataUpdateCoordinator)

# Reload the entry and assert that the data from above is still there
assert await async_reload_entry(hass, config_entry) is None
assert DOMAIN in hass.data and config_entry.entry_id in hass.data[DOMAIN]
assert isinstance(hass.data[DOMAIN][config_entry.entry_id], BermudaDataUpdateCoordinator)
assert await hass.config_entries.async_reload(setup_bermuda_entry.entry_id)
assert DOMAIN in hass.data and setup_bermuda_entry.entry_id in hass.data[DOMAIN]
assert isinstance(hass.data[DOMAIN][setup_bermuda_entry.entry_id], BermudaDataUpdateCoordinator)

# Unload the entry and verify that the data has been removed
assert await async_unload_entry(hass, config_entry)
assert config_entry.entry_id not in hass.data[DOMAIN]
assert await hass.config_entries.async_unload(setup_bermuda_entry.entry_id)
assert setup_bermuda_entry.entry_id not in hass.data[DOMAIN]


async def test_setup_entry_exception(hass, error_on_get_data):
Expand Down
72 changes: 34 additions & 38 deletions tests/test_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,52 +5,48 @@
# from homeassistant.components.switch import SERVICE_TURN_OFF
# from homeassistant.components.switch import SERVICE_TURN_ON
# from homeassistant.const import ATTR_ENTITY_ID
from pytest_homeassistant_custom_component.common import MockConfigEntry

from custom_components.bermuda import async_setup_entry

# from custom_components.bermuda.const import DEFAULT_NAME
from custom_components.bermuda.const import DOMAIN

from .const import MOCK_CONFIG

# from unittest.mock import call
# from unittest.mock import patch


# from custom_components.bermuda.const import SWITCH


async def test_switch_services(hass):
"""Test switch services."""
# Create a mock entry so we don't have to go through config flow
config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG, entry_id="test")
assert await async_setup_entry(hass, config_entry)
await hass.async_block_till_done()

# Functions/objects can be patched directly
# in test code as well and can be used to test
# additional things, like whether a function
# was called or what arguments it was called with
# with patch(
# "custom_components.bermuda.BermudaDataUpdateCoordinator.async_set_title"
# ) as title_func:
# await hass.services.async_call(
# SWITCH,
# SERVICE_TURN_OFF,
# service_data={ATTR_ENTITY_ID: f"{SWITCH}.{DEFAULT_NAME}_{SWITCH}"},
# blocking=True,
# )
# assert title_func.called
# assert title_func.call_args == call("foo")

# title_func.reset_mock()

# await hass.services.async_call(
# SWITCH,
# SERVICE_TURN_ON,
# service_data={ATTR_ENTITY_ID: f"{SWITCH}.{DEFAULT_NAME}_{SWITCH}"},
# blocking=True,
# )
# assert title_func.called
# assert title_func.call_args == call("bar")
# Not currently used - commenting out
# async def test_switch_services(hass: HomeAssistant):
# """Test switch services."""
# # Create a mock entry so we don't have to go through config flow
# config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG, entry_id="test")
# assert await async_setup_entry(hass, config_entry)
# await hass.async_block_till_done()

# Functions/objects can be patched directly
# in test code as well and can be used to test
# additional things, like whether a function
# was called or what arguments it was called with
# with patch(
# "custom_components.bermuda.BermudaDataUpdateCoordinator.async_set_title"
# ) as title_func:
# await hass.services.async_call(
# SWITCH,
# SERVICE_TURN_OFF,
# service_data={ATTR_ENTITY_ID: f"{SWITCH}.{DEFAULT_NAME}_{SWITCH}"},
# blocking=True,
# )
# assert title_func.called
# assert title_func.call_args == call("foo")

# title_func.reset_mock()

# await hass.services.async_call(
# SWITCH,
# SERVICE_TURN_ON,
# service_data={ATTR_ENTITY_ID: f"{SWITCH}.{DEFAULT_NAME}_{SWITCH}"},
# blocking=True,
# )
# assert title_func.called
# assert title_func.call_args == call("bar")