Rewrite google_wifi unittest tests to pytest style (#42030)

This commit is contained in:
Daniel 2020-11-13 15:40:46 +01:00 committed by GitHub
parent 976640102f
commit 5de30e19bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,17 +1,13 @@
"""The tests for the Google Wifi platform.""" """The tests for the Google Wifi platform."""
from datetime import datetime, timedelta from datetime import datetime, timedelta
import unittest
import requests_mock
from homeassistant import core as ha
import homeassistant.components.google_wifi.sensor as google_wifi import homeassistant.components.google_wifi.sensor as google_wifi
from homeassistant.const import STATE_UNKNOWN from homeassistant.const import STATE_UNKNOWN
from homeassistant.setup import setup_component from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from tests.async_mock import Mock, patch from tests.async_mock import Mock, patch
from tests.common import assert_setup_component, get_test_home_assistant from tests.common import assert_setup_component, async_fire_time_changed
NAME = "foo" NAME = "foo"
@ -34,33 +30,24 @@ MOCK_DATA_NEXT = (
MOCK_DATA_MISSING = '{"software": {},' '"system": {},' '"wan": {}}' MOCK_DATA_MISSING = '{"software": {},' '"system": {},' '"wan": {}}'
class TestGoogleWifiSetup(unittest.TestCase): async def test_setup_minimum(hass, requests_mock):
"""Tests for setting up the Google Wifi sensor platform."""
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.addCleanup(self.hass.stop)
@requests_mock.Mocker()
def test_setup_minimum(self, mock_req):
"""Test setup with minimum configuration.""" """Test setup with minimum configuration."""
resource = f"http://{google_wifi.DEFAULT_HOST}{google_wifi.ENDPOINT}" resource = f"http://{google_wifi.DEFAULT_HOST}{google_wifi.ENDPOINT}"
mock_req.get(resource, status_code=200) requests_mock.get(resource, status_code=200)
assert setup_component( assert await async_setup_component(
self.hass, hass,
"sensor", "sensor",
{"sensor": {"platform": "google_wifi", "monitored_conditions": ["uptime"]}}, {"sensor": {"platform": "google_wifi", "monitored_conditions": ["uptime"]}},
) )
assert_setup_component(1, "sensor") assert_setup_component(1, "sensor")
@requests_mock.Mocker()
def test_setup_get(self, mock_req): async def test_setup_get(hass, requests_mock):
"""Test setup with full configuration.""" """Test setup with full configuration."""
resource = f"http://localhost{google_wifi.ENDPOINT}" resource = f"http://localhost{google_wifi.ENDPOINT}"
mock_req.get(resource, status_code=200) requests_mock.get(resource, status_code=200)
assert setup_component( assert await async_setup_component(
self.hass, hass,
"sensor", "sensor",
{ {
"sensor": { "sensor": {
@ -81,72 +68,65 @@ class TestGoogleWifiSetup(unittest.TestCase):
assert_setup_component(6, "sensor") assert_setup_component(6, "sensor")
class TestGoogleWifiSensor(unittest.TestCase): def setup_api(data, requests_mock):
"""Tests for Google Wifi sensor platform."""
def setUp(self):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
with requests_mock.Mocker() as mock_req:
self.setup_api(MOCK_DATA, mock_req)
self.addCleanup(self.hass.stop)
def setup_api(self, data, mock_req):
"""Set up API with fake data.""" """Set up API with fake data."""
resource = f"http://localhost{google_wifi.ENDPOINT}" resource = f"http://localhost{google_wifi.ENDPOINT}"
now = datetime(1970, month=1, day=1) now = datetime(1970, month=1, day=1)
sensor_dict = {}
with patch("homeassistant.util.dt.now", return_value=now): with patch("homeassistant.util.dt.now", return_value=now):
mock_req.get(resource, text=data, status_code=200) requests_mock.get(resource, text=data, status_code=200)
conditions = google_wifi.MONITORED_CONDITIONS.keys() conditions = google_wifi.MONITORED_CONDITIONS.keys()
self.api = google_wifi.GoogleWifiAPI("localhost", conditions) api = google_wifi.GoogleWifiAPI("localhost", conditions)
self.name = NAME
self.sensor_dict = {}
for condition, cond_list in google_wifi.MONITORED_CONDITIONS.items(): for condition, cond_list in google_wifi.MONITORED_CONDITIONS.items():
sensor = google_wifi.GoogleWifiSensor(self.api, self.name, condition) sensor_dict[condition] = {
name = f"{self.name}_{condition}" "sensor": google_wifi.GoogleWifiSensor(api, NAME, condition),
units = cond_list[1] "name": f"{NAME}_{condition}",
icon = cond_list[2] "units": cond_list[1],
self.sensor_dict[condition] = { "icon": cond_list[2],
"sensor": sensor,
"name": name,
"units": units,
"icon": icon,
} }
return api, sensor_dict
def fake_delay(self, ha_delay):
def fake_delay(hass, ha_delay):
"""Fake delay to prevent update throttle.""" """Fake delay to prevent update throttle."""
hass_now = dt_util.utcnow() hass_now = dt_util.utcnow()
shifted_time = hass_now + timedelta(seconds=ha_delay) shifted_time = hass_now + timedelta(seconds=ha_delay)
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: shifted_time}) async_fire_time_changed(hass, shifted_time)
def test_name(self):
def test_name(requests_mock):
"""Test the name.""" """Test the name."""
for name in self.sensor_dict: api, sensor_dict = setup_api(MOCK_DATA, requests_mock)
sensor = self.sensor_dict[name]["sensor"] for name in sensor_dict:
test_name = self.sensor_dict[name]["name"] sensor = sensor_dict[name]["sensor"]
test_name = sensor_dict[name]["name"]
assert test_name == sensor.name assert test_name == sensor.name
def test_unit_of_measurement(self):
def test_unit_of_measurement(requests_mock):
"""Test the unit of measurement.""" """Test the unit of measurement."""
for name in self.sensor_dict: api, sensor_dict = setup_api(MOCK_DATA, requests_mock)
sensor = self.sensor_dict[name]["sensor"] for name in sensor_dict:
assert self.sensor_dict[name]["units"] == sensor.unit_of_measurement sensor = sensor_dict[name]["sensor"]
assert sensor_dict[name]["units"] == sensor.unit_of_measurement
def test_icon(self):
def test_icon(requests_mock):
"""Test the icon.""" """Test the icon."""
for name in self.sensor_dict: api, sensor_dict = setup_api(MOCK_DATA, requests_mock)
sensor = self.sensor_dict[name]["sensor"] for name in sensor_dict:
assert self.sensor_dict[name]["icon"] == sensor.icon sensor = sensor_dict[name]["sensor"]
assert sensor_dict[name]["icon"] == sensor.icon
@requests_mock.Mocker()
def test_state(self, mock_req): def test_state(hass, requests_mock):
"""Test the initial state.""" """Test the initial state."""
self.setup_api(MOCK_DATA, mock_req) api, sensor_dict = setup_api(MOCK_DATA, requests_mock)
now = datetime(1970, month=1, day=1) now = datetime(1970, month=1, day=1)
with patch("homeassistant.util.dt.now", return_value=now): with patch("homeassistant.util.dt.now", return_value=now):
for name in self.sensor_dict: for name in sensor_dict:
sensor = self.sensor_dict[name]["sensor"] sensor = sensor_dict[name]["sensor"]
self.fake_delay(2) fake_delay(hass, 2)
sensor.update() sensor.update()
if name == google_wifi.ATTR_LAST_RESTART: if name == google_wifi.ATTR_LAST_RESTART:
assert "1969-12-31 00:00:00" == sensor.state assert "1969-12-31 00:00:00" == sensor.state
@ -157,25 +137,25 @@ class TestGoogleWifiSensor(unittest.TestCase):
else: else:
assert "initial" == sensor.state assert "initial" == sensor.state
@requests_mock.Mocker()
def test_update_when_value_is_none(self, mock_req): def test_update_when_value_is_none(hass, requests_mock):
"""Test state gets updated to unknown when sensor returns no data.""" """Test state gets updated to unknown when sensor returns no data."""
self.setup_api(None, mock_req) api, sensor_dict = setup_api(None, requests_mock)
for name in self.sensor_dict: for name in sensor_dict:
sensor = self.sensor_dict[name]["sensor"] sensor = sensor_dict[name]["sensor"]
self.fake_delay(2) fake_delay(hass, 2)
sensor.update() sensor.update()
assert sensor.state is None assert sensor.state is None
@requests_mock.Mocker()
def test_update_when_value_changed(self, mock_req): def test_update_when_value_changed(hass, requests_mock):
"""Test state gets updated when sensor returns a new status.""" """Test state gets updated when sensor returns a new status."""
self.setup_api(MOCK_DATA_NEXT, mock_req) api, sensor_dict = setup_api(MOCK_DATA_NEXT, requests_mock)
now = datetime(1970, month=1, day=1) now = datetime(1970, month=1, day=1)
with patch("homeassistant.util.dt.now", return_value=now): with patch("homeassistant.util.dt.now", return_value=now):
for name in self.sensor_dict: for name in sensor_dict:
sensor = self.sensor_dict[name]["sensor"] sensor = sensor_dict[name]["sensor"]
self.fake_delay(2) fake_delay(hass, 2)
sensor.update() sensor.update()
if name == google_wifi.ATTR_LAST_RESTART: if name == google_wifi.ATTR_LAST_RESTART:
assert "1969-12-30 00:00:00" == sensor.state assert "1969-12-30 00:00:00" == sensor.state
@ -190,29 +170,34 @@ class TestGoogleWifiSensor(unittest.TestCase):
else: else:
assert "next" == sensor.state assert "next" == sensor.state
@requests_mock.Mocker()
def test_when_api_data_missing(self, mock_req): def test_when_api_data_missing(hass, requests_mock):
"""Test state logs an error when data is missing.""" """Test state logs an error when data is missing."""
self.setup_api(MOCK_DATA_MISSING, mock_req) api, sensor_dict = setup_api(MOCK_DATA_MISSING, requests_mock)
now = datetime(1970, month=1, day=1) now = datetime(1970, month=1, day=1)
with patch("homeassistant.util.dt.now", return_value=now): with patch("homeassistant.util.dt.now", return_value=now):
for name in self.sensor_dict: for name in sensor_dict:
sensor = self.sensor_dict[name]["sensor"] sensor = sensor_dict[name]["sensor"]
self.fake_delay(2) fake_delay(hass, 2)
sensor.update() sensor.update()
assert STATE_UNKNOWN == sensor.state assert STATE_UNKNOWN == sensor.state
def test_update_when_unavailable(self):
def test_update_when_unavailable(requests_mock):
"""Test state updates when Google Wifi unavailable.""" """Test state updates when Google Wifi unavailable."""
self.api.update = Mock( api, sensor_dict = setup_api(None, requests_mock)
"google_wifi.GoogleWifiAPI.update", side_effect=self.update_side_effect() api.update = Mock(
"google_wifi.GoogleWifiAPI.update",
side_effect=update_side_effect(requests_mock),
) )
for name in self.sensor_dict: for name in sensor_dict:
sensor = self.sensor_dict[name]["sensor"] sensor = sensor_dict[name]["sensor"]
sensor.update() sensor.update()
assert sensor.state is None assert sensor.state is None
def update_side_effect(self):
def update_side_effect(requests_mock):
"""Mock representation of update function.""" """Mock representation of update function."""
self.api.data = None api, sensor_dict = setup_api(MOCK_DATA, requests_mock)
self.api.available = False api.data = None
api.available = False