Rewrite mfi unittest tests to pytest (#42510)

This commit is contained in:
Adrian Suwała 2020-10-30 09:13:33 +01:00 committed by GitHub
parent f470d1e28d
commit 6011756e90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 224 additions and 219 deletions

View File

@ -1,105 +1,101 @@
"""The tests for the mFi sensor platform.""" """The tests for the mFi sensor platform."""
import unittest
from mficlient.client import FailedToLogin from mficlient.client import FailedToLogin
import pytest
import requests import requests
import homeassistant.components.mfi.sensor as mfi import homeassistant.components.mfi.sensor as mfi
import homeassistant.components.sensor as sensor import homeassistant.components.sensor as sensor_component
from homeassistant.const import TEMP_CELSIUS from homeassistant.const import TEMP_CELSIUS
from homeassistant.setup import setup_component from homeassistant.setup import async_setup_component
import tests.async_mock as mock import tests.async_mock as mock
from tests.common import get_test_home_assistant
PLATFORM = mfi
class TestMfiSensorSetup(unittest.TestCase): COMPONENT = sensor_component
"""Test the mFi sensor platform.""" THING = "sensor"
GOOD_CONFIG = {
PLATFORM = mfi "sensor": {
COMPONENT = sensor "platform": "mfi",
THING = "sensor" "host": "foo",
GOOD_CONFIG = { "port": 6123,
"sensor": { "username": "user",
"platform": "mfi", "password": "pass",
"host": "foo", "ssl": True,
"port": 6123, "verify_ssl": True,
"username": "user",
"password": "pass",
"ssl": True,
"verify_ssl": True,
}
} }
}
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method): async def test_setup_missing_config(hass):
"""Stop everything that was started.""" """Test setup with missing configuration."""
self.hass.stop() with mock.patch("homeassistant.components.mfi.sensor.MFiClient") as mock_client:
@mock.patch("homeassistant.components.mfi.sensor.MFiClient")
def test_setup_missing_config(self, mock_client):
"""Test setup with missing configuration."""
config = {"sensor": {"platform": "mfi"}} config = {"sensor": {"platform": "mfi"}}
assert setup_component(self.hass, "sensor", config) assert await async_setup_component(hass, "sensor", config)
assert not mock_client.called assert not mock_client.called
@mock.patch("homeassistant.components.mfi.sensor.MFiClient")
def test_setup_failed_login(self, mock_client): async def test_setup_failed_login(hass):
"""Test setup with login failure.""" """Test setup with login failure."""
with mock.patch("homeassistant.components.mfi.sensor.MFiClient") as mock_client:
mock_client.side_effect = FailedToLogin mock_client.side_effect = FailedToLogin
assert not self.PLATFORM.setup_platform(self.hass, dict(self.GOOD_CONFIG), None) assert not PLATFORM.setup_platform(hass, dict(GOOD_CONFIG), None)
@mock.patch("homeassistant.components.mfi.sensor.MFiClient")
def test_setup_failed_connect(self, mock_client): async def test_setup_failed_connect(hass):
"""Test setup with connection failure.""" """Test setup with connection failure."""
with mock.patch("homeassistant.components.mfi.sensor.MFiClient") as mock_client:
mock_client.side_effect = requests.exceptions.ConnectionError mock_client.side_effect = requests.exceptions.ConnectionError
assert not self.PLATFORM.setup_platform(self.hass, dict(self.GOOD_CONFIG), None) assert not PLATFORM.setup_platform(hass, dict(GOOD_CONFIG), None)
@mock.patch("homeassistant.components.mfi.sensor.MFiClient")
def test_setup_minimum(self, mock_client): async def test_setup_minimum(hass):
"""Test setup with minimum configuration.""" """Test setup with minimum configuration."""
config = dict(self.GOOD_CONFIG) with mock.patch("homeassistant.components.mfi.sensor.MFiClient") as mock_client:
del config[self.THING]["port"] config = dict(GOOD_CONFIG)
assert setup_component(self.hass, self.COMPONENT.DOMAIN, config) del config[THING]["port"]
self.hass.block_till_done() assert await async_setup_component(hass, COMPONENT.DOMAIN, config)
await hass.async_block_till_done()
assert mock_client.call_count == 1 assert mock_client.call_count == 1
assert mock_client.call_args == mock.call( assert mock_client.call_args == mock.call(
"foo", "user", "pass", port=6443, use_tls=True, verify=True "foo", "user", "pass", port=6443, use_tls=True, verify=True
) )
@mock.patch("homeassistant.components.mfi.sensor.MFiClient")
def test_setup_with_port(self, mock_client): async def test_setup_with_port(hass):
"""Test setup with port.""" """Test setup with port."""
config = dict(self.GOOD_CONFIG) with mock.patch("homeassistant.components.mfi.sensor.MFiClient") as mock_client:
config[self.THING]["port"] = 6123 config = dict(GOOD_CONFIG)
assert setup_component(self.hass, self.COMPONENT.DOMAIN, config) config[THING]["port"] = 6123
self.hass.block_till_done() assert await async_setup_component(hass, COMPONENT.DOMAIN, config)
await hass.async_block_till_done()
assert mock_client.call_count == 1 assert mock_client.call_count == 1
assert mock_client.call_args == mock.call( assert mock_client.call_args == mock.call(
"foo", "user", "pass", port=6123, use_tls=True, verify=True "foo", "user", "pass", port=6123, use_tls=True, verify=True
) )
@mock.patch("homeassistant.components.mfi.sensor.MFiClient")
def test_setup_with_tls_disabled(self, mock_client): async def test_setup_with_tls_disabled(hass):
"""Test setup without TLS.""" """Test setup without TLS."""
config = dict(self.GOOD_CONFIG) with mock.patch("homeassistant.components.mfi.sensor.MFiClient") as mock_client:
del config[self.THING]["port"] config = dict(GOOD_CONFIG)
config[self.THING]["ssl"] = False del config[THING]["port"]
config[self.THING]["verify_ssl"] = False config[THING]["ssl"] = False
assert setup_component(self.hass, self.COMPONENT.DOMAIN, config) config[THING]["verify_ssl"] = False
self.hass.block_till_done() assert await async_setup_component(hass, COMPONENT.DOMAIN, config)
await hass.async_block_till_done()
assert mock_client.call_count == 1 assert mock_client.call_count == 1
assert mock_client.call_args == mock.call( assert mock_client.call_args == mock.call(
"foo", "user", "pass", port=6080, use_tls=False, verify=False "foo", "user", "pass", port=6080, use_tls=False, verify=False
) )
@mock.patch("homeassistant.components.mfi.sensor.MFiClient")
@mock.patch("homeassistant.components.mfi.sensor.MfiSensor") async def test_setup_adds_proper_devices(hass):
def test_setup_adds_proper_devices(self, mock_sensor, mock_client): """Test if setup adds devices."""
"""Test if setup adds devices.""" with mock.patch(
"homeassistant.components.mfi.sensor.MFiClient"
) as mock_client, mock.patch(
"homeassistant.components.mfi.sensor.MfiSensor"
) as mock_sensor:
ports = { ports = {
i: mock.MagicMock(model=model) for i, model in enumerate(mfi.SENSOR_MODELS) i: mock.MagicMock(model=model) for i, model in enumerate(mfi.SENSOR_MODELS)
} }
@ -107,82 +103,90 @@ class TestMfiSensorSetup(unittest.TestCase):
mock_client.return_value.get_devices.return_value = [ mock_client.return_value.get_devices.return_value = [
mock.MagicMock(ports=ports) mock.MagicMock(ports=ports)
] ]
assert setup_component(self.hass, sensor.DOMAIN, self.GOOD_CONFIG) assert await async_setup_component(hass, COMPONENT.DOMAIN, GOOD_CONFIG)
self.hass.block_till_done() await hass.async_block_till_done()
for ident, port in ports.items(): for ident, port in ports.items():
if ident != "bad": if ident != "bad":
mock_sensor.assert_any_call(port, self.hass) mock_sensor.assert_any_call(port, hass)
assert mock.call(ports["bad"], self.hass) not in mock_sensor.mock_calls assert mock.call(ports["bad"], hass) not in mock_sensor.mock_calls
class TestMfiSensor(unittest.TestCase): @pytest.fixture(name="port")
"""Test for mFi sensor platform.""" def port_fixture():
"""Port fixture."""
return mock.MagicMock()
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.port = mock.MagicMock()
self.sensor = mfi.MfiSensor(self.port, self.hass)
def teardown_method(self, method): @pytest.fixture(name="sensor")
"""Stop everything that was started.""" def sensor_fixture(hass, port):
self.hass.stop() """Sensor fixture."""
return mfi.MfiSensor(port, hass)
def test_name(self):
"""Test the name."""
assert self.port.label == self.sensor.name
def test_uom_temp(self): async def test_name(port, sensor):
"""Test the UOM temperature.""" """Test the name."""
self.port.tag = "temperature" assert port.label == sensor.name
assert TEMP_CELSIUS == self.sensor.unit_of_measurement
def test_uom_power(self):
"""Test the UOEM power."""
self.port.tag = "active_pwr"
assert "Watts" == self.sensor.unit_of_measurement
def test_uom_digital(self): async def test_uom_temp(port, sensor):
"""Test the UOM digital input.""" """Test the UOM temperature."""
self.port.model = "Input Digital" port.tag = "temperature"
assert "State" == self.sensor.unit_of_measurement assert TEMP_CELSIUS == sensor.unit_of_measurement
def test_uom_unknown(self):
"""Test the UOM."""
self.port.tag = "balloons"
assert "balloons" == self.sensor.unit_of_measurement
def test_uom_uninitialized(self): async def test_uom_power(port, sensor):
"""Test that the UOM defaults if not initialized.""" """Test the UOEM power."""
type(self.port).tag = mock.PropertyMock(side_effect=ValueError) port.tag = "active_pwr"
assert "State" == self.sensor.unit_of_measurement assert sensor.unit_of_measurement == "Watts"
def test_state_digital(self):
"""Test the digital input."""
self.port.model = "Input Digital"
self.port.value = 0
assert mfi.STATE_OFF == self.sensor.state
self.port.value = 1
assert mfi.STATE_ON == self.sensor.state
self.port.value = 2
assert mfi.STATE_ON == self.sensor.state
def test_state_digits(self): async def test_uom_digital(port, sensor):
"""Test the state of digits.""" """Test the UOM digital input."""
self.port.tag = "didyoucheckthedict?" port.model = "Input Digital"
self.port.value = 1.25 assert sensor.unit_of_measurement == "State"
with mock.patch.dict(mfi.DIGITS, {"didyoucheckthedict?": 1}):
assert 1.2 == self.sensor.state
with mock.patch.dict(mfi.DIGITS, {}):
assert 1.0 == self.sensor.state
def test_state_uninitialized(self):
"""Test the state of uninitialized sensors."""
type(self.port).tag = mock.PropertyMock(side_effect=ValueError)
assert mfi.STATE_OFF == self.sensor.state
def test_update(self): async def test_uom_unknown(port, sensor):
"""Test the update.""" """Test the UOM."""
self.sensor.update() port.tag = "balloons"
assert self.port.refresh.call_count == 1 assert sensor.unit_of_measurement == "balloons"
assert self.port.refresh.call_args == mock.call()
async def test_uom_uninitialized(port, sensor):
"""Test that the UOM defaults if not initialized."""
type(port).tag = mock.PropertyMock(side_effect=ValueError)
assert sensor.unit_of_measurement == "State"
async def test_state_digital(port, sensor):
"""Test the digital input."""
port.model = "Input Digital"
port.value = 0
assert mfi.STATE_OFF == sensor.state
port.value = 1
assert mfi.STATE_ON == sensor.state
port.value = 2
assert mfi.STATE_ON == sensor.state
async def test_state_digits(port, sensor):
"""Test the state of digits."""
port.tag = "didyoucheckthedict?"
port.value = 1.25
with mock.patch.dict(mfi.DIGITS, {"didyoucheckthedict?": 1}):
assert sensor.state == 1.2
with mock.patch.dict(mfi.DIGITS, {}):
assert sensor.state == 1.0
async def test_state_uninitialized(port, sensor):
"""Test the state of uninitialized sensorfs."""
type(port).tag = mock.PropertyMock(side_effect=ValueError)
assert mfi.STATE_OFF == sensor.state
async def test_update(port, sensor):
"""Test the update."""
sensor.update()
assert port.refresh.call_count == 1
assert port.refresh.call_args == mock.call()

View File

@ -1,44 +1,35 @@
"""The tests for the mFi switch platform.""" """The tests for the mFi switch platform."""
import unittest import pytest
import homeassistant.components.mfi.switch as mfi import homeassistant.components.mfi.switch as mfi
import homeassistant.components.switch as switch import homeassistant.components.switch as switch_component
from homeassistant.setup import setup_component from homeassistant.setup import async_setup_component
import tests.async_mock as mock import tests.async_mock as mock
from tests.common import get_test_home_assistant
PLATFORM = mfi
class TestMfiSwitchSetup(unittest.TestCase): COMPONENT = switch_component
"""Test the mFi switch.""" THING = "switch"
GOOD_CONFIG = {
PLATFORM = mfi "switch": {
COMPONENT = switch "platform": "mfi",
THING = "switch" "host": "foo",
GOOD_CONFIG = { "port": 6123,
"switch": { "username": "user",
"platform": "mfi", "password": "pass",
"host": "foo", "ssl": True,
"port": 6123, "verify_ssl": True,
"username": "user",
"password": "pass",
"ssl": True,
"verify_ssl": True,
}
} }
}
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method): async def test_setup_adds_proper_devices(hass):
"""Stop everything that was started.""" """Test if setup adds devices."""
self.hass.stop() with mock.patch(
"homeassistant.components.mfi.switch.MFiClient"
@mock.patch("homeassistant.components.mfi.switch.MFiClient") ) as mock_client, mock.patch(
@mock.patch("homeassistant.components.mfi.switch.MfiSwitch") "homeassistant.components.mfi.switch.MfiSwitch"
def test_setup_adds_proper_devices(self, mock_switch, mock_client): ) as mock_switch:
"""Test if setup adds devices."""
ports = { ports = {
i: mock.MagicMock(model=model) for i, model in enumerate(mfi.SWITCH_MODELS) i: mock.MagicMock(model=model) for i, model in enumerate(mfi.SWITCH_MODELS)
} }
@ -47,74 +38,84 @@ class TestMfiSwitchSetup(unittest.TestCase):
mock_client.return_value.get_devices.return_value = [ mock_client.return_value.get_devices.return_value = [
mock.MagicMock(ports=ports) mock.MagicMock(ports=ports)
] ]
assert setup_component(self.hass, switch.DOMAIN, self.GOOD_CONFIG) assert await async_setup_component(hass, COMPONENT.DOMAIN, GOOD_CONFIG)
self.hass.block_till_done() await hass.async_block_till_done()
for ident, port in ports.items(): for ident, port in ports.items():
if ident != "bad": if ident != "bad":
mock_switch.assert_any_call(port) mock_switch.assert_any_call(port)
assert mock.call(ports["bad"], self.hass) not in mock_switch.mock_calls assert mock.call(ports["bad"], hass) not in mock_switch.mock_calls
class TestMfiSwitch(unittest.TestCase): @pytest.fixture(name="port")
"""Test for mFi switch platform.""" def port_fixture():
"""Port fixture."""
return mock.MagicMock()
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.port = mock.MagicMock()
self.switch = mfi.MfiSwitch(self.port)
def teardown_method(self, method): @pytest.fixture(name="switch")
"""Stop everything that was started.""" def switch_fixture(port):
self.hass.stop() """Switch fixture."""
return mfi.MfiSwitch(port)
def test_name(self):
"""Test the name."""
assert self.port.label == self.switch.name
def test_update(self): async def test_name(port, switch):
"""Test update.""" """Test the name."""
self.switch.update() assert port.label == switch.name
assert self.port.refresh.call_count == 1
assert self.port.refresh.call_args == mock.call()
def test_update_with_target_state(self):
"""Test update with target state."""
self.switch._target_state = True
self.port.data = {}
self.port.data["output"] = "stale"
self.switch.update()
assert 1.0 == self.port.data["output"]
assert self.switch._target_state is None
self.port.data["output"] = "untouched"
self.switch.update()
assert "untouched" == self.port.data["output"]
def test_turn_on(self): async def test_update(port, switch):
"""Test turn_on.""" """Test update."""
self.switch.turn_on() switch.update()
assert self.port.control.call_count == 1 assert port.refresh.call_count == 1
assert self.port.control.call_args == mock.call(True) assert port.refresh.call_args == mock.call()
assert self.switch._target_state
def test_turn_off(self):
"""Test turn_off."""
self.switch.turn_off()
assert self.port.control.call_count == 1
assert self.port.control.call_args == mock.call(False)
assert not self.switch._target_state
def test_current_power_w(self): async def test_update_with_target_state(port, switch):
"""Test current power.""" """Test update with target state."""
self.port.data = {"active_pwr": 10} # pylint: disable=protected-access
assert 10 == self.switch.current_power_w switch._target_state = True
port.data = {}
port.data["output"] = "stale"
switch.update()
assert port.data["output"] == 1.0
# pylint: disable=protected-access
assert switch._target_state is None
port.data["output"] = "untouched"
switch.update()
assert port.data["output"] == "untouched"
def test_current_power_w_no_data(self):
"""Test current power if there is no data."""
self.port.data = {"notpower": 123}
assert 0 == self.switch.current_power_w
def test_device_state_attributes(self): async def test_turn_on(port, switch):
"""Test the state attributes.""" """Test turn_on."""
self.port.data = {"v_rms": 1.25, "i_rms": 2.75} switch.turn_on()
assert {"volts": 1.2, "amps": 2.8} == self.switch.device_state_attributes assert port.control.call_count == 1
assert port.control.call_args == mock.call(True)
# pylint: disable=protected-access
assert switch._target_state
async def test_turn_off(port, switch):
"""Test turn_off."""
switch.turn_off()
assert port.control.call_count == 1
assert port.control.call_args == mock.call(False)
# pylint: disable=protected-access
assert not switch._target_state
async def test_current_power_w(port, switch):
"""Test current power."""
port.data = {"active_pwr": 10}
assert switch.current_power_w == 10
async def test_current_power_w_no_data(port, switch):
"""Test current power if there is no data."""
port.data = {"notpower": 123}
assert switch.current_power_w == 0
async def test_device_state_attributes(port, switch):
"""Test the state attributes."""
port.data = {"v_rms": 1.25, "i_rms": 2.75}
assert switch.device_state_attributes == {"volts": 1.2, "amps": 2.8}