Skip to content

Commit

Permalink
fix: attempt to import yaml config
Browse files Browse the repository at this point in the history
* Add tests
  • Loading branch information
firstof9 committed Jul 16, 2021
1 parent 6e650cb commit e01bb77
Show file tree
Hide file tree
Showing 13 changed files with 248 additions and 35 deletions.
33 changes: 33 additions & 0 deletions .github/workflows/pytest.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: Pytest

on:
push:
pull_request:
schedule:
- cron: "0 7 1-28/7 * *"

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.8, 3.9]

steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements_test.txt
- name: Generate coverage report
run: |
python -m pytest
pip install pytest-cov
pytest ./tests/ --cov=custom_components/nws_alerts/ --cov-report=xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v1
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

*.pyc
.coverage
2 changes: 2 additions & 0 deletions custom_components/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"""For testing"""

36 changes: 14 additions & 22 deletions custom_components/nws_alerts/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
""" NWS Alerts """
import aiohttp
from datetime import timedelta
import logging
from datetime import timedelta

import aiohttp
from async_timeout import timeout
from homeassistant import config_entries
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import (
API_ENDPOINT,
CONF_INTERVAL,
Expand All @@ -23,9 +27,11 @@
_LOGGER = logging.getLogger(__name__)


async def async_setup(hass, config_entry):
async def async_setup(hass: HomeAssistant, config_entry: ConfigType) -> bool:
"""Set up this component using YAML."""
if config_entry.get(DOMAIN) is None:
hass.data.setdefault(DOMAIN, {})

if DOMAIN not in config_entry:
# We get here if the integration is set up using config flow
return True

Expand All @@ -35,33 +41,19 @@ async def async_setup(hass, config_entry):
VERSION,
ISSUE_URL,
)
hass.data.setdefault(DOMAIN, {})

# Setup the data coordinator
coordinator = AlertsDataUpdateCoordinator(
hass,
config_entry.data,
config_entry.data.get(CONF_TIMEOUT),
config_entry.data.get(CONF_INTERVAL),
)

# Fetch initial data so we have data when entities subscribe
await coordinator.async_refresh()

hass.data[DOMAIN][config_entry.entry_id] = {
COORDINATOR: coordinator,
}

hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data={}
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=config_entry,
)
)

return True


async def async_setup_entry(hass, config_entry):
async def async_setup_entry(hass, config_entry) -> bool:
"""Load the saved entities."""
# Print startup message
_LOGGER.info(
Expand Down
21 changes: 16 additions & 5 deletions custom_components/nws_alerts/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
"""Adds config flow for NWS Alerts."""
import aiohttp
from __future__ import annotations

import logging
from typing import Any

import aiohttp
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
from homeassistant import config_entries
from homeassistant.data_entry_flow import FlowResult

from .const import (
API_ENDPOINT,
CONF_INTERVAL,
CONF_TIMEOUT,
CONF_ZONE_ID,
DEFAULT_INTERVAL,
DEFAULT_NAME,
DEFAULT_TIMEOUT,
DOMAIN,
CONF_ZONE_ID,
DEFAULT_NAME,
USER_AGENT,
)

Expand Down Expand Up @@ -87,6 +90,14 @@ def __init__(self):
self._data = {}
self._errors = {}

async def async_step_import(self, user_input: dict[str, Any]) -> FlowResult:
"""Import a config entry."""

result: FlowResult = await self.async_step_user(user_input=user_input)
if errors := result.get("errors"):
return self.async_abort(reason=next(iter(errors.values())))
return result

async def async_step_user(self, user_input={}):
"""Handle a flow initialized by the user."""
self._errors = {}
Expand Down
18 changes: 10 additions & 8 deletions custom_components/nws_alerts/sensor.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import logging

import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.const import CONF_NAME, ATTR_ATTRIBUTION
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import slugify

from .const import (
ATTRIBUTION,
CONF_INTERVAL,
CONF_TIMEOUT,
CONF_ZONE_ID,
COORDINATOR,
DEFAULT_ICON,
DEFAULT_INTERVAL,
DEFAULT_NAME,
CONF_ZONE_ID,
ATTRIBUTION,
DEFAULT_TIMEOUT,
DOMAIN,
COORDINATOR,
)

# ---------------------------------------------------------
Expand All @@ -40,12 +42,12 @@


async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
""" Configuration from yaml """
"""Configuration from yaml"""
async_add_entities([NWSAlertSensor(hass, config)], True)


async def async_setup_entry(hass, entry, async_add_entities):
""" Setup the sensor platform. """
"""Setup the sensor platform."""
async_add_entities([NWSAlertSensor(hass, entry)], True)


Expand Down
5 changes: 5 additions & 0 deletions requirements_test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
black
isort
pytest
pytest-cov
pytest-homeassistant-custom-component
Empty file added tests/__init__.py
Empty file.
9 changes: 9 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Fixtures for tests"""
import pytest

pytest_plugins = "pytest_homeassistant_custom_component"


@pytest.fixture(autouse=True)
def auto_enable_custom_integrations(enable_custom_integrations):
yield
3 changes: 3 additions & 0 deletions tests/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""Constants for tests."""

CONFIG_DATA = {"name": "NWS Alerts", "zone_id": "AZZ540,AZC013"}
81 changes: 81 additions & 0 deletions tests/test_config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""Test for config flow"""
from tests.const import CONFIG_DATA
from unittest.mock import patch
import pytest
from homeassistant import config_entries, data_entry_flow, setup
from pytest_homeassistant_custom_component.common import MockConfigEntry

from custom_components.nws_alerts.const import DOMAIN


@pytest.mark.parametrize(
"input,step_id,title,data",
[
(
{
"name": "Testing Alerts",
"zone_id": "AZZ540,AZC013",
"interval": 5,
"timeout": 120,
},
"user",
"Testing Alerts",
{
"name": "Testing Alerts",
"zone_id": "AZZ540,AZC013",
"interval": 5,
"timeout": 120,
},
),
],
)
async def test_form(
input,
step_id,
title,
data,
hass,
):
"""Test we get the form."""
await setup.async_setup_component(hass, "persistent_notification", {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] == {}
# assert result["title"] == title_1

with patch(
"custom_components.nws_alerts.async_setup", return_value=True
) as mock_setup, patch(
"custom_components.nws_alerts.async_setup_entry",
return_value=True,
) as mock_setup_entry:

result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], input
)

assert result2["type"] == "create_entry"
assert result2["title"] == title
assert result2["data"] == data

await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1


async def test_setup_user(hass):
"""Test that the user setup works"""
with patch("custom_components.nws_alerts.async_setup", return_value=True), patch(
"custom_components.nws_alerts.async_setup_entry",
return_value=True,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=CONFIG_DATA
)
await hass.async_block_till_done()

assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "NWS Alerts"
assert result["data"] == CONFIG_DATA
52 changes: 52 additions & 0 deletions tests/test_init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Tests for init."""

from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from pytest_homeassistant_custom_component.common import MockConfigEntry

from custom_components.nws_alerts.const import DOMAIN
from tests.const import CONFIG_DATA


async def test_setup_entry(
hass,
):
"""Test settting up entities."""
entry = MockConfigEntry(
domain=DOMAIN,
title="NWS Alerts",
data=CONFIG_DATA,
)

entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()

assert len(hass.states.async_entity_ids(SENSOR_DOMAIN)) == 1
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1


async def test_unload_entry(hass):
"""Test unloading entities."""
entry = MockConfigEntry(
domain=DOMAIN,
title="NWS Alerts",
data=CONFIG_DATA,
)

entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()

assert len(hass.states.async_entity_ids(SENSOR_DOMAIN)) == 1
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1

assert await hass.config_entries.async_unload(entries[0].entry_id)
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(SENSOR_DOMAIN)) == 1
assert len(hass.states.async_entity_ids(DOMAIN)) == 0

assert await hass.config_entries.async_remove(entries[0].entry_id)
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids(SENSOR_DOMAIN)) == 0
20 changes: 20 additions & 0 deletions tests/test_sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""Test NWS Alerts Sensors"""
from pytest_homeassistant_custom_component.common import MockConfigEntry

from custom_components.nws_alerts.const import DOMAIN
from tests.const import CONFIG_DATA


async def test_sensor(hass):

entry = MockConfigEntry(
domain=DOMAIN,
title="NWS Alerts",
data=CONFIG_DATA,
)

entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()

assert "nws_alerts" in hass.config.components

0 comments on commit e01bb77

Please sign in to comment.