Attempt to fix CI (#34800)

pull/34786/head
Paulus Schoutsen 2020-04-28 10:31:22 -07:00 committed by GitHub
parent c29c0e7e13
commit 454c5d824a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 224 additions and 244 deletions

View File

@ -11,10 +11,10 @@ import logging
import os
import sys
import threading
from unittest.mock import MagicMock, Mock, patch
import uuid
from aiohttp.test_utils import unused_port as get_test_instance_port # noqa
from asynctest import MagicMock, Mock, patch
from homeassistant import auth, config_entries, core as ha, loader
from homeassistant.auth import (

View File

@ -1,18 +1,15 @@
"""Test Hue bridge."""
from unittest.mock import Mock, patch
from asynctest import CoroutineMock, Mock, patch
import pytest
from homeassistant.components.hue import bridge, errors
from homeassistant.exceptions import ConfigEntryNotReady
from tests.common import mock_coro
async def test_bridge_setup(hass):
"""Test a successful setup."""
entry = Mock()
api = Mock(initialize=mock_coro)
api = Mock(initialize=CoroutineMock())
entry.data = {"host": "1.2.3.4", "username": "mock-username"}
hue_bridge = bridge.HueBridge(hass, entry, False, False)
@ -35,9 +32,7 @@ async def test_bridge_setup_invalid_username(hass):
with patch.object(
bridge, "authenticate_bridge", side_effect=errors.AuthenticationRequired
), patch.object(
hass.config_entries.flow, "async_init", return_value=mock_coro()
) as mock_init:
), patch.object(hass.config_entries.flow, "async_init") as mock_init:
assert await hue_bridge.async_setup() is False
assert len(mock_init.mock_calls) == 1
@ -78,18 +73,16 @@ async def test_reset_unloads_entry_if_setup(hass):
entry.data = {"host": "1.2.3.4", "username": "mock-username"}
hue_bridge = bridge.HueBridge(hass, entry, False, False)
with patch.object(
bridge, "authenticate_bridge", return_value=mock_coro(Mock())
), patch("aiohue.Bridge", return_value=Mock()), patch.object(
hass.config_entries, "async_forward_entry_setup"
) as mock_forward:
with patch.object(bridge, "authenticate_bridge", return_value=Mock()), patch(
"aiohue.Bridge", return_value=Mock()
), patch.object(hass.config_entries, "async_forward_entry_setup") as mock_forward:
assert await hue_bridge.async_setup() is True
assert len(hass.services.async_services()) == 1
assert len(mock_forward.mock_calls) == 3
with patch.object(
hass.config_entries, "async_forward_entry_unload", return_value=mock_coro(True)
hass.config_entries, "async_forward_entry_unload", return_value=True
) as mock_forward:
assert await hue_bridge.async_reset()
@ -99,13 +92,13 @@ async def test_reset_unloads_entry_if_setup(hass):
async def test_handle_unauthorized(hass):
"""Test handling an unauthorized error on update."""
entry = Mock(async_setup=Mock(return_value=mock_coro(Mock())))
entry = Mock(async_setup=CoroutineMock())
entry.data = {"host": "1.2.3.4", "username": "mock-username"}
hue_bridge = bridge.HueBridge(hass, entry, False, False)
with patch.object(
bridge, "authenticate_bridge", return_value=mock_coro(Mock())
), patch("aiohue.Bridge", return_value=Mock()):
with patch.object(bridge, "authenticate_bridge", return_value=Mock()), patch(
"aiohue.Bridge", return_value=Mock()
):
assert await hue_bridge.async_setup() is True
assert hue_bridge.authorized is True

View File

@ -34,12 +34,16 @@ from tests.common import (
mock_device_registry,
mock_mqtt_component,
mock_registry,
mock_storage,
threadsafe_coroutine_factory,
)
from tests.testing_config.custom_components.test.sensor import DEVICE_CLASSES
@pytest.fixture(autouse=True)
def mock_storage(hass_storage):
"""Autouse hass_storage for the TestCase tests."""
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
@ -87,15 +91,12 @@ class TestMQTTComponent(unittest.TestCase):
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_storage = mock_storage()
self.mock_storage.__enter__()
mock_mqtt_component(self.hass)
self.calls = []
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
self.mock_storage.__exit__(None, None, None)
@callback
def record_calls(self, *args):
@ -305,15 +306,12 @@ class TestMQTTCallbacks(unittest.TestCase):
def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_storage = mock_storage()
self.mock_storage.__enter__()
mock_mqtt_client(self.hass)
self.calls = []
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
self.mock_storage.__exit__(None, None, None)
@callback
def record_calls(self, *args):

View File

@ -2,12 +2,18 @@
from unittest.mock import MagicMock, Mock
from asynctest import CoroutineMock, patch
import pytest
import homeassistant.components.mqtt as mqtt
from homeassistant.const import CONF_PASSWORD
from homeassistant.setup import setup_component
from tests.common import get_test_home_assistant, mock_coro, mock_storage
from tests.common import get_test_home_assistant, mock_coro
@pytest.fixture(autouse=True)
def inject_fixture(hass_storage):
"""Inject pytest fixtures."""
class TestMQTT:
@ -16,13 +22,10 @@ class TestMQTT:
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_storage = mock_storage()
self.mock_storage.__enter__()
def teardown_method(self, method):
"""Stop everything that was started."""
self.hass.stop()
self.mock_storage.__exit__(None, None, None)
@patch("passlib.apps.custom_app_context", Mock(return_value=""))
@patch("tempfile.NamedTemporaryFile", Mock(return_value=MagicMock()))

View File

@ -2,6 +2,8 @@
import json
from unittest.mock import ANY, patch
import pytest
import homeassistant.components.mqtt_eventstream as eventstream
from homeassistant.const import EVENT_STATE_CHANGED
from homeassistant.core import State, callback
@ -15,24 +17,25 @@ from tests.common import (
get_test_home_assistant,
mock_mqtt_component,
mock_state_change_event,
mock_storage,
)
@pytest.fixture(autouse=True)
def mock_storage(hass_storage):
"""Autouse hass_storage for the TestCase tests."""
class TestMqttEventStream:
"""Test the MQTT eventstream module."""
def setup_method(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_storage = mock_storage()
self.mock_storage.__enter__()
self.mock_mqtt = mock_mqtt_component(self.hass)
def teardown_method(self):
"""Stop everything that was started."""
self.hass.stop()
self.mock_storage.__exit__(None, None, None)
def add_eventstream(self, sub_topic=None, pub_topic=None, ignore_event=None):
"""Add a mqtt_eventstream component."""

View File

@ -1,6 +1,8 @@
"""The tests for the MQTT statestream component."""
from unittest.mock import ANY, call, patch
import pytest
import homeassistant.components.mqtt_statestream as statestream
from homeassistant.core import State
from homeassistant.setup import setup_component
@ -9,24 +11,25 @@ from tests.common import (
get_test_home_assistant,
mock_mqtt_component,
mock_state_change_event,
mock_storage,
)
@pytest.fixture(autouse=True)
def mock_storage(hass_storage):
"""Autouse hass_storage for the TestCase tests."""
class TestMqttStateStream:
"""Test the MQTT statestream module."""
def setup_method(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.mock_storage = mock_storage()
self.mock_storage.__enter__()
self.mock_mqtt = mock_mqtt_component(self.hass)
def teardown_method(self):
"""Stop everything that was started."""
self.hass.stop()
self.mock_storage.__exit__(None, None, None)
def add_statestream(
self,

View File

@ -1,7 +1,5 @@
"""Unit tests for platform/plant.py."""
import asyncio
from datetime import datetime, timedelta
import unittest
import pytest
@ -15,9 +13,10 @@ from homeassistant.const import (
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.setup import setup_component
from homeassistant.core import State
from homeassistant.setup import async_setup_component
from tests.common import get_test_home_assistant, init_recorder_component
from tests.common import init_recorder_component
GOOD_DATA = {
"moisture": 50,
@ -47,31 +46,16 @@ GOOD_CONFIG = {
}
class _MockState:
def __init__(self, state=None):
self.state = state
class TestPlant(unittest.TestCase):
"""Tests for component "plant"."""
def setUp(self):
"""Create test instance of Home Assistant."""
self.hass = get_test_home_assistant()
self.hass.start()
def tearDown(self):
"""Stop everything that was started."""
self.hass.stop()
@asyncio.coroutine
def test_valid_data(self):
async def test_valid_data(hass):
"""Test processing valid data."""
sensor = plant.Plant("my plant", GOOD_CONFIG)
sensor.hass = self.hass
sensor.entity_id = "sensor.mqtt_plant_battery"
sensor.hass = hass
for reading, value in GOOD_DATA.items():
sensor.state_changed(
GOOD_CONFIG["sensors"][reading], None, _MockState(value)
GOOD_CONFIG["sensors"][reading],
None,
State(GOOD_CONFIG["sensors"][reading], value),
)
assert sensor.state == "ok"
attrib = sensor.state_attributes
@ -80,153 +64,154 @@ class TestPlant(unittest.TestCase):
# the JSON format than in hass
assert attrib[reading] == value
@asyncio.coroutine
def test_low_battery(self):
async def test_low_battery(hass):
"""Test processing with low battery data and limit set."""
sensor = plant.Plant("other plant", GOOD_CONFIG)
sensor.hass = self.hass
sensor.entity_id = "sensor.mqtt_plant_battery"
sensor.hass = hass
assert sensor.state_attributes["problem"] == "none"
sensor.state_changed(
"sensor.mqtt_plant_battery", _MockState(45), _MockState(10)
"sensor.mqtt_plant_battery",
State("sensor.mqtt_plant_battery", 45),
State("sensor.mqtt_plant_battery", 10),
)
assert sensor.state == "problem"
assert sensor.state_attributes["problem"] == "battery low"
def test_initial_states(self):
async def test_initial_states(hass):
"""Test plant initialises attributes if sensor already exists."""
self.hass.states.set(
MOISTURE_ENTITY, 5, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY}
)
hass.states.async_set(MOISTURE_ENTITY, 5, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY})
plant_name = "some_plant"
assert setup_component(
self.hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
self.hass.block_till_done()
state = self.hass.states.get(f"plant.{plant_name}")
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert 5 == state.attributes[plant.READING_MOISTURE]
def test_update_states(self):
async def test_update_states(hass):
"""Test updating the state of a sensor.
Make sure that plant processes this correctly.
"""
plant_name = "some_plant"
assert setup_component(
self.hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
self.hass.states.set(
MOISTURE_ENTITY, 5, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY}
)
self.hass.block_till_done()
state = self.hass.states.get(f"plant.{plant_name}")
hass.states.async_set(MOISTURE_ENTITY, 5, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert STATE_PROBLEM == state.state
assert 5 == state.attributes[plant.READING_MOISTURE]
def test_unavailable_state(self):
async def test_unavailable_state(hass):
"""Test updating the state with unavailable.
Make sure that plant processes this correctly.
"""
plant_name = "some_plant"
assert setup_component(
self.hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
self.hass.states.set(
hass.states.async_set(
MOISTURE_ENTITY, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY}
)
self.hass.block_till_done()
state = self.hass.states.get(f"plant.{plant_name}")
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_PROBLEM
assert state.attributes[plant.READING_MOISTURE] == STATE_UNAVAILABLE
def test_state_problem_if_unavailable(self):
async def test_state_problem_if_unavailable(hass):
"""Test updating the state with unavailable after setting it to valid value.
Make sure that plant processes this correctly.
"""
plant_name = "some_plant"
assert setup_component(
self.hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
self.hass.states.set(
MOISTURE_ENTITY, 42, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY}
)
self.hass.block_till_done()
state = self.hass.states.get(f"plant.{plant_name}")
hass.states.async_set(MOISTURE_ENTITY, 42, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_OK
assert state.attributes[plant.READING_MOISTURE] == 42
self.hass.states.set(
hass.states.async_set(
MOISTURE_ENTITY, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY}
)
self.hass.block_till_done()
state = self.hass.states.get(f"plant.{plant_name}")
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_PROBLEM
assert state.attributes[plant.READING_MOISTURE] == STATE_UNAVAILABLE
@pytest.mark.skipif(
plant.ENABLE_LOAD_HISTORY is False,
reason="tests for loading from DB are unstable, thus"
"this feature is turned of until tests become"
"stable",
)
def test_load_from_db(self):
async def test_load_from_db(hass):
"""Test bootstrapping the brightness history from the database.
This test can should only be executed if the loading of the history
is enabled via plant.ENABLE_LOAD_HISTORY.
"""
init_recorder_component(self.hass)
init_recorder_component(hass)
plant_name = "wise_plant"
for value in [20, 30, 10]:
self.hass.states.set(
hass.states.async_set(
BRIGHTNESS_ENTITY, value, {ATTR_UNIT_OF_MEASUREMENT: "Lux"}
)
self.hass.block_till_done()
await hass.async_block_till_done()
# wait for the recorder to really store the data
self.hass.data[recorder.DATA_INSTANCE].block_till_done()
hass.data[recorder.DATA_INSTANCE].block_till_done()
assert setup_component(
self.hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
self.hass.block_till_done()
await hass.async_block_till_done()
state = self.hass.states.get(f"plant.{plant_name}")
state = hass.states.get(f"plant.{plant_name}")
assert STATE_UNKNOWN == state.state
max_brightness = state.attributes.get(plant.ATTR_MAX_BRIGHTNESS_HISTORY)
assert 30 == max_brightness
def test_brightness_history(self):
async def test_brightness_history(hass):
"""Test the min_brightness check."""
plant_name = "some_plant"
assert setup_component(
self.hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
self.hass.states.set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
self.hass.block_till_done()
state = self.hass.states.get(f"plant.{plant_name}")
hass.states.async_set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert STATE_PROBLEM == state.state
self.hass.states.set(BRIGHTNESS_ENTITY, 600, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
self.hass.block_till_done()
state = self.hass.states.get(f"plant.{plant_name}")
hass.states.async_set(BRIGHTNESS_ENTITY, 600, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert STATE_OK == state.state
self.hass.states.set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
self.hass.block_till_done()
state = self.hass.states.get(f"plant.{plant_name}")
hass.states.async_set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: "lux"})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert STATE_OK == state.state
class TestDailyHistory(unittest.TestCase):
"""Test the DailyHistory helper class."""
def test_no_data(self):
def test_daily_history_no_data(hass):
"""Test with empty history."""
dh = plant.DailyHistory(3)
assert dh.max is None
def test_one_day(self):
def test_daily_history_one_day(hass):
"""Test storing data for the same day."""
dh = plant.DailyHistory(3)
values = [-2, 10, 0, 5, 20]
@ -236,7 +221,8 @@ class TestDailyHistory(unittest.TestCase):
assert 1 == len(dh._days)
assert dh.max == max_value
def test_multiple_days(self):
def test_daily_history_multiple_days(hass):
"""Test storing data for different days."""
dh = plant.DailyHistory(3)
today = datetime.now()

View File

@ -35,7 +35,6 @@ from tests.common import (
MockConfigEntry,
async_fire_time_changed,
async_test_home_assistant,
mock_storage,
)
@ -74,24 +73,22 @@ async def test_setup_with_config(hass):
assert loaded_server.plex_server == mock_plex_server
@pytest.mark.skip
class TestClockedPlex(ClockedTestCase):
"""Create clock-controlled asynctest class."""
@pytest.fixture(autouse=True)
def inject_fixture(self, caplog):
def inject_fixture(self, caplog, hass_storage):
"""Inject pytest fixtures as instance attributes."""
self.caplog = caplog
async def setUp(self):
"""Initialize this test class."""
self.hass = await async_test_home_assistant(self.loop)
self.mock_storage = mock_storage()
self.mock_storage.__enter__()
async def tearDown(self):
"""Clean up the HomeAssistant instance."""
await self.hass.async_stop()
self.mock_storage.__exit__(None, None, None)
async def test_setup_with_config_entry(self):
"""Test setup component with config."""

View File

@ -2,6 +2,7 @@
import copy
from asynctest import ClockedTestCase, patch
import pytest
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.components.plex.const import (
@ -17,7 +18,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_send
from .const import DEFAULT_DATA, DEFAULT_OPTIONS
from .mock_classes import MockPlexServer
from tests.common import MockConfigEntry, async_test_home_assistant, mock_storage
from tests.common import MockConfigEntry, async_test_home_assistant
async def test_new_users_available(hass):
@ -107,19 +108,17 @@ async def test_new_ignored_users_available(hass, caplog):
assert sensor.state == str(len(mock_plex_server.accounts))
@pytest.mark.skip
class TestClockedPlex(ClockedTestCase):
"""Create clock-controlled asynctest class."""
async def setUp(self):
"""Initialize this test class."""
self.hass = await async_test_home_assistant(self.loop)
self.mock_storage = mock_storage()
self.mock_storage.__enter__()
async def tearDown(self):
"""Clean up the HomeAssistant instance."""
await self.hass.async_stop()
self.mock_storage.__exit__(None, None, None)
async def test_mark_sessions_idle(self):
"""Test marking media_players as idle when sessions end."""

View File

@ -28,11 +28,15 @@ from tests.common import (
get_test_home_assistant,
mock_coro,
mock_registry,
mock_storage,
)
from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue
@pytest.fixture(autouse=True)
def mock_storage(hass_storage):
"""Autouse hass_storage for the TestCase tests."""
async def test_valid_device_config(hass, mock_openzwave):
"""Test valid device config."""
device_config = {"light.kitchen": {"ignored": "true"}}
@ -829,8 +833,6 @@ class TestZWaveDeviceEntityValues(unittest.TestCase):
def setUp(self):
"""Initialize values for this testcase class."""
self.hass = get_test_home_assistant()
self.mock_storage = mock_storage()
self.mock_storage.__enter__()
self.hass.start()
self.registry = mock_registry(self.hass)
@ -866,7 +868,6 @@ class TestZWaveDeviceEntityValues(unittest.TestCase):
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
self.mock_storage.__exit__(None, None, None)
@patch.object(zwave, "import_module")
@patch.object(zwave, "discovery")
@ -1199,8 +1200,6 @@ class TestZWaveServices(unittest.TestCase):
def setUp(self):
"""Initialize values for this testcase class."""
self.hass = get_test_home_assistant()
self.mock_storage = mock_storage()
self.mock_storage.__enter__()
self.hass.start()
# Initialize zwave
@ -1216,7 +1215,6 @@ class TestZWaveServices(unittest.TestCase):
self.hass.services.call("zwave", "stop_network", {})
self.hass.block_till_done()
self.hass.stop()
self.mock_storage.__exit__(None, None, None)
def test_add_node(self):
"""Test zwave add_node service."""